From 147d83a9e1a4a2476547b0d23c4aba19d9e996f6 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 9 Mar 2023 23:18:56 +0100 Subject: [PATCH 01/45] Initial commit --- README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..a33cf90 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# ecoCode-java-test-project +Java project to test the java plugin of ecoCode. From a91d8cc74d828d7ae8d2d2df1a409eee791ec3a1 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 9 Mar 2023 23:32:36 +0100 Subject: [PATCH 02/45] [ISSUE 65] first commit with test files for ecocode java plugin --- .gitignore | 7 + README.md | 34 +- pom.xml | 35 ++ .../java/checks/ArrayCopyCheck.java | 493 ++++++++++++++++++ .../checks/AvoidConcatenateStringsInLoop.java | 32 ++ .../java/checks/AvoidFullSQLRequestCheck.java | 30 ++ ...ingSizeCollectionInForEachLoopIgnored.java | 21 + ...voidGettingSizeCollectionInForLoopBad.java | 20 + ...oidGettingSizeCollectionInForLoopGood.java | 23 + ...GettingSizeCollectionInForLoopIgnored.java | 23 + ...idGettingSizeCollectionInWhileLoopBad.java | 22 + ...dGettingSizeCollectionInWhileLoopGood.java | 24 + ...ttingSizeCollectionInWhileLoopIgnored.java | 24 + .../checks/AvoidMultipleIfElseStatement.java | 38 ++ .../AvoidMultipleIfElseStatementNoIssue.java | 31 ++ .../checks/AvoidRegexPatternNotStatic.java | 11 + .../checks/AvoidSQLRequestInLoopCheck.java | 134 +++++ .../AvoidSetConstantInBatchUpdateCheck.java | 153 ++++++ .../AvoidSpringRepositoryCallInLoopCheck.java | 30 ++ .../checks/AvoidStatementForDMLQueries.java | 20 + .../checks/AvoidUsageOfStaticCollections.java | 19 + .../AvoidUsingGlobalVariablesCheck.java | 21 + ...FreeResourcesOfAutoCloseableInterface.java | 38 ++ .../checks/GoodUsageOfStaticCollections.java | 17 + .../checks/GoodWayConcatenateStringsLoop.java | 33 ++ .../java/checks/IncrementCheck.java | 36 ++ .../InitializeBufferWithAppropriateSize.java | 26 + .../NoFunctionCallWhenDeclaringForLoop.java | 58 +++ .../OptimizeReadFileExceptionCheck.java | 29 ++ .../OptimizeReadFileExceptionCheck2.java | 27 + .../OptimizeReadFileExceptionCheck3.java | 26 + .../OptimizeReadFileExceptionCheck4.java | 25 + .../OptimizeReadFileExceptionCheck5.java | 25 + ...arilyAssignValuesToVariablesTestCheck.java | 78 +++ ...esToVariablesTestCheckWithEmptyReturn.java | 18 + .../java/checks/UseCorrectForLoopCheck.java | 24 + .../java/checks/ValidRegexPattern.java | 12 + .../java/checks/ValidRegexPattern2.java | 12 + .../java/checks/ValidRegexPattern3.java | 16 + 39 files changed, 1743 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 pom.xml create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c56452 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +!.gitignore +!.github/**/*.* +.* +target +*.iml +lib/*.jar +bin \ No newline at end of file diff --git a/README.md b/README.md index a33cf90..458a90d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,32 @@ -# ecoCode-java-test-project -Java project to test the java plugin of ecoCode. +Purpose of this project +--- +To check locally all rules on java language. +To do this : +- first launch local development environment (SonarQube) +- launch sonar maven command to send sonar metrics to local SonarQube +- check if each Java class contains (or not) the rule error defined for this class + +Step 0 : requirements +--- + +launch local environment with tools : +- `/tool_build.sh` +- `/tool_start.sh` (if docker environment already built) +- `/tool_docker-init.sh` (if docker environment not built yet) +check https://localhost:9000 +configure (if docker environment already built) : +- change password of admin user +- check if plugin is installed on "marketPlace" tab on Administration +- create a new profile on each language to test - extend from Sonar WAY +- make this new profile as default +- add all rules "eco-conception" tagged on this new profile + +Step 1 : compile and build +--- + +`mvn clean compile` + +Step 2 : Send Sonar metrics to local SonarQube +--- + +`mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=admin -Dsonar.password=XXX` diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..62aa4ca --- /dev/null +++ b/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + io.ecocode + ecocode-java-plugin-test-project + 0.3.0-SNAPSHOT + + ecoCode Java Sonar Plugin Test Project + + + 11 + ${java.version} + ${java.version} + + UTF-8 + ${encoding} + ${encoding} + + + + + org.springframework.data + spring-data-jpa + 2.7.8 + + + org.springframework + spring-beans + 5.3.25 + + + + \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java new file mode 100644 index 0000000..5e1aa51 --- /dev/null +++ b/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++) { // Noncompliant + dest[i] = src[i]; + } + + // Copy with nested conditions + for (int i = 0; i < len; i++) { // Noncompliant + if(i + 2 < len) { + dest[i] = src[i + 2]; + } + } + + // Copy with nested ELSE conditions + for (int i = 0; i < len; i++) { // Noncompliant + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + } + + // Copy with more nested conditions + for (int i = 0; i < len; i++) { // Noncompliant + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + } + + // Copy nested by try/catch + for (int i = 0; i < len; i++) { // Noncompliant + try { + dest[i] = src[i]; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch and if + for (int i = 0; i < len; i++) { // Noncompliant + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch in catch + for (int i = 0; i < len; i++) { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + } + + // Copy nested by try/catch in finally + for (int i = 0; i < len; i++) { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[i] = src[i]; + } + } + + // 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) { // Noncompliant + dest[++i] = b; + } + + // Copy with nested conditions by foreach + i = -1; + for (boolean b : src) { // Noncompliant + if(b) { + dest[++i] = b; + } + } + + // Copy with nested ELSE conditions by foreach + i = -1; + for (boolean b : src) { // Noncompliant + if(i + 2 >= len) { + i++; + } else { + dest[++i] = b; + } + } + + // Copy with more nested conditions + i = -1; + for (boolean b : src) { // Noncompliant + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[++i] = b; + } + } + } + } + } + + // Copy nested by try/catch + i = -1; + for (boolean b : src) { // Noncompliant + try { + dest[++i] = b; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch and if + i = -1; + for (boolean b : src) { // Noncompliant + try { + if(dest != null) { + dest[++i] = b; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch in catch + i = -1; + for (boolean b : src) { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[++i] = b; + } + } + } + + // Copy nested by try/catch in finally + i = -1; + for (boolean b : src) { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[++i] = b; + } + } + + // Array transformation + i = -1; + for (boolean b : src) { + dest[++i] = transform(b); + } + + // Simple copy + i = 0; + for (boolean b : src) { // Noncompliant + dest[i] = src[i]; + i++; + } + + // Copy with nested conditions + i = 0; + for (boolean b : src) { // Noncompliant + if(b) { + dest[i] = src[i]; + } + i++; + } + + // Copy with nested ELSE conditions + i = 0; + for (boolean b : src) { // Noncompliant + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } + + // Copy with more nested conditions + i = 0; + for (boolean b : src) { // Noncompliant + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + i++; + } + + // Copy nested by try/catch + i = 0; + for (boolean b : src) { // Noncompliant + try { + dest[i] = src[i]; + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } + + // Copy nested by try/catch and if + i = 0; + for (boolean b : src) { // Noncompliant + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } + + // Copy nested by try/catch in catch + i = 0; + for (boolean b : src) { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + i++; + } + + // Copy nested by try/catch in finally + i = 0; + for (boolean b : src) { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[i] = src[i]; + } + i++; + } + + // 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) { // Noncompliant + dest[i] = src[i]; + i++; + } + + // Copy with nested conditions + i = 0; + while (i < len) { // Noncompliant + if(i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } + + // Copy with nested ELSE conditions + i = 0; + while (i < len) { // Noncompliant + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } + + // Copy with more nested conditions + i = 0; + while (i < len) { // Noncompliant + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + i++; + } + + // Copy nested by try/catch and if + i = 0; + while (i < len) { // Noncompliant + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } + + // Copy nested by try/catch in catch + i = 0; + while (i < len) { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + i++; + } + + // 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 { // Noncompliant + dest[i] = src[i]; + i++; + } while (i < len); + + // Copy with nested conditions + i = 0; + do { // Noncompliant + if(i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); + + // Copy with nested ELSE conditions + i = 0; + do { // Noncompliant + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); + + // Copy with more nested conditions + i = 0; + do { // Noncompliant + 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); + + // Copy nested by try/catch and if + i = 0; + do { // Noncompliant + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } while (i < len); + + // Copy nested by try/catch in catch + i = 0; + do { // Noncompliant + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + i++; + } while (i < len); + + // 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/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java new file mode 100644 index 0000000..1d141fc --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java @@ -0,0 +1,32 @@ +package fr.greencodeinitiative.java.checks; + +public class AvoidConcatenateStringsInLoop { + + public String concatenateStrings(String[] strings) { + String result1 = ""; + + for (String string : strings) { + result1 += string; // Noncompliant + } + return result1; + } + + public String concatenateStrings2() { + String result2 = ""; + + for (int i = 0; i < 1000; ++i) { + result2 += "another"; // Noncompliant + } + return result2; + } + + public String concatenateStrings3() { + String result3 = ""; + + for (int i = 0; i < 1000; ++i) { + result3 = result3 + "another"; // Noncompliant + } + return result3; + } + +} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java new file mode 100644 index 0000000..0c4ff7b --- /dev/null +++ b/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 + dummyCall(" sElEcT user fRoM myTable"); + + dummyCall("SELECTABLE 2*2 FROMAGE"); //not sql + dummyCall("SELECT *FROM table"); // Noncompliant + } + + + public void variableSQLrequest() { + String requestNonCompiliant = " SeLeCt * FrOm myTable"; // Noncompliant + 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 + } + + private void dummyCall(String request) { + + } + +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java new file mode 100644 index 0000000..467899d --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java new file mode 100644 index 0000000..2428fb3 --- /dev/null +++ b/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 + System.out.println("numberList.size()"); + } + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java new file mode 100644 index 0000000..fed87f5 --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java new file mode 100644 index 0000000..d9c4d51 --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java new file mode 100644 index 0000000..51b33bd --- /dev/null +++ b/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 + System.out.println("numberList.size()"); + i++; + } + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java new file mode 100644 index 0000000..b88e73a --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java new file mode 100644 index 0000000..62ed1fc --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java new file mode 100644 index 0000000..d84630d --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -0,0 +1,38 @@ +package fr.greencodeinitiative.java.checks; + +class AvoidMultipleIfElseStatementCheck { + AvoidMultipleIfElseStatementCheck(AvoidMultipleIfElseStatementCheck mc) { + } + + public void methodWithMultipleIfElseIf() { + int nb1 = 0; + int nb2 = 10; + + if (nb1 == 1) { // Noncompliant + nb1 = 1; + } else if (nb1 == nb2) { + // + } else if (nb2 == nb1) { + // + } else { + // + } + nb1 = nb2; + } + + public void methodWithMultipleIfElse() { + int nb1 = 0; + int nb2 = 10; + + if (nb1 == 1) { // Noncompliant + nb1 = 1; + } else { + // + } + if (nb1 == 1) { // Noncompliant + nb1 = 1; + } else { + // + } + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java new file mode 100644 index 0000000..60d1029 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java @@ -0,0 +1,31 @@ +package fr.greencodeinitiative.java.checks; + +class AvoidMultipleIfElseStatementNoIssueCheck { + AvoidMultipleIfElseStatementNoIssueCheck(AvoidMultipleIfElseStatementNoIssueCheck mc) { + } + + public void methodWithOneIfElseIf() { + int nb1 = 0; + int nb2 = 10; + + if (nb1 == 1) { + nb1 = 1; + } else if (nb1 == nb2) { + // + } else { + // + } + nb1 = nb2; + } + + public void methodWithOneIfElse() { + int nb1 = 0; + int nb2 = 10; + + if (nb1 == 1) { + nb1 = 1; + } else { + // + } + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java new file mode 100644 index 0000000..8f9d690 --- /dev/null +++ b/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 + return pattern.matcher("foo").find(); + } +} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java new file mode 100644 index 0000000..6365bc9 --- /dev/null +++ b/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 + + // 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 + + // 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 + + // 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/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java new file mode 100644 index 0000000..21e6121 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java @@ -0,0 +1,153 @@ +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.logging.Level; +import java.util.logging.Logger; +import java.util.stream.IntStream; + +class AvoidSetConstantInBatchUpdateCheck { + + Logger logger = Logger.getLogger(""); + + 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 + stmt.setByte(3, (byte) 3); // Noncompliant + stmt.setBytes(4, "v".getBytes()); // Noncompliant + stmt.setShort(5, (short) 5); // Noncompliant + stmt.setInt(6, 6); // Noncompliant + stmt.setLong(7, (long) 7); // Noncompliant + stmt.setLong(7, 7l); // Noncompliant + stmt.setFloat(8, (float) 8.); // Noncompliant + stmt.setFloat(8, 8.f); // Noncompliant + stmt.setDouble(9, 9.); // Noncompliant + stmt.setDouble(9, 9.); // Noncompliant + stmt.setString(10, "10"); // Noncompliant + stmt.setBigDecimal(11, BigDecimal.valueOf(.77)); // Noncompliant + stmt.addBatch(); + } + int[] nr = stmt.executeBatch(); + logger.log(Level.INFO, "{} 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 + stmt.setByte(3, o.getField3()); + stmt.setBytes(4, "v".getBytes()); // Noncompliant + stmt.setShort(5, (short) 5); // Noncompliant + stmt.setInt(6, 6); // Noncompliant + stmt.setLong(7, 7); // Noncompliant + stmt.setFloat(8, (float) 8.); // Noncompliant + stmt.setDouble(9, o.getField4()); + stmt.setString(10, o.getField2()); + stmt.setBigDecimal(11, BigDecimal.valueOf(11)); // Noncompliant + 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 + stmt.setByte(3, o.getField3()); + stmt.setByte(4, Byte.MAX_VALUE); // Noncompliant + stmt.setShort(5, Short.MIN_VALUE); // Noncompliant + stmt.setInt(6, Integer.MAX_VALUE); // Noncompliant + stmt.setLong(7, Long.MIN_VALUE); // Noncompliant + stmt.setFloat(8, Float.MAX_VALUE); // Noncompliant + stmt.setDouble(9, Double.MIN_VALUE); // Noncompliant + stmt.setString(10, o.getField2()); + stmt.setBigDecimal(11, BigDecimal.TEN); // Noncompliant + 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 + stmt.setByte(3, o.getField3()); + stmt.setByte(4, Byte.valueOf((byte) 3)); // Noncompliant + stmt.setShort(5, Short.valueOf((short) 55)); // Noncompliant + stmt.setInt(6, Integer.valueOf("222")); // Noncompliant + stmt.setLong(7, Long.valueOf(0)); // Noncompliant + stmt.setFloat(8, Float.valueOf(.33f)); // Noncompliant + stmt.setDouble(9, Double.valueOf(22)); // Noncompliant + stmt.setString(10, o.getField2()); + stmt.setBigDecimal(11, BigDecimal.valueOf(11)); // Noncompliant + 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/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java new file mode 100644 index 0000000..2b1579a --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -0,0 +1,30 @@ +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}} + if (employee.isPresent()) { + employees.add(employee.get()); + } + } + return employees; + } + + public class Employee { + } + + public interface EmployeeRepository extends JpaRepository { + + } + +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java new file mode 100644 index 0000000..428608f --- /dev/null +++ b/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 + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java new file mode 100644 index 0000000..50eb507 --- /dev/null +++ b/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 + + public static final Set SET = new HashSet(); // Noncompliant + + public static final Map MAP = new HashMap(); // Noncompliant + + public AvoidUsageOfStaticCollections() { + } + +} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java new file mode 100644 index 0000000..689986e --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java @@ -0,0 +1,21 @@ +package fr.greencodeinitiative.java.checks; + +public class AvoidUsingGlobalVariablesCheck { + public static double price = 15.24; // Noncompliant + public static long pages = 1053; // Noncompliant + + public static void main(String[] args) { + double newPrice = AvoidUsingGlobalVariablesCheck.price; + long newPages = AvoidUsingGlobalVariablesCheck.pages; + System.out.println(newPrice); + System.out.println(newPages); + } + static{ // Noncompliant + int a = 4; + } + + public void printingA() { + System.out.println("a"); + } + +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java b/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java new file mode 100644 index 0000000..06dc191 --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java b/src/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java new file mode 100644 index 0000000..8f8e55c --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java new file mode 100644 index 0000000..6f279ed --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java new file mode 100644 index 0000000..302e393 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -0,0 +1,36 @@ +package fr.greencodeinitiative.java.checks; + +class IncrementCheck { + IncrementCheck(IncrementCheck mc) { + } + + int foo1() { + int counter = 0; + return counter++; // Noncompliant + } + + int foo11() { + int counter = 0; + return ++counter; + } + + void foo2(int value) { + int counter = 0; + counter++; // Noncompliant + } + + 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 ; + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java b/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java new file mode 100644 index 0000000..925a8d1 --- /dev/null +++ b/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 + } + + public void testBuilderCompliant() { + StringBuilder stringBuilder = new StringBuilder(16); + } + + public void testBuilderNonCompliant() { + StringBuilder stringBuilder = new StringBuilder(); // Noncompliant + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java new file mode 100644 index 0000000..f4fa54a --- /dev/null +++ b/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 + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + + public void test4() { + for (int i = 0; i < getMyValue(); i++) { // Noncompliant + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + + public void test5() { + for (int i = 0; i < getMyValue(); incrementeMyValue(i)) { // Noncompliant + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + + public void test6() { + for (int i = getMyValue(); i < getMyValue(); i++) { // Noncompliant + System.out.println(i); + boolean b = getMyValue() > 6; + } + } + +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java new file mode 100644 index 0000000..be2bd55 --- /dev/null +++ b/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 + } catch (FileNotFoundException e) { + logger.info(e.getMessage()); + } + //... + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java new file mode 100644 index 0000000..50955d6 --- /dev/null +++ b/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 + logger.info("my log"); + } catch (FileNotFoundException e) { + logger.info(e.getMessage()); + } + //... + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java new file mode 100644 index 0000000..83214c2 --- /dev/null +++ b/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 + logger.info("my log"); + } catch (IOException e) { + logger.info(e.getMessage()); + } + //... + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java new file mode 100644 index 0000000..a4fd950 --- /dev/null +++ b/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 + logger.info("my log"); + } catch (Exception e) { + logger.info(e.getMessage()); + } + //... + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java new file mode 100644 index 0000000..bf27946 --- /dev/null +++ b/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 + logger.info("my log"); + } catch (Throwable e) { + logger.info(e.getMessage()); + } + //... + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java new file mode 100644 index 0000000..3ed0cf7 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java @@ -0,0 +1,78 @@ +package fr.greencodeinitiative.java.checks; + +class UnnecessarilyAssignValuesToVariablesTestCheck { + UnnecessarilyAssignValuesToVariablesTestCheck(UnnecessarilyAssignValuesToVariablesTestCheck mc) { + } + + public int testSwitchCase() throws Exception { + int variableFor = 5; + int variableIf = 5; + int variableWhile = 5; + int variableExp = 5; + int variableReturn = 5; + int variableCLass = 5; + int[] intArray = {10, 20, 30, 40, 50}; + + Exception variableException = new Exception("message"); + int variableNotUse = 5; // Noncompliant + + + variableNotUse = 10; + for (variableFor = 0; variableFor < 5; ++variableFor) { + System.out.println(variableFor); + } + + for (int ia : intArray) { + System.out.println((char) ia); + } + + if (variableIf > 10) { + System.out.println(variableIf); + } + + while (variableWhile > 10) { + System.out.println(variableWhile); + } + + variableExp += 1; + variableNotUse = variableExp; + TestClass testClass = new TestClass(variableCLass); + if (testClass.isTrue()) { + throw variableException; + } + return variableReturn; + } + + private class TestClass { + TestClass(int i) { + ++i; + } + + public boolean isTrue() { + return true; + } + } + + + private int getIntValue() { + return 3; + } + + public int testNonCompliantReturn() { + int i = getIntValue(); // Noncompliant + return i; + } + + public int testCompliantReturn() { + return getIntValue(); + } + + public void testNonCompliantThrow() throws Exception { + Exception exception = new Exception("dummy"); // Noncompliant + throw exception; + } + + public void testCompliantThrow() throws Exception { + throw new Exception("dummy"); + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java new file mode 100644 index 0000000..4dbb952 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java @@ -0,0 +1,18 @@ +package fr.greencodeinitiative.java.checks; + +import java.util.ArrayList; + +class UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn { + UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn(UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn mc) { + } + + public void testSwitchCase() { + + ArrayList lst = new ArrayList(0); + if (lst == null) { + return; + } + System.out.println(lst); + } + +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java new file mode 100644 index 0000000..669f058 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java @@ -0,0 +1,24 @@ +package fr.greencodeinitiative.java.checks; + +import java.util.Arrays; +import java.util.List; + +class UseCorrectForLoopCheck { + UseCorrectForLoopCheck(UseCorrectForLoopCheck mc) { + } + + private final Integer[] intArray = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + private final List intList = Arrays.asList(intArray); + + public void testForEachLoop() { + int dummy = 0; + for (Integer i : intArray) { // Noncompliant + dummy += i; + } + + for (Integer i : intList) { + dummy += i; + } + System.out.println(dummy); + } +} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java b/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java new file mode 100644 index 0000000..5ed3652 --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java b/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java new file mode 100644 index 0000000..d6d9efd --- /dev/null +++ b/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/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java b/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java new file mode 100644 index 0000000..e190734 --- /dev/null +++ b/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(); + } +} From 44728f0c4ced10f193d3e6676031ba48a427414a Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 10 Mar 2023 12:11:39 +0100 Subject: [PATCH 03/45] [ISSUE 65] optimization on ArrayCopyCheck class (to limit some useless errors) --- .../java/checks/ArrayCopyCheck.java | 1033 +++++++++-------- 1 file changed, 547 insertions(+), 486 deletions(-) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 5e1aa51..2794cf9 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -4,490 +4,551 @@ 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++) { // Noncompliant - dest[i] = src[i]; - } - - // Copy with nested conditions - for (int i = 0; i < len; i++) { // Noncompliant - if(i + 2 < len) { - dest[i] = src[i + 2]; - } - } - - // Copy with nested ELSE conditions - for (int i = 0; i < len; i++) { // Noncompliant - if(i + 2 >= len) { - i++; - } else { - dest[i] = src[i + 2]; - } - } - - // Copy with more nested conditions - for (int i = 0; i < len; i++) { // Noncompliant - if(i + 2 < len) { - if(dest != null) { - if(src != null) { - if(i > 1 && i + 2 < src.length) { - dest[i] = src[i + 2]; - } - } - } - } - } - - // Copy nested by try/catch - for (int i = 0; i < len; i++) { // Noncompliant - try { - dest[i] = src[i]; - } catch (RuntimeException e) { - e.printStackTrace(); - } - } - - // Copy nested by try/catch and if - for (int i = 0; i < len; i++) { // Noncompliant - try { - if(dest != null) { - dest[i] = src[i]; - } - } catch (RuntimeException e) { - e.printStackTrace(); - } - } - - // Copy nested by try/catch in catch - for (int i = 0; i < len; i++) { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - if(dest != null) { - dest[i] = src[i]; - } - } - } - - // Copy nested by try/catch in finally - for (int i = 0; i < len; i++) { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - dest[i] = src[i]; - } - } - - // 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) { // Noncompliant - dest[++i] = b; - } - - // Copy with nested conditions by foreach - i = -1; - for (boolean b : src) { // Noncompliant - if(b) { - dest[++i] = b; - } - } - - // Copy with nested ELSE conditions by foreach - i = -1; - for (boolean b : src) { // Noncompliant - if(i + 2 >= len) { - i++; - } else { - dest[++i] = b; - } - } - - // Copy with more nested conditions - i = -1; - for (boolean b : src) { // Noncompliant - if(i + 2 < len) { - if(dest != null) { - if(src != null) { - if(i > 1 && i + 2 < src.length) { - dest[++i] = b; - } - } - } - } - } - - // Copy nested by try/catch - i = -1; - for (boolean b : src) { // Noncompliant - try { - dest[++i] = b; - } catch (RuntimeException e) { - e.printStackTrace(); - } - } - - // Copy nested by try/catch and if - i = -1; - for (boolean b : src) { // Noncompliant - try { - if(dest != null) { - dest[++i] = b; - } - } catch (RuntimeException e) { - e.printStackTrace(); - } - } - - // Copy nested by try/catch in catch - i = -1; - for (boolean b : src) { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - if(dest != null) { - dest[++i] = b; - } - } - } - - // Copy nested by try/catch in finally - i = -1; - for (boolean b : src) { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - dest[++i] = b; - } - } - - // Array transformation - i = -1; - for (boolean b : src) { - dest[++i] = transform(b); - } - - // Simple copy - i = 0; - for (boolean b : src) { // Noncompliant - dest[i] = src[i]; - i++; - } - - // Copy with nested conditions - i = 0; - for (boolean b : src) { // Noncompliant - if(b) { - dest[i] = src[i]; - } - i++; - } - - // Copy with nested ELSE conditions - i = 0; - for (boolean b : src) { // Noncompliant - if(i + 2 >= len) { - i++; - } else { - dest[i] = src[i + 2]; - } - i++; - } - - // Copy with more nested conditions - i = 0; - for (boolean b : src) { // Noncompliant - if(i + 2 < len) { - if(dest != null) { - if(src != null) { - if(i > 1 && i + 2 < src.length) { - dest[i] = src[i + 2]; - } - } - } - } - i++; - } - - // Copy nested by try/catch - i = 0; - for (boolean b : src) { // Noncompliant - try { - dest[i] = src[i]; - } catch (RuntimeException e) { - e.printStackTrace(); - } - i++; - } - - // Copy nested by try/catch and if - i = 0; - for (boolean b : src) { // Noncompliant - try { - if(dest != null) { - dest[i] = src[i]; - } - } catch (RuntimeException e) { - e.printStackTrace(); - } - i++; - } - - // Copy nested by try/catch in catch - i = 0; - for (boolean b : src) { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - if(dest != null) { - dest[i] = src[i]; - } - } - i++; - } - - // Copy nested by try/catch in finally - i = 0; - for (boolean b : src) { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - dest[i] = src[i]; - } - i++; - } - - // 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) { // Noncompliant - dest[i] = src[i]; - i++; - } - - // Copy with nested conditions - i = 0; - while (i < len) { // Noncompliant - if(i + 2 < len) { - dest[i] = src[i + 2]; - } - i++; - } - - // Copy with nested ELSE conditions - i = 0; - while (i < len) { // Noncompliant - if(i + 2 >= len) { - i++; - } else { - dest[i] = src[i + 2]; - } - i++; - } - - // Copy with more nested conditions - i = 0; - while (i < len) { // Noncompliant - if(i + 2 < len) { - if(dest != null) { - if(src != null) { - if(i > 1 && i + 2 < src.length) { - dest[i] = src[i + 2]; - } - } - } - } - i++; - } - - // Copy nested by try/catch and if - i = 0; - while (i < len) { // Noncompliant - try { - if(dest != null) { - dest[i] = src[i]; - } - } catch (RuntimeException e) { - e.printStackTrace(); - } - i++; - } - - // Copy nested by try/catch in catch - i = 0; - while (i < len) { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - if(dest != null) { - dest[i] = src[i]; - } - } - i++; - } - - // 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 { // Noncompliant - dest[i] = src[i]; - i++; - } while (i < len); - - // Copy with nested conditions - i = 0; - do { // Noncompliant - if(i + 2 < len) { - dest[i] = src[i + 2]; - } - i++; - } while (i < len); - - // Copy with nested ELSE conditions - i = 0; - do { // Noncompliant - if(i + 2 >= len) { - i++; - } else { - dest[i] = src[i + 2]; - } - i++; - } while (i < len); - - // Copy with more nested conditions - i = 0; - do { // Noncompliant - 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); - - // Copy nested by try/catch and if - i = 0; - do { // Noncompliant - try { - if(dest != null) { - dest[i] = src[i]; - } - } catch (RuntimeException e) { - e.printStackTrace(); - } - i++; - } while (i < len); - - // Copy nested by try/catch in catch - i = 0; - do { // Noncompliant - try { - dest.toString(); - } catch (RuntimeException e) { - if(dest != null) { - dest[i] = src[i]; - } - } - i++; - } while (i < len); - - // Array transformation - i = 0; - do { - dest[i] = transform(src[i]); - i++; - } while (i < len); - } - - private boolean transform(boolean a) { - return !a; - } - + public void copyArrayOK() { + final int len = 5; + final boolean[] src = new boolean[len]; + + // Copy with clone + boolean[] 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); + + System.out.println(dest); + } + + public void nonRegression() { + final int len = 5; + 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; + } + + System.out.println(a); + } + + 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 + + // Copy with nested conditions + for (int i = 0; i < len; i++) { + if (i + 2 < len) { + dest[i] = src[i + 2]; + } + } // Noncompliant + + // Copy with nested ELSE conditions + for (int i = 0; i < len; i++) { + if (i + 2 >= len) { + System.out.println("just to have a 'if' + 'else'"); + } else { + dest[i] = src[i + 2]; + } + } // Noncompliant + + // 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]; + } else { + System.out.println("just to have a 'else' 1"); + } + } else { + System.out.println("just to have a 'else' 2"); + } + } else { + System.out.println("just to have a 'else' 3"); + } + } + } // Noncompliant + + // Copy nested by try/catch + for (int i = 0; i < len; i++) { + try { + dest[i] = src[i]; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } // Noncompliant + + // 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 + + // Copy nested by try/catch in catch + for (int i = 0; i < len; i++) { + try { + Arrays.toString(dest); + } catch (RuntimeException e) { + e.printStackTrace(); + if (dest != null) { + dest[i] = src[i]; + } + } + } // Noncompliant + + // 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 + + // 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 + + // Copy with nested conditions by foreach + i = -1; + for (boolean b : src) { + if (b) { + dest[++i] = b; + } + } // Noncompliant + + // Copy with nested ELSE conditions by foreach + i = -1; + for (boolean b : src) { + if (i + 2 >= len) { + i++; + } else { + dest[++i] = b; + } + } // Noncompliant + + // 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; + } else { + System.out.println("just to have a 'else' 1"); + } + } else { + System.out.println("just to have a 'else' 2"); + } + } else { + System.out.println("just to have a 'else' 3"); + } + } else { + System.out.println("just to have a 'else' 4"); + } + } // Noncompliant + + // Copy nested by try/catch + i = -1; + for (boolean b : src) { + try { + dest[++i] = b; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } // Noncompliant + + // 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 + + // Copy nested by try/catch in catch + i = -1; + for (boolean b : src) { + try { + if (b) { + Arrays.toString(dest); + } + } catch (RuntimeException e) { + e.printStackTrace(); + if (dest != null) { + dest[++i] = b; + } + } + } // Noncompliant + + // Copy nested by try/catch in finally + i = -1; + for (boolean b : src) { + try { + if (b) { + Arrays.toString(dest); + } + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[++i] = b; + } + } // Noncompliant + + // Array transformation + i = -1; + for (boolean b : src) { + dest[++i] = transform(b); + } + + // Simple copy + i = 0; + for (boolean b : src) { + if (b) { + dest[i] = src[i]; + i++; + } + } // Noncompliant + + // Copy with nested conditions + i = 0; + for (boolean b : src) { + if (b) { + dest[i] = src[i]; + } + i++; + } // Noncompliant + + // Copy with nested ELSE conditions + i = 0; + for (boolean b : src) { + if (b) { + if (i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } + } // Noncompliant + + // Copy with more nested conditions + i = 0; + for (boolean b : src) { + if (b) { + if (i + 2 < len) { + if (dest != null) { + if (src != null) { + if (i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } else { + System.out.println("just to have a 'else' 1"); + } + } else { + System.out.println("just to have a 'else' 2"); + } + } else { + System.out.println("just to have a 'else' 3"); + } + } else { + System.out.println("just to have a 'else' 4"); + } + i++; + } else { + System.out.println("just to have a 'else' 5"); + } + } // Noncompliant + + // Copy nested by try/catch + i = 0; + for (boolean b : src) { + try { + if (b) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } // Noncompliant + + // Copy nested by try/catch and if + i = 0; + for (boolean b : src) { + try { + if (b && dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } // Noncompliant + + // Copy nested by try/catch in catch + i = 0; + for (boolean b : src) { + try { + if (b) { + Arrays.toString(dest); + } + } catch (RuntimeException e) { + e.printStackTrace(); + if (dest != null) { + dest[i] = src[i]; + } + } + i++; + } // Noncompliant + + // Copy nested by try/catch in finally + i = 0; + for (boolean b : src) { + try { + if (b) { + Arrays.toString(dest); + } + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[i] = src[i]; + } + i++; + } // Noncompliant + + // Array transformation + i = 0; + for (boolean b : src) { + if (b) { + 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 + + // Copy with nested conditions + i = 0; + while (i < len) { + if (i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } // Noncompliant + + // Copy with nested ELSE conditions + i = 0; + while (i < len) { + if (i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } // Noncompliant + + // 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]; + } else { + System.out.println("just to have a 'else' 1"); + } + } else { + System.out.println("just to have a 'else' 2"); + } + } else { + System.out.println("just to have a 'else' 3"); + } + } + i++; + } // Noncompliant + + // 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 + + // Copy nested by try/catch in catch + i = 0; + while (i < len) { + try { + Arrays.toString(dest); + } catch (RuntimeException e) { + e.printStackTrace(); + if (dest != null) { + dest[i] = src[i]; + } + } + i++; + } // Noncompliant + + // 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 + + // Copy with nested conditions + i = 0; + do { + if (i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); // Noncompliant + + // Copy with nested ELSE conditions + i = 0; + do { + if (i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); // Noncompliant + + // 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]; + } else { + System.out.println("just to have a 'else' 1"); + } + } else { + System.out.println("just to have a 'else' 2"); + } + } else { + System.out.println("just to have a 'else' 3"); + } + } + i++; + } while (i < len); // Noncompliant + + // 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 + + // Copy nested by try/catch in catch + i = 0; + do { + try { + Arrays.toString(dest); + } catch (RuntimeException e) { + e.printStackTrace(); + if (dest != null) { + dest[i] = src[i]; + } + } + i++; + } while (i < len); // Noncompliant + + // 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 From 89e9e6353c038aa96693562e1afa2a02904f5744 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 10 Mar 2023 12:21:18 +0100 Subject: [PATCH 04/45] [ISSUE 65] optimization on ArrayCopyCheck class (to limit some useless errors) - BIS --- .../java/checks/ArrayCopyCheck.java | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 2794cf9..259b0fb 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -17,7 +17,7 @@ public void copyArrayOK() { // Copy with Arrays.copyOf() dest = Arrays.copyOf(src, src.length); - System.out.println(dest); + System.err.println(dest); } public void nonRegression() { @@ -41,7 +41,7 @@ public void nonRegression() { a = b; } - System.out.println(a); + System.err.println(a); } public void copyWithForLoop() { @@ -64,7 +64,7 @@ public void copyWithForLoop() { // Copy with nested ELSE conditions for (int i = 0; i < len; i++) { if (i + 2 >= len) { - System.out.println("just to have a 'if' + 'else'"); + System.err.println("just to have a 'if' + 'else'"); } else { dest[i] = src[i + 2]; } @@ -78,13 +78,13 @@ public void copyWithForLoop() { if (i > 1 && i + 2 < src.length) { dest[i] = src[i + 2]; } else { - System.out.println("just to have a 'else' 1"); + System.err.println("just to have a 'else' 1"); } } else { - System.out.println("just to have a 'else' 2"); + System.err.println("just to have a 'else' 2"); } } else { - System.out.println("just to have a 'else' 3"); + System.err.println("just to have a 'else' 3"); } } } // Noncompliant @@ -124,7 +124,7 @@ public void copyWithForLoop() { // Copy nested by try/catch in finally for (int i = 0; i < len; i++) { try { - dest.toString(); + Arrays.toString(dest); } catch (RuntimeException e) { e.printStackTrace(); } finally { @@ -176,16 +176,16 @@ public void copyWithForEachLoop() { if (i > 1 && i + 2 < src.length) { dest[++i] = b; } else { - System.out.println("just to have a 'else' 1"); + System.err.println("just to have a 'else' 1"); } } else { - System.out.println("just to have a 'else' 2"); + System.err.println("just to have a 'else' 2"); } } else { - System.out.println("just to have a 'else' 3"); + System.err.println("just to have a 'else' 3"); } } else { - System.out.println("just to have a 'else' 4"); + System.err.println("just to have a 'else' 4"); } } // Noncompliant @@ -287,20 +287,20 @@ public void copyWithForEachLoop() { if (i > 1 && i + 2 < src.length) { dest[i] = src[i + 2]; } else { - System.out.println("just to have a 'else' 1"); + System.err.println("just to have a 'else' 1"); } } else { - System.out.println("just to have a 'else' 2"); + System.err.println("just to have a 'else' 2"); } } else { - System.out.println("just to have a 'else' 3"); + System.err.println("just to have a 'else' 3"); } } else { - System.out.println("just to have a 'else' 4"); + System.err.println("just to have a 'else' 4"); } i++; } else { - System.out.println("just to have a 'else' 5"); + System.err.println("just to have a 'else' 5"); } } // Noncompliant @@ -412,13 +412,13 @@ public void copyWithWhileLoop() { if (i > 1 && i + 2 < src.length) { dest[i] = src[i + 2]; } else { - System.out.println("just to have a 'else' 1"); + System.err.println("just to have a 'else' 1"); } } else { - System.out.println("just to have a 'else' 2"); + System.err.println("just to have a 'else' 2"); } } else { - System.out.println("just to have a 'else' 3"); + System.err.println("just to have a 'else' 3"); } } i++; @@ -500,13 +500,13 @@ public void copyWithDoWhileLoop() { if (i > 1 && i + 2 < src.length) { dest[i] = src[i + 2]; } else { - System.out.println("just to have a 'else' 1"); + System.err.println("just to have a 'else' 1"); } } else { - System.out.println("just to have a 'else' 2"); + System.err.println("just to have a 'else' 2"); } } else { - System.out.println("just to have a 'else' 3"); + System.err.println("just to have a 'else' 3"); } } i++; From 129f981743e5ddd839c9a11094d58adc0cc9fbbc Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 10 Mar 2023 12:55:10 +0100 Subject: [PATCH 05/45] [ISSUE 65] upgrade README.md --- README.md | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 458a90d..8791d6e 100644 --- a/README.md +++ b/README.md @@ -2,31 +2,28 @@ Purpose of this project --- To check locally all rules on java language. To do this : + - first launch local development environment (SonarQube) - launch sonar maven command to send sonar metrics to local SonarQube -- check if each Java class contains (or not) the rule error defined for this class +- on local SonarQube, check if each Java class contains (or not) the rule error defined for this class -Step 0 : requirements +Step 1 : prepare local environment --- -launch local environment with tools : -- `/tool_build.sh` -- `/tool_start.sh` (if docker environment already built) -- `/tool_docker-init.sh` (if docker environment not built yet) -check https://localhost:9000 -configure (if docker environment already built) : -- change password of admin user -- check if plugin is installed on "marketPlace" tab on Administration -- create a new profile on each language to test - extend from Sonar WAY -- make this new profile as default -- add all rules "eco-conception" tagged on this new profile +To launch local environment : please follow https://github.com/green-code-initiative/ecoCode/blob/main/INSTALL.md +(especially SonarQube configuration part) Step 1 : compile and build --- `mvn clean compile` -Step 2 : Send Sonar metrics to local SonarQube +Step 2 : send Sonar metrics to local SonarQube --- `mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=admin -Dsonar.password=XXX` + +Step 3 : check errors +--- +on local SonarQube, check if each Java class contains (or not) the rule error defined for this class +(for example : you can search for tag `eco-conception` rule on a special file) From bc5ab7ed4a5ebccf9aaa021e596e0ac3ac37c5b0 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 11 Mar 2023 22:50:27 +0100 Subject: [PATCH 06/45] add LICENCE.md --- LICENCE.md | 674 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENCE.md diff --git a/LICENCE.md b/LICENCE.md new file mode 100644 index 0000000..20d40b6 --- /dev/null +++ b/LICENCE.md @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file From d5ca9e934cca4cab5ab3ea0932d5abf64359bf0c Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 11 Mar 2023 23:36:45 +0100 Subject: [PATCH 07/45] fix version project --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 62aa4ca..8bf9a4d 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-java-plugin-test-project - 0.3.0-SNAPSHOT + 0.0.1-SNAPSHOT ecoCode Java Sonar Plugin Test Project From e285b39f9d3da7ac63c9b13ecc80ed4a91d774af Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sun, 12 Mar 2023 22:45:46 +0100 Subject: [PATCH 08/45] Add tool scripts --- tool_build.sh | 3 +++ tool_sonar.sh | 4 ++++ 2 files changed, 7 insertions(+) create mode 100755 tool_build.sh create mode 100755 tool_sonar.sh diff --git a/tool_build.sh b/tool_build.sh new file mode 100755 index 0000000..84820a4 --- /dev/null +++ b/tool_build.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +mvn clean package diff --git a/tool_sonar.sh b/tool_sonar.sh new file mode 100755 index 0000000..728a0f5 --- /dev/null +++ b/tool_sonar.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env sh + +# "sonar.login" variable : private TOKEN generated in your local SonarQube during installation +mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=sqa_919e0287178896de96aa019e300e85a93c9acc2d From bfee59ac33d1e6e0d0bfa18e87184fe6845113ab Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sun, 12 Mar 2023 23:02:12 +0100 Subject: [PATCH 09/45] rename tool sonar --- tool_sonar.sh => tool_send_to_sonar.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tool_sonar.sh => tool_send_to_sonar.sh (100%) diff --git a/tool_sonar.sh b/tool_send_to_sonar.sh similarity index 100% rename from tool_sonar.sh rename to tool_send_to_sonar.sh From 362b8f06127987d2e2e965b055d0ff673e6b58be Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sun, 12 Mar 2023 23:06:02 +0100 Subject: [PATCH 10/45] upgrade doc --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8791d6e..c3c5d91 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ Purpose of this project --- + To check locally all rules on java language. To do this : @@ -16,14 +17,15 @@ To launch local environment : please follow https://github.com/green-code-initia Step 1 : compile and build --- -`mvn clean compile` +`./tool_build.sh` Step 2 : send Sonar metrics to local SonarQube --- -`mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=admin -Dsonar.password=XXX` +before, change the token inside script and then launch `./tool_send_to_sonar.sh` Step 3 : check errors --- + on local SonarQube, check if each Java class contains (or not) the rule error defined for this class (for example : you can search for tag `eco-conception` rule on a special file) From 1e49a9cfce1cc8b1525c5306ae78af1eba9d76bc Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 13 Mar 2023 13:55:04 +0100 Subject: [PATCH 11/45] upgrade doc --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c3c5d91..1a77341 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,8 @@ Step 1 : compile and build Step 2 : send Sonar metrics to local SonarQube --- -before, change the token inside script and then launch `./tool_send_to_sonar.sh` +- first : change the token inside script (to give your personal SonarQube token, previously generated, please see install documention) +- secondly : launch `./tool_send_to_sonar.sh` Step 3 : check errors --- From dab4d8bfe093b2c4f7e04a9a0b6c8a2eb94a5160 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 17 Mar 2023 17:13:02 +0100 Subject: [PATCH 12/45] Update source files --- README.md | 2 +- .../java/checks/ArrayCopyCheck.java | 1043 ++++++++--------- .../checks/AvoidConcatenateStringsInLoop.java | 6 +- .../java/checks/AvoidFullSQLRequestCheck.java | 8 +- ...voidGettingSizeCollectionInForLoopBad.java | 2 +- ...idGettingSizeCollectionInWhileLoopBad.java | 2 +- .../checks/AvoidRegexPatternNotStatic.java | 2 +- .../checks/AvoidSQLRequestInLoopCheck.java | 6 +- .../AvoidSetConstantInBatchUpdateCheck.java | 72 +- .../checks/AvoidStatementForDMLQueries.java | 2 +- .../checks/AvoidUsageOfStaticCollections.java | 6 +- .../AvoidUsingGlobalVariablesCheck.java | 6 +- .../java/checks/IncrementCheck.java | 4 +- .../InitializeBufferWithAppropriateSize.java | 4 +- .../NoFunctionCallWhenDeclaringForLoop.java | 8 +- .../OptimizeReadFileExceptionCheck.java | 2 +- .../OptimizeReadFileExceptionCheck2.java | 2 +- .../OptimizeReadFileExceptionCheck3.java | 2 +- .../OptimizeReadFileExceptionCheck4.java | 2 +- .../OptimizeReadFileExceptionCheck5.java | 2 +- ...arilyAssignValuesToVariablesTestCheck.java | 6 +- .../java/checks/UseCorrectForLoopCheck.java | 2 +- 22 files changed, 565 insertions(+), 626 deletions(-) diff --git a/README.md b/README.md index 1a77341..3b45ed0 100644 --- a/README.md +++ b/README.md @@ -29,4 +29,4 @@ Step 3 : check errors --- on local SonarQube, check if each Java class contains (or not) the rule error defined for this class -(for example : you can search for tag `eco-conception` rule on a special file) +(for example : you can search for tag `eco-design` rule on a special file) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 259b0fb..d188905 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -1,554 +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]; - - // Copy with clone - boolean[] 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); - - System.err.println(dest); - } - - public void nonRegression() { - final int len = 5; - 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; - } - - System.err.println(a); - } - - 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 - - // Copy with nested conditions - for (int i = 0; i < len; i++) { - if (i + 2 < len) { - dest[i] = src[i + 2]; - } - } // Noncompliant - - // Copy with nested ELSE conditions - for (int i = 0; i < len; i++) { - if (i + 2 >= len) { - System.err.println("just to have a 'if' + 'else'"); - } else { - dest[i] = src[i + 2]; - } - } // Noncompliant - - // 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]; - } else { - System.err.println("just to have a 'else' 1"); - } - } else { - System.err.println("just to have a 'else' 2"); - } - } else { - System.err.println("just to have a 'else' 3"); - } - } - } // Noncompliant - - // Copy nested by try/catch - for (int i = 0; i < len; i++) { - try { - dest[i] = src[i]; - } catch (RuntimeException e) { - e.printStackTrace(); - } - } // Noncompliant - - // 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 - - // Copy nested by try/catch in catch - for (int i = 0; i < len; i++) { - try { - Arrays.toString(dest); - } catch (RuntimeException e) { - e.printStackTrace(); - if (dest != null) { - dest[i] = src[i]; - } - } - } // Noncompliant - - // Copy nested by try/catch in finally - for (int i = 0; i < len; i++) { - try { - Arrays.toString(dest); - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - dest[i] = src[i]; - } - } // Noncompliant - - // 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 - - // Copy with nested conditions by foreach - i = -1; - for (boolean b : src) { - if (b) { - dest[++i] = b; - } - } // Noncompliant - - // Copy with nested ELSE conditions by foreach - i = -1; - for (boolean b : src) { - if (i + 2 >= len) { - i++; - } else { - dest[++i] = b; - } - } // Noncompliant - - // 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; - } else { - System.err.println("just to have a 'else' 1"); - } - } else { - System.err.println("just to have a 'else' 2"); - } - } else { - System.err.println("just to have a 'else' 3"); - } - } else { - System.err.println("just to have a 'else' 4"); - } - } // Noncompliant - - // Copy nested by try/catch - i = -1; - for (boolean b : src) { - try { - dest[++i] = b; - } catch (RuntimeException e) { - e.printStackTrace(); - } - } // Noncompliant - - // 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 - - // Copy nested by try/catch in catch - i = -1; - for (boolean b : src) { - try { - if (b) { - Arrays.toString(dest); - } - } catch (RuntimeException e) { - e.printStackTrace(); - if (dest != null) { - dest[++i] = b; - } - } - } // Noncompliant - - // Copy nested by try/catch in finally - i = -1; - for (boolean b : src) { - try { - if (b) { - Arrays.toString(dest); - } - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - dest[++i] = b; - } - } // Noncompliant - - // Array transformation - i = -1; - for (boolean b : src) { - dest[++i] = transform(b); - } - - // Simple copy - i = 0; - for (boolean b : src) { - if (b) { - dest[i] = src[i]; - i++; - } - } // Noncompliant - - // Copy with nested conditions - i = 0; - for (boolean b : src) { - if (b) { - dest[i] = src[i]; - } - i++; - } // Noncompliant - - // Copy with nested ELSE conditions - i = 0; - for (boolean b : src) { - if (b) { - if (i + 2 >= len) { - i++; - } else { - dest[i] = src[i + 2]; - } - i++; - } - } // Noncompliant - - // Copy with more nested conditions - i = 0; - for (boolean b : src) { - if (b) { - if (i + 2 < len) { - if (dest != null) { - if (src != null) { - if (i > 1 && i + 2 < src.length) { - dest[i] = src[i + 2]; - } else { - System.err.println("just to have a 'else' 1"); - } - } else { - System.err.println("just to have a 'else' 2"); - } - } else { - System.err.println("just to have a 'else' 3"); - } - } else { - System.err.println("just to have a 'else' 4"); - } - i++; - } else { - System.err.println("just to have a 'else' 5"); - } - } // Noncompliant - - // Copy nested by try/catch - i = 0; - for (boolean b : src) { - try { - if (b) { - dest[i] = src[i]; - } - } catch (RuntimeException e) { - e.printStackTrace(); - } - i++; - } // Noncompliant - - // Copy nested by try/catch and if - i = 0; - for (boolean b : src) { - try { - if (b && dest != null) { - dest[i] = src[i]; - } - } catch (RuntimeException e) { - e.printStackTrace(); - } - i++; - } // Noncompliant - - // Copy nested by try/catch in catch - i = 0; - for (boolean b : src) { - try { - if (b) { - Arrays.toString(dest); - } - } catch (RuntimeException e) { - e.printStackTrace(); - if (dest != null) { - dest[i] = src[i]; - } - } - i++; - } // Noncompliant - - // Copy nested by try/catch in finally - i = 0; - for (boolean b : src) { - try { - if (b) { - Arrays.toString(dest); - } - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - dest[i] = src[i]; - } - i++; - } // Noncompliant - - // Array transformation - i = 0; - for (boolean b : src) { - if (b) { - 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 - - // Copy with nested conditions - i = 0; - while (i < len) { - if (i + 2 < len) { - dest[i] = src[i + 2]; - } - i++; - } // Noncompliant - - // Copy with nested ELSE conditions - i = 0; - while (i < len) { - if (i + 2 >= len) { - i++; - } else { - dest[i] = src[i + 2]; - } - i++; - } // Noncompliant - - // 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]; - } else { - System.err.println("just to have a 'else' 1"); - } - } else { - System.err.println("just to have a 'else' 2"); - } - } else { - System.err.println("just to have a 'else' 3"); - } - } - i++; - } // Noncompliant - - // 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 - - // Copy nested by try/catch in catch - i = 0; - while (i < len) { - try { - Arrays.toString(dest); - } catch (RuntimeException e) { - e.printStackTrace(); - if (dest != null) { - dest[i] = src[i]; - } - } - i++; - } // Noncompliant - - // 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 - - // Copy with nested conditions - i = 0; - do { - if (i + 2 < len) { - dest[i] = src[i + 2]; - } - i++; - } while (i < len); // Noncompliant - - // Copy with nested ELSE conditions - i = 0; - do { - if (i + 2 >= len) { - i++; - } else { - dest[i] = src[i + 2]; - } - i++; - } while (i < len); // Noncompliant - - // 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]; - } else { - System.err.println("just to have a 'else' 1"); - } - } else { - System.err.println("just to have a 'else' 2"); - } - } else { - System.err.println("just to have a 'else' 3"); - } - } - i++; - } while (i < len); // Noncompliant - - // 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 - - // Copy nested by try/catch in catch - i = 0; - do { - try { - Arrays.toString(dest); - } catch (RuntimeException e) { - e.printStackTrace(); - if (dest != null) { - dest[i] = src[i]; - } - } - i++; - } while (i < len); // Noncompliant - - // Array transformation - i = 0; - do { - dest[i] = transform(src[i]); - i++; - } while (i < len); - } - - private boolean transform(boolean a) { - return !a; - } - +import java.util.Collection; +import java.util.Collections; + +class TestClass { + + 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++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + dest[i] = src[i]; + } + + // Copy with nested conditions + for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 < len) { + dest[i] = src[i + 2]; + } + } + + // Copy with nested ELSE conditions + for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + } + + // Copy with more nested conditions + for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + } + + // Copy nested by try/catch + for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest[i] = src[i]; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch and if + for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch in catch + for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + } + + // Copy nested by try/catch in finally + for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[i] = src[i]; + } + } + + // 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + dest[++i] = b; + } + + // Copy with nested conditions by foreach + i = -1; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(b) { + dest[++i] = b; + } + } + + // Copy with nested ELSE conditions by foreach + i = -1; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 >= len) { + i++; + } else { + dest[++i] = b; + } + } + + // Copy with more nested conditions + i = -1; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[++i] = b; + } + } + } + } + } + + // Copy nested by try/catch + i = -1; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest[++i] = b; + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch and if + i = -1; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + if(dest != null) { + dest[++i] = b; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + // Copy nested by try/catch in catch + i = -1; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[++i] = b; + } + } + } + + // Copy nested by try/catch in finally + i = -1; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[++i] = b; + } + } + + // Array transformation + i = -1; + for (boolean b : src) { + dest[++i] = transform(b); + } + + // Simple copy + int i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + dest[i] = src[i]; + i++; + } + + // Copy with nested conditions + i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(b) { + dest[i] = src[i]; + } + i++; + } + + // Copy with nested ELSE conditions + i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } + + // Copy with more nested conditions + i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + i++; + } + + // Copy nested by try/catch + i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest[i] = src[i]; + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } + + // Copy nested by try/catch and if + i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } + + // Copy nested by try/catch in catch + i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + i++; + } + + // Copy nested by try/catch in finally + i = 0; + for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + e.printStackTrace(); + } finally { + dest[i] = src[i]; + } + i++; + } + + // 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + dest[i] = src[i]; + i++; + } + + // Copy with nested conditions + i = 0; + while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } + + // Copy with nested ELSE conditions + i = 0; + while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } + + // Copy with more nested conditions + i = 0; + while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 < len) { + if(dest != null) { + if(src != null) { + if(i > 1 && i + 2 < src.length) { + dest[i] = src[i + 2]; + } + } + } + } + i++; + } + + // Copy nested by try/catch and if + i = 0; + while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } + + // Copy nested by try/catch in catch + i = 0; + while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + i++; + } + + // 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 { // Noncompliant {{Use System.arraycopy to copy arrays}} + dest[i] = src[i]; + i++; + } while (i < len); + + // Copy with nested conditions + i = 0; + do { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 < len) { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); + + // Copy with nested ELSE conditions + i = 0; + do { // Noncompliant {{Use System.arraycopy to copy arrays}} + if(i + 2 >= len) { + i++; + } else { + dest[i] = src[i + 2]; + } + i++; + } while (i < len); + + // Copy with more nested conditions + i = 0; + do { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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); + + // Copy nested by try/catch and if + i = 0; + do { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + if(dest != null) { + dest[i] = src[i]; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + i++; + } while (i < len); + + // Copy nested by try/catch in catch + i = 0; + do { // Noncompliant {{Use System.arraycopy to copy arrays}} + try { + dest.toString(); + } catch (RuntimeException e) { + if(dest != null) { + dest[i] = src[i]; + } + } + i++; + } while (i < len); + + // 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/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java index 1d141fc..c5079eb 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java @@ -6,7 +6,7 @@ public String concatenateStrings(String[] strings) { String result1 = ""; for (String string : strings) { - result1 += string; // Noncompliant + result1 += string; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} } return result1; } @@ -15,7 +15,7 @@ public String concatenateStrings2() { String result2 = ""; for (int i = 0; i < 1000; ++i) { - result2 += "another"; // Noncompliant + result2 += "another"; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} } return result2; } @@ -24,7 +24,7 @@ public String concatenateStrings3() { String result3 = ""; for (int i = 0; i < 1000; ++i) { - result3 = result3 + "another"; // Noncompliant + result3 = result3 + "another"; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} } return result3; } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java index 0c4ff7b..45c277e 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java @@ -5,22 +5,22 @@ class AvoidFullSQLRequestCheck { } public void literalSQLrequest() { - dummyCall(" sElEcT * fRoM myTable"); // Noncompliant + 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 + dummyCall("SELECT *FROM table"); // Noncompliant {{Don't use the query SELECT * FROM}} } public void variableSQLrequest() { - String requestNonCompiliant = " SeLeCt * FrOm myTable"; // Noncompliant + 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 + String requestNonCompiliant_nSpace = "SELECT *FROM table"; // Noncompliant {{Don't use the query SELECT * FROM}} } private void dummyCall(String request) { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java index 2428fb3..f990526 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java @@ -13,7 +13,7 @@ public void badForLoop() { numberList.add(10); numberList.add(20); - for (int i = 0; i < numberList.size(); i++) { // Noncompliant + for (int i = 0; i < numberList.size(); i++) { // Noncompliant {{Avoid getting the size of the collection in the loop}} System.out.println("numberList.size()"); } } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java index 51b33bd..9b6fae7 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java @@ -14,7 +14,7 @@ public void badWhileLoop() { numberList.add(20); int i = 0; - while (i < numberList.size()) { // Noncompliant + while (i < numberList.size()) { // Noncompliant {{Avoid getting the size of the collection in the loop}} System.out.println("numberList.size()"); i++; } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java index 8f9d690..0474e45 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java @@ -5,7 +5,7 @@ public class AvoidRegexPatternNotStatic { public boolean foo() { - final Pattern pattern = Pattern.compile("foo"); // Noncompliant + 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/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java index 6365bc9..4981d0b 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java @@ -54,7 +54,7 @@ public void testWithForLoop() { // create the java statement String query = baseQuery.concat("" + i); Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(query); // Noncompliant + ResultSet rs = st.executeQuery(query); // Noncompliant {{Avoid SQL request in loop}} // iterate through the java resultset while (rs.next()) { @@ -85,7 +85,7 @@ public void testWithForEachLoop() { System.out.println(i); // create the java statement Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(query); // Noncompliant + ResultSet rs = st.executeQuery(query); // Noncompliant {{Avoid SQL request in loop}} // iterate through the java resultset while (rs.next()) { @@ -116,7 +116,7 @@ public void testWithWhileLoop() { // create the java statement Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(query); // Noncompliant + ResultSet rs = st.executeQuery(query); // Noncompliant {{Avoid SQL request in loop}} // iterate through the java resultset while (rs.next()) { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java index 21e6121..e33e7e0 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java @@ -35,19 +35,19 @@ void batchInsertInForLoop(int[] data) throws SQLException { for (int i = 0; i < data.length; i++) { stmt.setInt(1, data[i]); - stmt.setBoolean(2, true); // Noncompliant - stmt.setByte(3, (byte) 3); // Noncompliant - stmt.setBytes(4, "v".getBytes()); // Noncompliant - stmt.setShort(5, (short) 5); // Noncompliant - stmt.setInt(6, 6); // Noncompliant - stmt.setLong(7, (long) 7); // Noncompliant - stmt.setLong(7, 7l); // Noncompliant - stmt.setFloat(8, (float) 8.); // Noncompliant - stmt.setFloat(8, 8.f); // Noncompliant - stmt.setDouble(9, 9.); // Noncompliant - stmt.setDouble(9, 9.); // Noncompliant - stmt.setString(10, "10"); // Noncompliant - stmt.setBigDecimal(11, BigDecimal.valueOf(.77)); // Noncompliant + stmt.setBoolean(2, true); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setByte(3, (byte) 3); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setBytes(4, "v".getBytes()); // 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(); @@ -62,16 +62,16 @@ int[] batchInsertInForeachLoop(DummyClass[] data) throws SQLException { PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (DummyClass o : data) { stmt.setInt(1, o.getField1()); - stmt.setBoolean(2, Boolean.valueOf("false")); // Noncompliant + stmt.setBoolean(2, Boolean.valueOf("false")); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); - stmt.setBytes(4, "v".getBytes()); // Noncompliant - stmt.setShort(5, (short) 5); // Noncompliant - stmt.setInt(6, 6); // Noncompliant - stmt.setLong(7, 7); // Noncompliant - stmt.setFloat(8, (float) 8.); // Noncompliant + stmt.setBytes(4, "v".getBytes()); // 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 + stmt.setBigDecimal(11, BigDecimal.valueOf(11)); // Noncompliant {{Avoid setting constants in batch update}} stmt.addBatch(); } return stmt.executeBatch(); @@ -87,16 +87,16 @@ int[] batchInsertInWhileLoop2(DummyClass[] data) throws SQLException { while (i < data.length) { DummyClass o = data[i]; stmt.setInt(1, o.getField1()); - stmt.setBoolean(2, Boolean.TRUE); // Noncompliant + stmt.setBoolean(2, Boolean.TRUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); - stmt.setByte(4, Byte.MAX_VALUE); // Noncompliant - stmt.setShort(5, Short.MIN_VALUE); // Noncompliant - stmt.setInt(6, Integer.MAX_VALUE); // Noncompliant - stmt.setLong(7, Long.MIN_VALUE); // Noncompliant - stmt.setFloat(8, Float.MAX_VALUE); // Noncompliant - stmt.setDouble(9, Double.MIN_VALUE); // Noncompliant + stmt.setByte(4, Byte.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 + stmt.setBigDecimal(11, BigDecimal.TEN); // Noncompliant {{Avoid setting constants in batch update}} stmt.addBatch(); i++; } @@ -114,16 +114,16 @@ int[] batchInsertInWhileLoop(DummyClass[] data) throws SQLException { do { DummyClass o = data[i]; stmt.setInt(1, o.getField1()); - stmt.setBoolean(2, Boolean.valueOf(true)); // Noncompliant + 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 - stmt.setShort(5, Short.valueOf((short) 55)); // Noncompliant - stmt.setInt(6, Integer.valueOf("222")); // Noncompliant - stmt.setLong(7, Long.valueOf(0)); // Noncompliant - stmt.setFloat(8, Float.valueOf(.33f)); // Noncompliant - stmt.setDouble(9, Double.valueOf(22)); // Noncompliant + 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 + stmt.setBigDecimal(11, BigDecimal.valueOf(11)); // Noncompliant {{Avoid setting constants in batch update}} stmt.addBatch(); i++; } while (i < data.length); diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java index 428608f..87204a6 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java @@ -15,6 +15,6 @@ class AvoidStatementForDMLQueries { 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 + 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/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java index 50eb507..ac1b9f0 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java @@ -7,11 +7,11 @@ */ public class AvoidUsageOfStaticCollections { - public static final List LIST = new ArrayList(); // Noncompliant + public static final List LIST = new ArrayList(); // Noncompliant {{Avoid usage of static collections.}} - public static final Set SET = new HashSet(); // Noncompliant + public static final Set SET = new HashSet(); // Noncompliant {{Avoid usage of static collections.}} - public static final Map MAP = new HashMap(); // Noncompliant + public static final Map MAP = new HashMap(); // Noncompliant {{Avoid usage of static collections.}} public AvoidUsageOfStaticCollections() { } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java index 689986e..3dea9e3 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java @@ -1,8 +1,8 @@ package fr.greencodeinitiative.java.checks; public class AvoidUsingGlobalVariablesCheck { - public static double price = 15.24; // Noncompliant - public static long pages = 1053; // Noncompliant + public static double price = 15.24; // Noncompliant {{Avoid using global variables}} + public static long pages = 1053; // Noncompliant {{Avoid using global variables}} public static void main(String[] args) { double newPrice = AvoidUsingGlobalVariablesCheck.price; @@ -10,7 +10,7 @@ public static void main(String[] args) { System.out.println(newPrice); System.out.println(newPages); } - static{ // Noncompliant + static{ // Noncompliant {{Avoid using global variables}} int a = 4; } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java index 302e393..7f5f6cc 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -6,7 +6,7 @@ class IncrementCheck { int foo1() { int counter = 0; - return counter++; // Noncompliant + return counter++; // Noncompliant {{Use ++i instead of i++}} } int foo11() { @@ -16,7 +16,7 @@ int foo11() { void foo2(int value) { int counter = 0; - counter++; // Noncompliant + counter++; // Noncompliant {{Use ++i instead of i++}} } void foo22(int value) { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java b/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java index 925a8d1..a02cc36 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java @@ -13,7 +13,7 @@ public void testBufferCompliant2() { } public void testBufferNonCompliant() { - StringBuffer stringBuffer = new StringBuffer(); // Noncompliant + StringBuffer stringBuffer = new StringBuffer(); // Noncompliant {{Initialize StringBuilder or StringBuffer with appropriate size}} } public void testBuilderCompliant() { @@ -21,6 +21,6 @@ public void testBuilderCompliant() { } public void testBuilderNonCompliant() { - StringBuilder stringBuilder = new StringBuilder(); // Noncompliant + StringBuilder stringBuilder = new StringBuilder(); // Noncompliant {{Initialize StringBuilder or StringBuffer with appropriate size}} } } \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java index f4fa54a..28da0a8 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -28,28 +28,28 @@ public void test2() { } public void test3() { - for (int i = getMyValue(); i < 20; i++) { // Noncompliant + 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 + 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 + 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 + 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; } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java index be2bd55..6991122 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java @@ -20,7 +20,7 @@ public void readPreferences(String filename) { //... InputStream in = null; try { - in = new FileInputStream(filename); // Noncompliant + in = new FileInputStream(filename); // Noncompliant {{Optimize Read File Exceptions}} } catch (FileNotFoundException e) { logger.info(e.getMessage()); } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java index 50955d6..9b0833d 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java @@ -17,7 +17,7 @@ class OptimizeReadFileExceptionCheck2 { public void readPreferences(String filename) throws IOException { //... - try (InputStream in = new FileInputStream(filename)) { // Noncompliant + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} logger.info("my log"); } catch (FileNotFoundException e) { logger.info(e.getMessage()); diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java index 83214c2..18c2344 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java @@ -16,7 +16,7 @@ class OptimizeReadFileExceptionCheck3 { public void readPreferences(String filename) { //... - try (InputStream in = new FileInputStream(filename)) { // Noncompliant + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} logger.info("my log"); } catch (IOException e) { logger.info(e.getMessage()); diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java index a4fd950..3843580 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java @@ -15,7 +15,7 @@ class OptimizeReadFileExceptionCheck4 { public void readPreferences(String filename) { //... - try (InputStream in = new FileInputStream(filename)) { // Noncompliant + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} logger.info("my log"); } catch (Exception e) { logger.info(e.getMessage()); diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java index bf27946..7a0e84a 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java @@ -15,7 +15,7 @@ class OptimizeReadFileExceptionCheck5 { public void readPreferences(String filename) { //... - try (InputStream in = new FileInputStream(filename)) { // Noncompliant + try (InputStream in = new FileInputStream(filename)) { // Noncompliant {{Optimize Read File Exceptions}} logger.info("my log"); } catch (Throwable e) { logger.info(e.getMessage()); diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java index 3ed0cf7..4a59150 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java @@ -14,7 +14,7 @@ public int testSwitchCase() throws Exception { int[] intArray = {10, 20, 30, 40, 50}; Exception variableException = new Exception("message"); - int variableNotUse = 5; // Noncompliant + int variableNotUse = 5; // Noncompliant {{The variable is not assigned}} variableNotUse = 10; @@ -59,7 +59,7 @@ private int getIntValue() { } public int testNonCompliantReturn() { - int i = getIntValue(); // Noncompliant + int i = getIntValue(); // Noncompliant {{Immediately return this expression instead of assigning it to the temporary variable}} return i; } @@ -68,7 +68,7 @@ public int testCompliantReturn() { } public void testNonCompliantThrow() throws Exception { - Exception exception = new Exception("dummy"); // Noncompliant + Exception exception = new Exception("dummy"); // Noncompliant {{Immediately throw this expression instead of assigning it to the temporary variable}} throw exception; } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java index 669f058..dfdde5d 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java @@ -12,7 +12,7 @@ class UseCorrectForLoopCheck { public void testForEachLoop() { int dummy = 0; - for (Integer i : intArray) { // Noncompliant + for (Integer i : intArray) { // Noncompliant {{Avoid the use of Foreach with Arrays}} dummy += i; } From 01504792a74f9b518f26b89433ba7951a63d57f6 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 17 Mar 2023 17:54:23 +0100 Subject: [PATCH 13/45] update source test files --- .../java/checks/ArrayCopyCheck.java | 144 +++++++++--------- .../checks/AvoidMultipleIfElseStatement.java | 12 +- .../AvoidSetConstantInBatchUpdateCheck.java | 31 ++-- .../java/checks/UseCorrectForLoopCheck.java | 4 +- 4 files changed, 94 insertions(+), 97 deletions(-) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index d188905..8d3bcbb 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -48,28 +48,28 @@ public void copyWithForLoop() { boolean[] dest = new boolean[len]; // Simple copy - for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (int i = 0; i < len; i++) { if(i + 2 < len) { if(dest != null) { if(src != null) { @@ -79,19 +79,19 @@ public void copyWithForLoop() { } } } - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch - for (int i = 0; i < len; i++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (int i = 0; i < len; i++) { try { if(dest != null) { dest[i] = src[i]; @@ -99,10 +99,10 @@ public void copyWithForLoop() { } 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++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (int i = 0; i < len; i++) { try { dest.toString(); } catch (RuntimeException e) { @@ -110,10 +110,10 @@ public void copyWithForLoop() { 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++) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (int i = 0; i < len; i++) { try { dest.toString(); } catch (RuntimeException e) { @@ -121,7 +121,7 @@ public void copyWithForLoop() { } finally { dest[i] = src[i]; } - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Array transformation for (int i = 0; i < len; i++) { @@ -136,31 +136,31 @@ public void copyWithForEachLoop() { // Simple copy by foreach int i = -1; - for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { if(i + 2 < len) { if(dest != null) { if(src != null) { @@ -170,21 +170,21 @@ public void copyWithForEachLoop() { } } } - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch i = -1; - for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { try { if(dest != null) { dest[++i] = b; @@ -192,11 +192,11 @@ public void copyWithForEachLoop() { } 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { try { dest.toString(); } catch (RuntimeException e) { @@ -204,11 +204,11 @@ public void copyWithForEachLoop() { dest[++i] = b; } } - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch in finally i = -1; - for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { try { dest.toString(); } catch (RuntimeException e) { @@ -216,7 +216,7 @@ public void copyWithForEachLoop() { } finally { dest[++i] = b; } - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Array transformation i = -1; @@ -226,34 +226,34 @@ public void copyWithForEachLoop() { // Simple copy int i = 0; - for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { if(i + 2 < len) { if(dest != null) { if(src != null) { @@ -264,22 +264,22 @@ public void copyWithForEachLoop() { } } i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch i = 0; - for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { try { if(dest != null) { dest[i] = src[i]; @@ -288,11 +288,11 @@ public void copyWithForEachLoop() { e.printStackTrace(); } i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch in catch i = 0; - for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { try { dest.toString(); } catch (RuntimeException e) { @@ -301,11 +301,11 @@ public void copyWithForEachLoop() { } } i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch in finally i = 0; - for (boolean b : src) { // Noncompliant {{Use System.arraycopy to copy arrays}} + for (boolean b : src) { try { dest.toString(); } catch (RuntimeException e) { @@ -314,7 +314,7 @@ public void copyWithForEachLoop() { dest[i] = src[i]; } i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Array transformation i = 0; @@ -331,34 +331,34 @@ public void copyWithWhileLoop() { // Simple copy int i = 0; - while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + while (i < len) { dest[i] = src[i]; i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy with nested conditions i = 0; - while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + 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) { // Noncompliant {{Use System.arraycopy to copy arrays}} + while (i < len) { if(i + 2 < len) { if(dest != null) { if(src != null) { @@ -369,11 +369,11 @@ public void copyWithWhileLoop() { } } i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch and if i = 0; - while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + while (i < len) { try { if(dest != null) { dest[i] = src[i]; @@ -382,11 +382,11 @@ public void copyWithWhileLoop() { e.printStackTrace(); } i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch in catch i = 0; - while (i < len) { // Noncompliant {{Use System.arraycopy to copy arrays}} + while (i < len) { try { dest.toString(); } catch (RuntimeException e) { @@ -395,7 +395,7 @@ public void copyWithWhileLoop() { } } i++; - } + } // Noncompliant {{Use System.arraycopy to copy arrays}} // Array transformation i = 0; @@ -412,34 +412,34 @@ public void copyWithDoWhileLoop() { // Simple copy int i = 0; - do { // Noncompliant {{Use System.arraycopy to copy arrays}} + do { dest[i] = src[i]; i++; - } while (i < len); + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy with nested conditions i = 0; - do { // Noncompliant {{Use System.arraycopy to copy arrays}} + do { if(i + 2 < len) { dest[i] = src[i + 2]; } i++; - } while (i < len); + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy with nested ELSE conditions i = 0; - do { // Noncompliant {{Use System.arraycopy to copy arrays}} + do { if(i + 2 >= len) { i++; } else { dest[i] = src[i + 2]; } i++; - } while (i < len); + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy with more nested conditions i = 0; - do { // Noncompliant {{Use System.arraycopy to copy arrays}} + do { if(i + 2 < len) { if(dest != null) { if(src != null) { @@ -450,11 +450,11 @@ public void copyWithDoWhileLoop() { } } i++; - } while (i < len); + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch and if i = 0; - do { // Noncompliant {{Use System.arraycopy to copy arrays}} + do { try { if(dest != null) { dest[i] = src[i]; @@ -463,11 +463,11 @@ public void copyWithDoWhileLoop() { e.printStackTrace(); } i++; - } while (i < len); + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} // Copy nested by try/catch in catch i = 0; - do { // Noncompliant {{Use System.arraycopy to copy arrays}} + do { try { dest.toString(); } catch (RuntimeException e) { @@ -476,7 +476,7 @@ public void copyWithDoWhileLoop() { } } i++; - } while (i < len); + } while (i < len); // Noncompliant {{Use System.arraycopy to copy arrays}} // Array transformation i = 0; diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index d84630d..6dbc73d 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -8,7 +8,7 @@ public void methodWithMultipleIfElseIf() { int nb1 = 0; int nb2 = 10; - if (nb1 == 1) { // Noncompliant + if (nb1 == 1) { nb1 = 1; } else if (nb1 == nb2) { // @@ -16,7 +16,7 @@ public void methodWithMultipleIfElseIf() { // } else { // - } + } // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} nb1 = nb2; } @@ -24,15 +24,15 @@ public void methodWithMultipleIfElse() { int nb1 = 0; int nb2 = 10; - if (nb1 == 1) { // Noncompliant + if (nb1 == 1) { nb1 = 1; } else { // - } - if (nb1 == 1) { // Noncompliant + } // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} + if (nb1 == 1) { nb1 = 1; } else { // - } + } // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} } } \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java index e33e7e0..122a48b 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java @@ -1,26 +1,21 @@ 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.logging.Level; -import java.util.logging.Logger; +import java.util.regex.Pattern; import java.util.stream.IntStream; +import java.util.stream.Stream; class AvoidSetConstantInBatchUpdateCheck { - Logger logger = Logger.getLogger(""); - - void literalSQLrequest() throws SQLException { //dirty call + void literalSQLrequest() { //dirty call int x = 0; Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle"); PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?)"); stmt.setInt(1, 101); stmt.setString(2, "Ratan"); - stmt.setBigDecimal(3, BigDecimal.ONE); + stmt.setBigDecimal(3, Bigdecimal.ONE); stmt.setBigDecimal(4, BigDecimal.valueOf(x)); stmt.setBoolean(5, Boolean.valueOf("true")); int i = stmt.executeUpdate(); @@ -28,7 +23,7 @@ void literalSQLrequest() throws SQLException { //dirty call con.close(); } - void batchInsertInForLoop(int[] data) throws SQLException { + void batchInsertInForLoop(int[] data) { Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle"); PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?)"); @@ -37,7 +32,7 @@ void batchInsertInForLoop(int[] data) throws SQLException { stmt.setBoolean(2, true); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, (byte) 3); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setBytes(4, "v".getBytes()); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setByte(4, 'v'); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, (short) 5); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, 6); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, (long) 7); // Noncompliant {{Avoid setting constants in batch update}} @@ -51,12 +46,12 @@ void batchInsertInForLoop(int[] data) throws SQLException { stmt.addBatch(); } int[] nr = stmt.executeBatch(); - logger.log(Level.INFO, "{} rows updated", IntStream.of(nr).sum()); + logger.log("{} rows updated", IntStream.of(nr).sum()); con.close(); } - int[] batchInsertInForeachLoop(DummyClass[] data) throws SQLException { + int[] batchInsertInForeachLoop(DummyClass[] data) { try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle")) { PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); @@ -64,7 +59,7 @@ int[] batchInsertInForeachLoop(DummyClass[] data) throws SQLException { stmt.setInt(1, o.getField1()); stmt.setBoolean(2, Boolean.valueOf("false")); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); - stmt.setBytes(4, "v".getBytes()); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setByte(4, 'v'); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, (short) 5); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, 6); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, 7); // Noncompliant {{Avoid setting constants in batch update}} @@ -79,7 +74,7 @@ int[] batchInsertInForeachLoop(DummyClass[] data) throws SQLException { } - int[] batchInsertInWhileLoop2(DummyClass[] data) throws SQLException { + int[] batchInsertInWhileLoop(DummyClass[] data) { try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle")) { PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?,?,?,?,?)"); @@ -90,6 +85,7 @@ int[] batchInsertInWhileLoop2(DummyClass[] data) throws SQLException { stmt.setBoolean(2, Boolean.TRUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); stmt.setByte(4, Byte.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setByte(4, Character.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, Short.MIN_VALUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, Integer.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, Long.MIN_VALUE); // Noncompliant {{Avoid setting constants in batch update}} @@ -104,7 +100,7 @@ int[] batchInsertInWhileLoop2(DummyClass[] data) throws SQLException { } } - int[] batchInsertInWhileLoop(DummyClass[] data) throws SQLException { + int[] batchInsertInWhileLoop(DummyClass[] data) { if (data.length == 0) { return new int[]{}; } @@ -117,10 +113,11 @@ int[] batchInsertInWhileLoop(DummyClass[] data) throws SQLException { stmt.setBoolean(2, Boolean.valueOf(true)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); stmt.setByte(4, Byte.valueOf((byte) 3)); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setByte(4, Character.valueOf('1')); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, Short.valueOf((short) 55)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, Integer.valueOf("222")); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, Long.valueOf(0)); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setFloat(8, Float.valueOf(.33f)); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setFloat(8, Float.valueOf(.33)); // 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}} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java index dfdde5d..fe5ee97 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java @@ -12,9 +12,9 @@ class UseCorrectForLoopCheck { public void testForEachLoop() { int dummy = 0; - for (Integer i : intArray) { // Noncompliant {{Avoid the use of Foreach with Arrays}} + for (Integer i : intArray) { dummy += i; - } + } // Noncompliant {{Avoid the use of Foreach with Arrays}} for (Integer i : intList) { dummy += i; From f66a7ecb41b0a3a71fbcab8aa8f9442cc84adcda Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 23 Mar 2023 23:57:36 +0100 Subject: [PATCH 14/45] delete useless tool script --- tool_build.sh | 3 --- 1 file changed, 3 deletions(-) delete mode 100755 tool_build.sh diff --git a/tool_build.sh b/tool_build.sh deleted file mode 100755 index 84820a4..0000000 --- a/tool_build.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env sh - -mvn clean package From 7a2794b7a4e8bdf85e545d6b8b8db084675f3aaa Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 29 Mar 2023 23:17:33 +0200 Subject: [PATCH 15/45] improve shell and doc --- .gitignore | 6 +----- README.md | 12 ++++++------ tool_send_to_sonar.sh | 3 ++- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 8c56452..71a8d56 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,3 @@ !.gitignore -!.github/**/*.* .* -target -*.iml -lib/*.jar -bin \ No newline at end of file +target \ No newline at end of file diff --git a/README.md b/README.md index 3b45ed0..95fa9de 100644 --- a/README.md +++ b/README.md @@ -14,16 +14,16 @@ Step 1 : prepare local environment To launch local environment : please follow https://github.com/green-code-initiative/ecoCode/blob/main/INSTALL.md (especially SonarQube configuration part) -Step 1 : compile and build +Step 2 : send Sonar metrics to local SonarQube --- -`./tool_build.sh` +```sh +./tool_send_to_sonar.sh MY_SONAR_TOKEN -Step 2 : send Sonar metrics to local SonarQube ---- +or -- first : change the token inside script (to give your personal SonarQube token, previously generated, please see install documention) -- secondly : launch `./tool_send_to_sonar.sh` +mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=MY_SONAR_TOKEN +``` Step 3 : check errors --- diff --git a/tool_send_to_sonar.sh b/tool_send_to_sonar.sh index 728a0f5..61de09a 100755 --- a/tool_send_to_sonar.sh +++ b/tool_send_to_sonar.sh @@ -1,4 +1,5 @@ #!/usr/bin/env sh # "sonar.login" variable : private TOKEN generated in your local SonarQube during installation -mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=sqa_919e0287178896de96aa019e300e85a93c9acc2d +# (input paramater of this script) +mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=$1 From ef0d508e2da8ae2ef88344155c66fde88406d10f Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 29 Mar 2023 23:43:23 +0200 Subject: [PATCH 16/45] improve shell and doc and gitignor --- .gitignore | 3 ++- README.md | 11 ++++++++--- tool_build.sh | 3 +++ 3 files changed, 13 insertions(+), 4 deletions(-) create mode 100755 tool_build.sh diff --git a/.gitignore b/.gitignore index 71a8d56..b413004 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ !.gitignore .* -target \ No newline at end of file +target +*.iml diff --git a/README.md b/README.md index 95fa9de..cb2f8c6 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,14 @@ Step 1 : prepare local environment --- To launch local environment : please follow https://github.com/green-code-initiative/ecoCode/blob/main/INSTALL.md -(especially SonarQube configuration part) +(especially SonarQube configuration part and get generated private token) -Step 2 : send Sonar metrics to local SonarQube +Step 2 : compile and build +--- + +`./tool_build.sh` + +Step 3 : send Sonar metrics to local SonarQube --- ```sh @@ -25,7 +30,7 @@ or mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=MY_SONAR_TOKEN ``` -Step 3 : check errors +Step 4 : check errors --- on local SonarQube, check if each Java class contains (or not) the rule error defined for this class diff --git a/tool_build.sh b/tool_build.sh new file mode 100755 index 0000000..bfac031 --- /dev/null +++ b/tool_build.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +mvn clean package -DskipTests From 152cd8900b2aebcbb596bce5407d54b72050b7d4 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 29 Mar 2023 23:44:01 +0200 Subject: [PATCH 17/45] correction of compile pbs to send to sonar next --- .../java/checks/ArrayCopyCheck.java | 974 +++++++++--------- .../AvoidSetConstantInBatchUpdateCheck.java | 35 +- 2 files changed, 504 insertions(+), 505 deletions(-) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 8d3bcbb..b748dd2 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -1,493 +1,491 @@ import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; class TestClass { - 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 - int 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; - } - + 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/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java index 122a48b..41bb443 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java @@ -1,21 +1,22 @@ package fr.greencodeinitiative.java.checks; import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DriverManager; import java.sql.PreparedStatement; -import java.util.regex.Pattern; +import java.sql.SQLException; import java.util.stream.IntStream; -import java.util.stream.Stream; class AvoidSetConstantInBatchUpdateCheck { - void literalSQLrequest() { //dirty call + 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(3, BigDecimal.ONE); stmt.setBigDecimal(4, BigDecimal.valueOf(x)); stmt.setBoolean(5, Boolean.valueOf("true")); int i = stmt.executeUpdate(); @@ -23,7 +24,7 @@ void literalSQLrequest() { //dirty call con.close(); } - void batchInsertInForLoop(int[] data) { + 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(?,?,?,?,?,?,?,?,?,?,?)"); @@ -32,7 +33,7 @@ void batchInsertInForLoop(int[] data) { stmt.setBoolean(2, true); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, (byte) 3); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setByte(4, 'v'); // Noncompliant {{Avoid setting constants in batch update}} + stmt.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}} @@ -46,12 +47,12 @@ void batchInsertInForLoop(int[] data) { stmt.addBatch(); } int[] nr = stmt.executeBatch(); - logger.log("{} rows updated", IntStream.of(nr).sum()); + System.out.printf("{} rows updated", IntStream.of(nr).sum()); con.close(); } - int[] batchInsertInForeachLoop(DummyClass[] data) { + 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(?,?,?,?,?,?,?,?,?,?,?,?,?)"); @@ -59,7 +60,7 @@ int[] batchInsertInForeachLoop(DummyClass[] data) { stmt.setInt(1, o.getField1()); stmt.setBoolean(2, Boolean.valueOf("false")); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); - stmt.setByte(4, 'v'); // Noncompliant {{Avoid setting constants in batch update}} + stmt.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}} @@ -74,7 +75,7 @@ int[] batchInsertInForeachLoop(DummyClass[] data) { } - int[] batchInsertInWhileLoop(DummyClass[] data) { + 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(?,?,?,?,?,?,?,?,?,?,?,?,?)"); @@ -85,7 +86,7 @@ int[] batchInsertInWhileLoop(DummyClass[] data) { stmt.setBoolean(2, Boolean.TRUE); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); stmt.setByte(4, Byte.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setByte(4, Character.MAX_VALUE); // Noncompliant {{Avoid setting constants in batch update}} + stmt.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}} @@ -100,7 +101,7 @@ int[] batchInsertInWhileLoop(DummyClass[] data) { } } - int[] batchInsertInWhileLoop(DummyClass[] data) { + int[] batchInsertInWhileLoop(DummyClass[] data) throws SQLException { if (data.length == 0) { return new int[]{}; } @@ -113,11 +114,10 @@ int[] batchInsertInWhileLoop(DummyClass[] data) { stmt.setBoolean(2, Boolean.valueOf(true)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setByte(3, o.getField3()); stmt.setByte(4, Byte.valueOf((byte) 3)); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setByte(4, Character.valueOf('1')); // Noncompliant {{Avoid setting constants in batch update}} stmt.setShort(5, Short.valueOf((short) 55)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setInt(6, Integer.valueOf("222")); // Noncompliant {{Avoid setting constants in batch update}} stmt.setLong(7, Long.valueOf(0)); // Noncompliant {{Avoid setting constants in batch update}} - stmt.setFloat(8, Float.valueOf(.33)); // Noncompliant {{Avoid setting constants in batch update}} + stmt.setFloat(8, Float.valueOf(.33f)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setDouble(9, Double.valueOf(22)); // Noncompliant {{Avoid setting constants in batch update}} stmt.setString(10, o.getField2()); stmt.setBigDecimal(11, BigDecimal.valueOf(11)); // Noncompliant {{Avoid setting constants in batch update}} @@ -143,8 +143,9 @@ public byte getField3() { } public double getField4() { - return .1; } - } - + return .1; + } + } + } \ No newline at end of file From 48aacb3b255fe58731a4443d753e41a490e8f060 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 10 Apr 2023 10:45:58 +0200 Subject: [PATCH 18/45] [ISSUE 60] adding test use cases --- .../java/checks/IncrementCheck.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java index 7f5f6cc..a88292b 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -30,7 +30,19 @@ void foo3(int value) { } void foo4(int value) { - int counter =0; + 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 From dfc12d945344c186b0f5fd15c99e93b05245d7f1 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 12 Apr 2023 22:52:43 +0200 Subject: [PATCH 19/45] [ISSUE 166] correction of wrong message (#9) --- .../checks/UnnecessarilyAssignValuesToVariablesTestCheck.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java index 4a59150..b61a58e 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java @@ -14,7 +14,7 @@ public int testSwitchCase() throws Exception { int[] intArray = {10, 20, 30, 40, 50}; Exception variableException = new Exception("message"); - int variableNotUse = 5; // Noncompliant {{The variable is not assigned}} + int variableNotUse = 5; // Noncompliant {{The variable is declared but not really used}} variableNotUse = 10; From 78003eca15b35a970701cf68464686e774450516 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 8 Jun 2023 08:13:40 +0200 Subject: [PATCH 20/45] upgrade authent method for SonarQube --- tool_send_to_sonar.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tool_send_to_sonar.sh b/tool_send_to_sonar.sh index 61de09a..80bff05 100755 --- a/tool_send_to_sonar.sh +++ b/tool_send_to_sonar.sh @@ -2,4 +2,4 @@ # "sonar.login" variable : private TOKEN generated in your local SonarQube during installation # (input paramater of this script) -mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=$1 +mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 From 6cf57753a9d53fe98b21aa1201ee1103366745ca Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Jul 2023 22:03:26 +0700 Subject: [PATCH 21/45] update sonar scanner command --- tool_send_to_sonar.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tool_send_to_sonar.sh b/tool_send_to_sonar.sh index 80bff05..03abfae 100755 --- a/tool_send_to_sonar.sh +++ b/tool_send_to_sonar.sh @@ -1,5 +1,8 @@ #!/usr/bin/env sh -# "sonar.login" variable : private TOKEN generated in your local SonarQube during installation +# "sonar.token" variable (or sonar.login before SONARQUBE 9.9) : private TOKEN generated in your local SonarQube during installation # (input paramater of this script) mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 + +# command if you have a SONARQUBE < 9.9 (sonar.token existing for SONARQUBE >= 10.0) +# mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=$1 From 37a343f03309f7c8b63c2002a05e4fe2f36561af Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 15 Aug 2023 23:50:36 +0200 Subject: [PATCH 22/45] [ISSUE 216] upgrade EC2 rule pour Java (multiple If/Else/Elseif) --- .../checks/AvoidMultipleIfElseStatement.java | 266 ++++++++++++++++-- .../AvoidMultipleIfElseStatementNoIssue.java | 187 +++++++++++- 2 files changed, 422 insertions(+), 31 deletions(-) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index 6dbc73d..0ce74dc 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -1,38 +1,266 @@ package fr.greencodeinitiative.java.checks; class AvoidMultipleIfElseStatementCheck { - AvoidMultipleIfElseStatementCheck(AvoidMultipleIfElseStatementCheck mc) { - } - public void methodWithMultipleIfElseIf() { +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// // +// // 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; - int nb2 = 10; 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 if (nb1 == nb2) { - // - } else if (nb2 == nb1) { - // } else { - // - } // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} - nb1 = nb2; + 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; } - public void methodWithMultipleIfElse() { + + // 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) { - nb1 = 1; + nb2 = 1; + } else if (nb1 == nb2) { + nb2 = 2; } else { - // - } // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} + 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) { - 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 { - // - } // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} + nb2 = 4; + } // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + + return nb2; } -} \ No newline at end of file + +} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java index 60d1029..d3a57b7 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java @@ -1,31 +1,194 @@ package fr.greencodeinitiative.java.checks; -class AvoidMultipleIfElseStatementNoIssueCheck { - AvoidMultipleIfElseStatementNoIssueCheck(AvoidMultipleIfElseStatementNoIssueCheck mc) { +class AvoidMultipleIfElseStatementCheckNoIssue { + + // 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; } - public void methodWithOneIfElseIf() { + // 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; - int nb2 = 10; if (nb1 == 1) { nb1 = 1; - } else if (nb1 == nb2) { - // + } + + 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; + } + } } - nb1 = nb2; + + return nb1; } - public void methodWithOneIfElse() { + // 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) { - 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; } -} \ No newline at end of file + +} From a8b4dff28fa8f2945735ca4a72a37959b87e0713 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 1 Dec 2023 22:09:38 +0100 Subject: [PATCH 23/45] [ISSUE 112] add use case file for EC1 streams --- .../AvoidSpringRepositoryCallInLoopCheck.java | 12 +- ...voidSpringRepositoryCallInStreamCheck.java | 139 ++++++++++++++++++ 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java index 2b1579a..33989f2 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -12,7 +12,7 @@ public class AvoidSpringRepositoryCallInLoopCheck { 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}} + Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} if (employee.isPresent()) { employees.add(employee.get()); } @@ -21,6 +21,16 @@ public List smellGetAllEmployeesByIds(List ids) { } public class Employee { + private Integer id; + private String name; + + public Employee(Integer id, String name) { + this.id = id; + this.name = name; + } + + public Integer getId() { return id; } + public String getName() { return name; } } public interface EmployeeRepository extends JpaRepository { diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java new file mode 100644 index 0000000..636e55e --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java @@ -0,0 +1,139 @@ +/* + * 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.IntStream; +import java.util.stream.Stream; + +public class AvoidSpringRepositoryCallInStreamCheck { + + @Autowired + private EmployeeRepository employeeRepository; + + public void 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}} + if (employee.isPresent()) { + employees.add(employee.get()); + } + }); + } + + public void 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}} + if (employee.isPresent()) { + employees.add(employee.get()); + } + }); + } + + 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}} + if (employee.isPresent()) { + employees.add(employee.get()); + } + }) + .collect(Collectors.toList()); + } + + public List smellGetAllEmployeesByIdsPeek() { + List employees = new ArrayList<>(); + Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + return stream.peek(id -> { + Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} + if (employee.isPresent()) { + employees.add(employee.get()); + } + }) + .collect(Collectors.toList()); + } + + public List smellGetAllEmployeesByIdsWithOptional(List ids) { + List employees = new ArrayList<>(); + return ids + .stream() + .map(element -> { + Employee empl = new Employee(); + employees.add(empl); + return employeeRepository.findById(element).orElse(empl);// Noncompliant {{Avoid Spring repository call in loop or stream}} + }) + .collect(Collectors.toList()); + } + + public List smellGetAllEmployeesByIds(List ids) { + Stream stream = ids.stream(); + return stream.map(element -> { + Employee empl = new Employee(); + employees.add(empl); + 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(element -> { + Employee empl = new Employee(); + employees.add(empl); + return employeeRepository.deleteById(element);// 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(); + return employeeRepository.findById(element).orElse(empl).anotherMethod().anotherOne();// Noncompliant {{Avoid Spring repository call in loop or stream}} + }) + .collect(Collectors.toList()); + } + + 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 From 9e87447c24add57a96c953fb4d7275b66f1d8faa Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 1 Dec 2023 22:12:20 +0100 Subject: [PATCH 24/45] [ISSUE 112] add use case file for EC1 streams - add header --- .../AvoidSpringRepositoryCallInLoopCheck.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java index 33989f2..ee93298 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -1,3 +1,20 @@ +/* + * 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; From 8ed7e9261d8a8df3d60410a30b913282c6bced9a Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sun, 3 Dec 2023 23:34:24 +0100 Subject: [PATCH 25/45] [ISSUE 247] add 2 new use cases for switch --- .../AvoidMultipleIfElseStatementNoIssue.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java index d3a57b7..62a8373 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java @@ -191,4 +191,40 @@ public int shouldBeCompliantBecauseSeveralVariablesUsedMaximumTwiceInIfOrElseIfS 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; + } + } From 5c920ef4dd1a384db69e2cb5df2d55192ff52b09 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 7 Dec 2023 23:30:43 +0100 Subject: [PATCH 26/45] [ISSUE 248] Add test to prove ISSUE 248 is already ok --- .../AvoidMultipleIfElseStatementNoIssue.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java index 62a8373..fc7c8f7 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java @@ -227,4 +227,30 @@ public double shouldBeCompliantBecauseVariableHasNotCompatibleTypeDoubleForSwitc 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; + } + } From 5ce922a0c2a7cc27ecce75f8276676ed9771c83d Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 17 Jan 2024 08:15:35 +0100 Subject: [PATCH 27/45] [TECH] add comment --- tool_send_to_sonar.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/tool_send_to_sonar.sh b/tool_send_to_sonar.sh index 03abfae..6a658d7 100755 --- a/tool_send_to_sonar.sh +++ b/tool_send_to_sonar.sh @@ -3,6 +3,7 @@ # "sonar.token" variable (or sonar.login before SONARQUBE 9.9) : private TOKEN generated in your local SonarQube during installation # (input paramater of this script) mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 +# mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 -Dsonar.host.url=https://sonar-staging.gcp.cicd.solocal.com/ # command if you have a SONARQUBE < 9.9 (sonar.token existing for SONARQUBE >= 10.0) # mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=$1 From 89b0be42261e06092af4955c391184bdab284204 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 19 Jan 2024 11:44:35 +0100 Subject: [PATCH 28/45] delete unsed script for building --- tool_build.sh | 3 --- 1 file changed, 3 deletions(-) delete mode 100755 tool_build.sh diff --git a/tool_build.sh b/tool_build.sh deleted file mode 100755 index bfac031..0000000 --- a/tool_build.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env sh - -mvn clean package -DskipTests From c07d9bfd41ed2eb85075df609166a3a5d5888b97 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 19 Jan 2024 11:44:35 +0100 Subject: [PATCH 29/45] delete unsed script for building --- tool_build.sh | 3 --- 1 file changed, 3 deletions(-) delete mode 100755 tool_build.sh diff --git a/tool_build.sh b/tool_build.sh deleted file mode 100755 index bfac031..0000000 --- a/tool_build.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env sh - -mvn clean package -DskipTests From f276d965b35074f5898251f8e70b4b4d0290c482 Mon Sep 17 00:00:00 2001 From: alograg Date: Fri, 19 Jan 2024 12:56:29 +0100 Subject: [PATCH 30/45] docs: :memo: Documentation of changes --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8ca0454 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +### Changed + +- Rules elimination test for [Remove deprecated rules EC4, EC53, EC63 and EC75 for JAVA](https://github.com/green-code-initiative/ecoCode/pull/272) + +### Deleted + From d9cfbd2f2741e928f3263cd5eac14a93d70f7d87 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 22 Jan 2024 19:23:48 +0100 Subject: [PATCH 31/45] EC2 rule : correction NullPointer with interface (no Issue) --- ...ltipleIfElseStatementInterfaceNoIssue.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java new file mode 100644 index 0000000..43dd875 --- /dev/null +++ b/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 AvoidMultipleIfElseStatementCheck { + + TransactionMetaData initMetaData(ITransactionFoundation transactionFoundation) throws ProgramException, MnemonicTemplateShellException; + +} From c57f877c88f64631d6fd63ec255e6ba88914bfe7 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 25 Jan 2024 21:54:02 +0100 Subject: [PATCH 32/45] add new use case from ISSUE 9 of ecoCode-java repository --- ...MultipleIfElseStatementNoBlockNoIssue.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java new file mode 100644 index 0000000..b33c3a4 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java @@ -0,0 +1,27 @@ +/* + * 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 AvoidMultipleIfElseStatementNotBlock { + + public boolean equals(Object obj) { + if (this == obj) + return true; + } + +} From 8d25c52744a14692152be8a99f51485157a7abc8 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 2 Feb 2024 16:36:36 +0100 Subject: [PATCH 33/45] delete test files because of PR #6 on ecoCode-java repo (deletion of deprecated java rules EC4, EC53, EC63 and EC75) --- CHANGELOG.md | 17 ---- .../checks/AvoidConcatenateStringsInLoop.java | 32 -------- .../AvoidUsingGlobalVariablesCheck.java | 21 ----- ...arilyAssignValuesToVariablesTestCheck.java | 78 ------------------- ...esToVariablesTestCheckWithEmptyReturn.java | 18 ----- .../java/checks/UseCorrectForLoopCheck.java | 24 ------ 6 files changed, 190 deletions(-) delete mode 100644 CHANGELOG.md delete mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java delete mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java delete mode 100644 src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java delete mode 100644 src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java delete mode 100644 src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 8ca0454..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,17 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Added - -### Changed - -- Rules elimination test for [Remove deprecated rules EC4, EC53, EC63 and EC75 for JAVA](https://github.com/green-code-initiative/ecoCode/pull/272) - -### Deleted - diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java deleted file mode 100644 index c5079eb..0000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java +++ /dev/null @@ -1,32 +0,0 @@ -package fr.greencodeinitiative.java.checks; - -public class AvoidConcatenateStringsInLoop { - - public String concatenateStrings(String[] strings) { - String result1 = ""; - - for (String string : strings) { - result1 += string; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} - } - return result1; - } - - public String concatenateStrings2() { - String result2 = ""; - - for (int i = 0; i < 1000; ++i) { - result2 += "another"; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} - } - return result2; - } - - public String concatenateStrings3() { - String result3 = ""; - - for (int i = 0; i < 1000; ++i) { - result3 = result3 + "another"; // Noncompliant {{Don't concatenate Strings in loop, use StringBuilder instead.}} - } - return result3; - } - -} diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java deleted file mode 100644 index 3dea9e3..0000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java +++ /dev/null @@ -1,21 +0,0 @@ -package fr.greencodeinitiative.java.checks; - -public class AvoidUsingGlobalVariablesCheck { - public static double price = 15.24; // Noncompliant {{Avoid using global variables}} - public static long pages = 1053; // Noncompliant {{Avoid using global variables}} - - public static void main(String[] args) { - double newPrice = AvoidUsingGlobalVariablesCheck.price; - long newPages = AvoidUsingGlobalVariablesCheck.pages; - System.out.println(newPrice); - System.out.println(newPages); - } - static{ // Noncompliant {{Avoid using global variables}} - int a = 4; - } - - public void printingA() { - System.out.println("a"); - } - -} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java deleted file mode 100644 index b61a58e..0000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheck.java +++ /dev/null @@ -1,78 +0,0 @@ -package fr.greencodeinitiative.java.checks; - -class UnnecessarilyAssignValuesToVariablesTestCheck { - UnnecessarilyAssignValuesToVariablesTestCheck(UnnecessarilyAssignValuesToVariablesTestCheck mc) { - } - - public int testSwitchCase() throws Exception { - int variableFor = 5; - int variableIf = 5; - int variableWhile = 5; - int variableExp = 5; - int variableReturn = 5; - int variableCLass = 5; - int[] intArray = {10, 20, 30, 40, 50}; - - Exception variableException = new Exception("message"); - int variableNotUse = 5; // Noncompliant {{The variable is declared but not really used}} - - - variableNotUse = 10; - for (variableFor = 0; variableFor < 5; ++variableFor) { - System.out.println(variableFor); - } - - for (int ia : intArray) { - System.out.println((char) ia); - } - - if (variableIf > 10) { - System.out.println(variableIf); - } - - while (variableWhile > 10) { - System.out.println(variableWhile); - } - - variableExp += 1; - variableNotUse = variableExp; - TestClass testClass = new TestClass(variableCLass); - if (testClass.isTrue()) { - throw variableException; - } - return variableReturn; - } - - private class TestClass { - TestClass(int i) { - ++i; - } - - public boolean isTrue() { - return true; - } - } - - - private int getIntValue() { - return 3; - } - - public int testNonCompliantReturn() { - int i = getIntValue(); // Noncompliant {{Immediately return this expression instead of assigning it to the temporary variable}} - return i; - } - - public int testCompliantReturn() { - return getIntValue(); - } - - public void testNonCompliantThrow() throws Exception { - Exception exception = new Exception("dummy"); // Noncompliant {{Immediately throw this expression instead of assigning it to the temporary variable}} - throw exception; - } - - public void testCompliantThrow() throws Exception { - throw new Exception("dummy"); - } -} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java b/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java deleted file mode 100644 index 4dbb952..0000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java +++ /dev/null @@ -1,18 +0,0 @@ -package fr.greencodeinitiative.java.checks; - -import java.util.ArrayList; - -class UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn { - UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn(UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn mc) { - } - - public void testSwitchCase() { - - ArrayList lst = new ArrayList(0); - if (lst == null) { - return; - } - System.out.println(lst); - } - -} \ No newline at end of file diff --git a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java deleted file mode 100644 index fe5ee97..0000000 --- a/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoopCheck.java +++ /dev/null @@ -1,24 +0,0 @@ -package fr.greencodeinitiative.java.checks; - -import java.util.Arrays; -import java.util.List; - -class UseCorrectForLoopCheck { - UseCorrectForLoopCheck(UseCorrectForLoopCheck mc) { - } - - private final Integer[] intArray = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - private final List intList = Arrays.asList(intArray); - - public void testForEachLoop() { - int dummy = 0; - for (Integer i : intArray) { - dummy += i; - } // Noncompliant {{Avoid the use of Foreach with Arrays}} - - for (Integer i : intList) { - dummy += i; - } - System.out.println(dummy); - } -} \ No newline at end of file From c9d40f187b03ecf0ae8df8ee0036a57d4976f33d Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 6 Feb 2024 22:16:13 +0100 Subject: [PATCH 34/45] [ISSUE 15] correction NullPointer in EC2 --- ...leIfElseStatementCompareMethodNoIssue.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java new file mode 100644 index 0000000..0a36154 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java @@ -0,0 +1,37 @@ +package fr.greencodeinitiative.java.checks; + +class AvoidMultipleIfElseStatementCheck { + + 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()); + } + +} From 30c1271e6559211d5d221d83a31ffce53dab0552 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sun, 17 Mar 2024 15:48:03 +0100 Subject: [PATCH 35/45] Add java rule EC80 : Optimize Database SQL Queries (Clause LIMIT) (#18) --- .../checks/OptimizeSQLQueriesWithLimit.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java new file mode 100644 index 0000000..63ede82 --- /dev/null +++ b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java @@ -0,0 +1,18 @@ +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)}} + @Query("select t from Todo t where t.status != 'COMPLETED' LIMIT 25") // Compliant + + 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 From ee0836c0fb67e94ec6b0e198d44bdc4379b2446c Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 29 May 2024 18:46:12 +0200 Subject: [PATCH 36/45] correction of code to be buildable to make an analysis to Sonar --- pom.xml | 6 +- .../java/checks/ArrayCopyCheck.java | 2 +- .../checks/AvoidMultipleIfElseStatement.java | 2 +- ...leIfElseStatementCompareMethodNoIssue.java | 35 +++++++++++- ...ltipleIfElseStatementInterfaceNoIssue.java | 4 +- ...MultipleIfElseStatementNoBlockNoIssue.java | 3 +- .../AvoidMultipleIfElseStatementNoIssue.java | 2 +- ...voidSpringRepositoryCallInStreamCheck.java | 56 +++++++------------ .../checks/OptimizeSQLQueriesWithLimit.java | 12 ++++ tool_send_to_sonar.sh | 2 +- 10 files changed, 79 insertions(+), 45 deletions(-) diff --git a/pom.xml b/pom.xml index 8bf9a4d..c059b1f 100644 --- a/pom.xml +++ b/pom.xml @@ -10,10 +10,12 @@ ecoCode Java Sonar Plugin Test Project - 11 + 17 ${java.version} ${java.version} + target + UTF-8 ${encoding} ${encoding} @@ -23,7 +25,7 @@ org.springframework.data spring-data-jpa - 2.7.8 + 3.3.0 org.springframework diff --git a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index b748dd2..1f93de1 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -1,6 +1,6 @@ import java.util.Arrays; -class TestClass { +class ArrayCopyCheck { public void copyArrayOK() { final int len = 5; diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index 0ce74dc..329342a 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -1,6 +1,6 @@ package fr.greencodeinitiative.java.checks; -class AvoidMultipleIfElseStatementCheck { +class AvoidMultipleIfElseStatement { // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java index 0a36154..573cdc9 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java @@ -1,6 +1,6 @@ package fr.greencodeinitiative.java.checks; -class AvoidMultipleIfElseStatementCheck { +class AvoidMultipleIfElseStatementCompareMethodNoIssue { public int compare(FieldVo o1, FieldVo o2) { @@ -34,4 +34,37 @@ public int compare(FieldVo o1, FieldVo o2) { 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/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java index 43dd875..1409a4e 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java @@ -17,8 +17,8 @@ */ package fr.greencodeinitiative.java.checks; -interface AvoidMultipleIfElseStatementCheck { +interface AvoidMultipleIfElseStatementInterfaceNoIssue { - TransactionMetaData initMetaData(ITransactionFoundation transactionFoundation) throws ProgramException, MnemonicTemplateShellException; + Object initMetaData(Object transactionFoundation) throws IllegalAccessException; } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java index b33c3a4..d66bfed 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java @@ -17,11 +17,12 @@ */ package fr.greencodeinitiative.java.checks; -class AvoidMultipleIfElseStatementNotBlock { +class AvoidMultipleIfElseStatementNoBlockNoIssue { public boolean equals(Object obj) { if (this == obj) return true; + return false; } } diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java index fc7c8f7..f4260da 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java @@ -1,6 +1,6 @@ package fr.greencodeinitiative.java.checks; -class AvoidMultipleIfElseStatementCheckNoIssue { +class AvoidMultipleIfElseStatementNoIssue { // inital RULES : please see HTML description file of this rule (resources directory) diff --git a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java index 636e55e..38fa010 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java @@ -22,7 +22,6 @@ import java.util.*; import java.util.stream.Collectors; -import java.util.stream.IntStream; import java.util.stream.Stream; public class AvoidSpringRepositoryCallInStreamCheck { @@ -30,69 +29,58 @@ public class AvoidSpringRepositoryCallInStreamCheck { @Autowired private EmployeeRepository employeeRepository; - public void smellGetAllEmployeesByIdsForEach() { + 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}} - if (employee.isPresent()) { - employees.add(employee.get()); - } + employee.ifPresent(employees::add); }); + return employees; } - public void smellGetAllEmployeesByIdsForEachOrdered() { + 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}} - if (employee.isPresent()) { - employees.add(employee.get()); - } + employee.ifPresent(employees::add); }); + return employees; } - public List smellGetAllEmployeesByIdsMap() { + public List> smellGetAllEmployeesByIdsMap() { List employees = new ArrayList<>(); Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return stream.map(id -> { Optional employee = employeeRepository.findById(id); // Noncompliant {{Avoid Spring repository call in loop or stream}} - if (employee.isPresent()) { - employees.add(employee.get()); - } + employee.ifPresent(employees::add); + return employees; }) .collect(Collectors.toList()); } - public List smellGetAllEmployeesByIdsPeek() { - List employees = new ArrayList<>(); + 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}} - if (employee.isPresent()) { - employees.add(employee.get()); - } }) .collect(Collectors.toList()); } public List smellGetAllEmployeesByIdsWithOptional(List ids) { - List employees = new ArrayList<>(); return ids .stream() .map(element -> { - Employee empl = new Employee(); - employees.add(empl); - return employeeRepository.findById(element).orElse(empl);// Noncompliant {{Avoid Spring repository call in loop or stream}} + 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) { + public List> smellGetAllEmployeesByIds(List ids) { Stream stream = ids.stream(); return stream.map(element -> { - Employee empl = new Employee(); - employees.add(empl); return employeeRepository.findById(element);// Noncompliant {{Avoid Spring repository call in loop or stream}} }) .collect(Collectors.toList()); @@ -102,12 +90,10 @@ public List smellGetAllEmployeesByIdsWithoutStream(List ids) return employeeRepository.findAllById(ids); // Compliant } - public List smellDeleteEmployeeById(List ids) { + public List> smellDeleteEmployeeById(List ids) { Stream stream = ids.stream(); - return stream.map(element -> { - Employee empl = new Employee(); - employees.add(empl); - return employeeRepository.deleteById(element);// Noncompliant {{Avoid Spring repository call in loop or stream}} + return stream.map(id -> { + return employeeRepository.findById(id);// Noncompliant {{Avoid Spring repository call in loop or stream}} }) .collect(Collectors.toList()); } @@ -115,15 +101,15 @@ public List smellDeleteEmployeeById(List ids) { public List smellGetAllEmployeesByIdsWithSeveralMethods(List ids) { Stream stream = ids.stream(); return stream.map(element -> { - Employee empl = new Employee(); - return employeeRepository.findById(element).orElse(empl).anotherMethod().anotherOne();// Noncompliant {{Avoid Spring repository call in loop or stream}} + 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 class Employee { - private Integer id; - private String name; + public static class Employee { + private final Integer id; + private final String name; public Employee(Integer id, String name) { this.id = id; diff --git a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java index 63ede82..52c912f 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java @@ -1,3 +1,8 @@ +import org.springframework.data.jpa.repository.Query; + +import java.util.ArrayList; +import java.util.List; + class OptimizeSQLQueriesWithLimit { public void literalSQLrequest() { @@ -6,7 +11,14 @@ public void literalSQLrequest() { } @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)}} diff --git a/tool_send_to_sonar.sh b/tool_send_to_sonar.sh index 6a658d7..2147084 100755 --- a/tool_send_to_sonar.sh +++ b/tool_send_to_sonar.sh @@ -2,7 +2,7 @@ # "sonar.token" variable (or sonar.login before SONARQUBE 9.9) : private TOKEN generated in your local SonarQube during installation # (input paramater of this script) -mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 +mvn clean org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 # mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 -Dsonar.host.url=https://sonar-staging.gcp.cicd.solocal.com/ # command if you have a SONARQUBE < 9.9 (sonar.token existing for SONARQUBE >= 10.0) From c0251589700af491130d626dec6fbaa3abc66751 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 19 Jul 2024 16:34:54 +0200 Subject: [PATCH 37/45] update docker port managment --- tool_send_to_sonar.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tool_send_to_sonar.sh b/tool_send_to_sonar.sh index 2147084..cb663d9 100755 --- a/tool_send_to_sonar.sh +++ b/tool_send_to_sonar.sh @@ -2,8 +2,7 @@ # "sonar.token" variable (or sonar.login before SONARQUBE 9.9) : private TOKEN generated in your local SonarQube during installation # (input paramater of this script) -mvn clean org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 -# mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.token=$1 -Dsonar.host.url=https://sonar-staging.gcp.cicd.solocal.com/ +mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.host.url=http://localhost:$1 -Dsonar.token=$2 # command if you have a SONARQUBE < 9.9 (sonar.token existing for SONARQUBE >= 10.0) # mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=$1 From f0eb9320120d0798fbc8a832d57c8af807ec733c Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 28 Oct 2024 22:05:23 +0100 Subject: [PATCH 38/45] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb2f8c6..b0da22d 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Step 3 : send Sonar metrics to local SonarQube --- ```sh -./tool_send_to_sonar.sh MY_SONAR_TOKEN +./tool_send_to_sonar.sh MY_SONAR_PORT MY_SONAR_TOKEN or From 85cf20a5a835b799ee8c362e9af12bd199d7b4d0 Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 29 Oct 2024 16:01:06 +0100 Subject: [PATCH 39/45] refactor: Moves resources in dedicated subdirectory to prepare future merge with ecoCode-java repo --- .../test-projects/ecocode-java-plugin-test-project/.gitignore | 0 .../test-projects/ecocode-java-plugin-test-project/LICENCE.md | 0 .../it/test-projects/ecocode-java-plugin-test-project/README.md | 0 .../it/test-projects/ecocode-java-plugin-test-project/pom.xml | 0 .../java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java | 2 ++ .../java/checks/AvoidFullSQLRequestCheck.java | 0 .../checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java | 0 .../java/checks/AvoidGettingSizeCollectionInForLoopBad.java | 0 .../java/checks/AvoidGettingSizeCollectionInForLoopGood.java | 0 .../java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java | 0 .../java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java | 0 .../java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java | 0 .../checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java | 0 .../java/checks/AvoidMultipleIfElseStatement.java | 0 .../AvoidMultipleIfElseStatementCompareMethodNoIssue.java | 0 .../checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java | 0 .../java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java | 0 .../java/checks/AvoidMultipleIfElseStatementNoIssue.java | 0 .../java/checks/AvoidRegexPatternNotStatic.java | 0 .../java/checks/AvoidSQLRequestInLoopCheck.java | 0 .../java/checks/AvoidSetConstantInBatchUpdateCheck.java | 0 .../java/checks/AvoidSpringRepositoryCallInLoopCheck.java | 0 .../java/checks/AvoidSpringRepositoryCallInStreamCheck.java | 0 .../java/checks/AvoidStatementForDMLQueries.java | 0 .../java/checks/AvoidUsageOfStaticCollections.java | 0 .../java/checks/FreeResourcesOfAutoCloseableInterface.java | 0 .../java/checks/GoodUsageOfStaticCollections.java | 0 .../java/checks/GoodWayConcatenateStringsLoop.java | 0 .../java/fr/greencodeinitiative/java/checks/IncrementCheck.java | 0 .../java/checks/InitializeBufferWithAppropriateSize.java | 0 .../java/checks/NoFunctionCallWhenDeclaringForLoop.java | 0 .../java/checks/OptimizeReadFileExceptionCheck.java | 0 .../java/checks/OptimizeReadFileExceptionCheck2.java | 0 .../java/checks/OptimizeReadFileExceptionCheck3.java | 0 .../java/checks/OptimizeReadFileExceptionCheck4.java | 0 .../java/checks/OptimizeReadFileExceptionCheck5.java | 0 .../java/checks/OptimizeSQLQueriesWithLimit.java | 2 ++ .../fr/greencodeinitiative/java/checks/ValidRegexPattern.java | 0 .../fr/greencodeinitiative/java/checks/ValidRegexPattern2.java | 0 .../fr/greencodeinitiative/java/checks/ValidRegexPattern3.java | 0 .../ecocode-java-plugin-test-project/tool_send_to_sonar.sh | 0 41 files changed, 4 insertions(+) rename .gitignore => src/it/test-projects/ecocode-java-plugin-test-project/.gitignore (100%) rename LICENCE.md => src/it/test-projects/ecocode-java-plugin-test-project/LICENCE.md (100%) rename README.md => src/it/test-projects/ecocode-java-plugin-test-project/README.md (100%) rename pom.xml => src/it/test-projects/ecocode-java-plugin-test-project/pom.xml (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java (99%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java (95%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java (100%) rename src/{ => it/test-projects/ecocode-java-plugin-test-project/src}/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java (100%) rename tool_send_to_sonar.sh => src/it/test-projects/ecocode-java-plugin-test-project/tool_send_to_sonar.sh (100%) diff --git a/.gitignore b/src/it/test-projects/ecocode-java-plugin-test-project/.gitignore similarity index 100% rename from .gitignore rename to src/it/test-projects/ecocode-java-plugin-test-project/.gitignore diff --git a/LICENCE.md b/src/it/test-projects/ecocode-java-plugin-test-project/LICENCE.md similarity index 100% rename from LICENCE.md rename to src/it/test-projects/ecocode-java-plugin-test-project/LICENCE.md diff --git a/README.md b/src/it/test-projects/ecocode-java-plugin-test-project/README.md similarity index 100% rename from README.md rename to src/it/test-projects/ecocode-java-plugin-test-project/README.md diff --git a/pom.xml b/src/it/test-projects/ecocode-java-plugin-test-project/pom.xml similarity index 100% rename from pom.xml rename to src/it/test-projects/ecocode-java-plugin-test-project/pom.xml diff --git a/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 similarity index 99% rename from src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 1f93de1..adee2b5 100644 --- a/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 @@ -1,3 +1,5 @@ +package fr.greencodeinitiative.java.checks; + import java.util.Arrays; class ArrayCopyCheck { diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheck.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForEachLoopIgnored.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopBad.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopGood.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInForLoopIgnored.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopBad.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopGood.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInWhileLoopIgnored.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementCompareMethodNoIssue.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementInterfaceNoIssue.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoBlockNoIssue.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementNoIssue.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheck.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdateCheck.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInStreamCheck.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodUsageOfStaticCollections.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/GoodWayConcatenateStringsLoop.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck2.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck3.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck4.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheck5.java diff --git a/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 similarity index 95% rename from src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/OptimizeSQLQueriesWithLimit.java index 52c912f..c21e2a4 100644 --- a/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 @@ -1,3 +1,5 @@ +package fr.greencodeinitiative.java.checks; + import org.springframework.data.jpa.repository.Query; import java.util.ArrayList; diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern2.java diff --git a/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 similarity index 100% rename from src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java rename to src/it/test-projects/ecocode-java-plugin-test-project/src/main/java/fr/greencodeinitiative/java/checks/ValidRegexPattern3.java diff --git a/tool_send_to_sonar.sh b/src/it/test-projects/ecocode-java-plugin-test-project/tool_send_to_sonar.sh similarity index 100% rename from tool_send_to_sonar.sh rename to src/it/test-projects/ecocode-java-plugin-test-project/tool_send_to_sonar.sh From fc369b9e8f97d0b6009560cd48c5831a03d0041e Mon Sep 17 00:00:00 2001 From: jycr Date: Sat, 19 Oct 2024 18:51:09 +0200 Subject: [PATCH 40/45] Update SonarQube dependencies --- pom.xml | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index ea5912d..ede7da7 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,7 +71,7 @@ 1.7 - + 1.6.5 @@ -88,9 +93,9 @@ - org.sonarsource.sonarqube + org.sonarsource.api.plugin sonar-plugin-api - ${sonarqube.version} + ${sonar.plugin.api.version} provided @@ -333,8 +338,11 @@
com/mycila/maven/plugin/license/templates/GPL-3.txt
- **/*.java + ${project.basedir}/src/**/*.java + + ${project.basedir}/src/it/test-projects/** +
From 5aec7d67eb350e08299fbacf87e9c53a7984c2a2 Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 29 Oct 2024 14:39:58 +0100 Subject: [PATCH 41/45] Adds SonarQube integration tests --- pom.xml | 139 ++++++ .../LaunchSonarqubeAndBuildProjectIT.java | 440 ++++++++++++++++++ .../tests/profile/ProfileBackup.java | 163 +++++++ .../tests/profile/ProfileMetadata.java | 42 ++ .../tests/profile/RuleMetadata.java | 40 ++ 5 files changed, 824 insertions(+) create mode 100644 src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java create mode 100644 src/it/java/io/ecocode/java/integration/tests/profile/ProfileBackup.java create mode 100644 src/it/java/io/ecocode/java/integration/tests/profile/ProfileMetadata.java create mode 100644 src/it/java/io/ecocode/java/integration/tests/profile/RuleMetadata.java diff --git a/pom.xml b/pom.xml index ede7da7..9c9e681 100644 --- a/pom.xml +++ b/pom.xml @@ -74,6 +74,19 @@ 1.6.5 + + https://repo1.maven.org/maven2 + + false + + + ${sonarqube.version} + + + ${sonarjava.version} + + + @@ -147,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 + @@ -356,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..f865cc1 --- /dev/null +++ b/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java @@ -0,0 +1,440 @@ +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 splitAndTrim(String value, String regexSeparator) { + return Stream + .of(value.split(regexSeparator)) + .map(String::trim) + .filter(not(String::isEmpty)); + } + + private static Set additionalPluginsToInstall() { + return commaSeparatedValues(systemProperty("test-it.plugins")) + .map(LaunchSonarqubeAndBuildProjectIT::toPluginLocation) + .collect(Collectors.toSet()); + } + + 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 = pipeSeparatedValues(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 + '\'' + + '}'; + } +} From 177b20ffb250345a78a3617bc1d0df18982d8c42 Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 29 Oct 2024 15:55:26 +0100 Subject: [PATCH 42/45] Updates documentation and changelog --- CHANGELOG.md | 1 + README.md | 28 ++++++++----------- pom.xml | 4 +-- .../LaunchSonarqubeAndBuildProjectIT.java | 14 ++++++++-- 4 files changed, 25 insertions(+), 22 deletions(-) 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..dff5905 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 -``` -... 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). +NB: To install other `ecocode` plugins, you can : +- 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 ------------------ diff --git a/pom.xml b/pom.xml index 9c9e681..0da8b0b 100644 --- a/pom.xml +++ b/pom.xml @@ -86,7 +86,7 @@ ${sonarjava.version} - + @@ -466,7 +466,7 @@ ${project.baseUri}/target/${project.artifactId}-${project.version}.jar, - org.sonarsource.java|sonar-java-plugin|${test-it.sonarjava.version}, + org.sonarsource.java:sonar-java-plugin:${test-it.sonarjava.version}, diff --git a/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java b/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java index f865cc1..279e141 100644 --- a/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java +++ b/src/it/java/io/ecocode/java/integration/tests/LaunchSonarqubeAndBuildProjectIT.java @@ -218,6 +218,10 @@ 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)) @@ -226,9 +230,13 @@ private static Stream splitAndTrim(String value, String regexSeparator) } private static Set additionalPluginsToInstall() { - return commaSeparatedValues(systemProperty("test-it.plugins")) + 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() { @@ -262,9 +270,9 @@ private static Location toPluginLocation(String location) { throw new IllegalArgumentException(e); } } - List pluginGAVvalues = pipeSeparatedValues(location).collect(toList()); + List pluginGAVvalues = colonSeparatedValues(location).collect(toList()); if (pluginGAVvalues.size() != 3) { - throw new IllegalArgumentException("Invalid plugin GAV definition (`groupId|artifactId|version`): " + location); + throw new IllegalArgumentException("Invalid plugin GAV definition (`groupId:artifactId:version`): " + location); } return MavenLocation.of( // groupId From 8a2dd086e0fb9c7d5beaac7a28b008042ab570a1 Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 29 Oct 2024 16:20:15 +0100 Subject: [PATCH 43/45] Upgrade Java for Maven build (keep target compilation to Java 11) --- .github/workflows/build.yml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) 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: From 7cd4b19cc0c48751c16101dd10c28a3cc0fea2d0 Mon Sep 17 00:00:00 2001 From: jycr Date: Wed, 30 Oct 2024 23:48:44 +0100 Subject: [PATCH 44/45] Remove no longer necessary files --- .../.gitignore | 4 - .../LICENCE.md | 674 ------------------ .../README.md | 37 - .../tool_send_to_sonar.sh | 8 - 4 files changed, 723 deletions(-) delete mode 100644 src/it/test-projects/ecocode-java-plugin-test-project/.gitignore delete mode 100644 src/it/test-projects/ecocode-java-plugin-test-project/LICENCE.md delete mode 100644 src/it/test-projects/ecocode-java-plugin-test-project/README.md delete mode 100755 src/it/test-projects/ecocode-java-plugin-test-project/tool_send_to_sonar.sh diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/.gitignore b/src/it/test-projects/ecocode-java-plugin-test-project/.gitignore deleted file mode 100644 index b413004..0000000 --- a/src/it/test-projects/ecocode-java-plugin-test-project/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -!.gitignore -.* -target -*.iml diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/LICENCE.md b/src/it/test-projects/ecocode-java-plugin-test-project/LICENCE.md deleted file mode 100644 index 20d40b6..0000000 --- a/src/it/test-projects/ecocode-java-plugin-test-project/LICENCE.md +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - 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 . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/README.md b/src/it/test-projects/ecocode-java-plugin-test-project/README.md deleted file mode 100644 index b0da22d..0000000 --- a/src/it/test-projects/ecocode-java-plugin-test-project/README.md +++ /dev/null @@ -1,37 +0,0 @@ -Purpose of this project ---- - -To check locally all rules on java language. -To do this : - -- first launch local development environment (SonarQube) -- launch sonar maven command to send sonar metrics to local SonarQube -- on local SonarQube, check if each Java class contains (or not) the rule error defined for this class - -Step 1 : prepare local environment ---- - -To launch local environment : please follow https://github.com/green-code-initiative/ecoCode/blob/main/INSTALL.md -(especially SonarQube configuration part and get generated private token) - -Step 2 : compile and build ---- - -`./tool_build.sh` - -Step 3 : send Sonar metrics to local SonarQube ---- - -```sh -./tool_send_to_sonar.sh MY_SONAR_PORT MY_SONAR_TOKEN - -or - -mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=MY_SONAR_TOKEN -``` - -Step 4 : check errors ---- - -on local SonarQube, check if each Java class contains (or not) the rule error defined for this class -(for example : you can search for tag `eco-design` rule on a special file) diff --git a/src/it/test-projects/ecocode-java-plugin-test-project/tool_send_to_sonar.sh b/src/it/test-projects/ecocode-java-plugin-test-project/tool_send_to_sonar.sh deleted file mode 100755 index cb663d9..0000000 --- a/src/it/test-projects/ecocode-java-plugin-test-project/tool_send_to_sonar.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env sh - -# "sonar.token" variable (or sonar.login before SONARQUBE 9.9) : private TOKEN generated in your local SonarQube during installation -# (input paramater of this script) -mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.host.url=http://localhost:$1 -Dsonar.token=$2 - -# command if you have a SONARQUBE < 9.9 (sonar.token existing for SONARQUBE >= 10.0) -# mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar -Dsonar.login=$1 From 61e760386696de3bf7fc0a172a6c65452ca731e7 Mon Sep 17 00:00:00 2001 From: jycr Date: Wed, 30 Oct 2024 23:53:51 +0100 Subject: [PATCH 45/45] Update compatibility matrix --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index dff5905..1af3e3b 100644 --- a/README.md +++ b/README.md @@ -34,8 +34,8 @@ You can give a try with a one command: ... 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) - NB: To install other `ecocode` plugins, you can : + - 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. For example : @@ -57,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).