Excluding Java test files from SonarQube 4.1.1 analysis - java

I do not wand violations to be reported for Java test files in SonarQube, but I do want JUnit and Cobertura code coverage to be analyzed and displayed (JUnit and code coverage reports are reused, not executed by SonarQube).
How do I exclude test files from violations analysis only? I tried adding to global exclusion these settings, but they are not working:
**/test/**
**/Test*.*
Thanks

SonarQube can ignore issues on certain components and against certain coding rules. You might want to read the Ignore Issues on Multiple Criteria section in SonarQube Narrowing the Focus.
As mentioned in the documentation:
You can ignore issues on certain components and for certain coding rules.
Examples:
I want to ignore all issues on all files => *;**/*
I want to ignore all issues on COBOL program bank/ZTR00021.cbl => *;bank/ZTR00021.cbl
I want to ignore all issues on classes located directly in the Java package com.foo, but not in its sub-packages => ;com/foo/
I want to ignore all issues against coding rule cpp.Union on files in the directory object and its sub-directories => cpp.Union;object/**/*

Related

How can a consistent Java code format be enforced?

I'm looking for a way to force developers to use the same Java code formatting rules. My requirements are:
Gradle integration
Task that checks if code is correctly formatted. This will be used on CI to cause a build failure if incorrectly formatted code is submitted
Task that fixes incorrectly formatted code (nice-to-have)
IntelliJ integration
Incorrectly formatted code can be fixed within the IDE via the "Reformat Code" action
Code that is generated by the IDE (e.g. getter/setter generation) conforms to the rules
Supports the OpenJDK/Oracle Java formatting rules
Currently I'm using Spotless with the following configuration
spotless {
java {
toggleOffOn()
eclipse().configFile("${project.rootDir}/tools/eclipse-java-formatter.xml")
indentWithSpaces()
removeUnusedImports()
}
}
For IntelliJ integration, I've installed the Eclipse Code Formatter plugin and configured it to use the same rules as Spotless.
This approach meets all of the requirements above except for 2.2 i.e. any code generated by IntelliJ must be reformatted before it conforms to the formatting rules. A further problem is that the imports seem to be arbitrarily reordered when code is reformatted. This generates a lot of spurious changes which makes pull requests more difficult to review.
Is there another approach (e.g. CheckStyle) that does not suffer from these shortcomings?
You could use the Google Java Format, which has plugins for the aforementioned IDEs (IntelliJ IDEA, Eclipse), it provides integrations with tools such as Maven, Gradle, or SBT, and provides means to run the formatter as pre-commit hook or when pushing the code to Github with Github actions.
In their README they also mention the imports issue and how to fix it for IntelliJ IDEA, and more insights are provided e.g.: on how to handle it on Spotless Gradle plugin, when using the Maven Spotless plugin, or for Github actions.
A drawback for your specific case may be that the tool enforces the Google Java style guide, which was praised and recommended by the Oracle Java team as described in the Oracle Java magazine. It also provides the option to use the AOSP code style.
Below a snippet for spotless Gradle configuration, considering imports ordering:
spotless {
java {
importOrder() // standard import order
importOrder('java', 'javax', 'com.acme', '') // or importOrderFile
// You probably want an empty string at the end - all of the
// imports you didn't specify explicitly will go there.
removeUnusedImports()
googleJavaFormat() // has its own section below
eclipse() // has its own section below
prettier() // has its own section below
clangFormat() // has its own section below
licenseHeader '/* (C) $YEAR */' // or licenseHeaderFile
}
}
Checkstyle supports most of your requirements.
Gradle Integration:
plugins {
id 'checkstyle'
}
checkstyle {
toolVersion = checkstyleVersion
config = rootProject.resources.text.fromFile(checkstyleRulesRootPath) # Loads configuration from a file
ignoreFailures = false # Causes build to fail
maxWarnings = 0 # Fails even for warnings
}
It do not fixes code automatically (AFAIK).
IntelliJ integration:
There's Checkstyle plugin which you can configure to display warnings as you're coding.
You can also configure IntelliJ autoformatting to use these rules.
Formatting rules
Here is the configuration for Oracle/Sun specifications in checkstyle.
I think you can use it p3c plugin
I use formatter-maven-plugin and import-maven-plugin
Those plugins have validate/check goals that I use in our CI tool to validate incoming PRs.
They also have gradle variants. Checkout here
I can help you here. Mainly, you have asked two main problems here:
Incorrectly formatted code can be fixed within the IDE via the "Reformat Code" action
For this, you need to write a code template. We use a specific code template in our organisation. Now, you need to import this XML code template under Settings > Code Style.
Now the code will by default be formatted the way the template has been written.
Or use Ctrl +Shift+ F as the eclipse shortcut(enabled in intelliJ).
Support for the OpenJDK/Oracle Java formatting rules can be taken care of within the same template. Please refer their code template as default one provided in Eclipse.
Code that is generated by the IDE (e.g. getter/setter generation) conforms to the rules
This link will help. Please explore more on how to write the custom code templates.
To restrict all the developers to not to push the wrong format of the code, you need to write a GIT hook. It will not allow the code to be pushed unless the code complies with basic rules provided in the custom script of the hook. Nobody needs to do anything on local intelliJ, the git hook will act from the remote GIT repo. Here is one supporting link.
I have provided crisp information here because it is more the matter of customized rules that will be there in your code templates.
Other questions:
Task that checks if code is correctly formatted. This will be used on CI to cause a build failure if incorrectly formatted code is submitted.
When you will restrict the committed code using git hooks, there shall never be any code unformatted on the repo. So, you don't need it as part of CI build.
It may be done by providing a pipeline script that will trigger a method having the git location of your code. It looks a tedious thing to me.
Hope, all your questions are answered.

Does jacoco detect unused classes

Jacoco, as all other profiling capabilities in java I know of, depends on java agents/instrumentation.
Java instrumentation can only impact bytecode when a class is loaded.
I wonder if it is somehow possible to detect unused classes with Jacoco? Obviously, there might be classes that are "dead" and are in turn, never loaded by the ClassLoader.
When coverage output (HTML report, etc.) is generated after the test run has executed, JaCoCo scans additional classes in the runtime classpath that haven't been loaded during test execution, so they can also be instrumented and included in the output.
I implemented this same mechanism in my own code coverage tool (JMockit Coverage), which also relies on java.lang.instrument. It's the only way to have all relevant classes instrumented for coverage.
Yes, though it might be easier to specify -verbose:class if you are not already using Jacoco.
I just ran a test: I created a file called Delete.java that is never called by any other method. The generated Jacoco report shows the Delete class with 0% coverage.

Running a code with JUnit Test Cases

I have checked out a code from CVS and need to make changes to it. The code has 2 folders
Java
Test
The later has JUnit test cases. I'm not very familiar with JUnit but as far as my understanding is, the classes are duplicated in JUnit as class names. That's why I get the error in the test folder.
Class "xxxxx" already exists
I'm not sure how do I run this project without removing the folder test. Is there a way I can make eclipse ignore the JUnit test cases for now?
Go into the properties of the Eclipse project, open Java Build Path / Source and remove folder Test. Eclipse will then ignore the sources in that folder.
Test and normal java classes are merged together during build time, your error happens because the test classes have the exact same name as the normal classes. You should rename your test cases with some kind of prefix like Test to prevent them conflicting.
Doing things to work around the problem will only conflict later when you are changing the build platform, maybe your current build platform accepts it, but your future platform/editor may not, and then you have the real problems.

What is the difference between emma.jar ,emma_ant.jar and emma_device.jar?

Now ,I have a test project need using emma.
But when I open the "$ANDROID_HOME/sdk/tools/lib" path, I found three emma*.jar.
It's emma.jar, emma_ant.jar, emma_device.jar.
But anybody can tell me what's there difference ?
Thanks
Here is a partial answer, about two of the three jars :
emma.jar Contains the implementation of EMMA core components command
line tools, and EMMA runtime classes (EMMA classes that are needed by
Java application code that has been instrumented for coverage).
emma_ant.jar Contains the implementation of EMMA ANT tasks (this
archive depends on emma.jar and does not overlap with it in content).
See Emma Reference Manual

"Hide" a maven artifact from the eclipse autocomplete

For reasons I don't even want to begin to get into.. I have a maven hierarchy that looks like the one below. In a nutshell, everything requires commonslang3, except one ancient artifact that requires commonslang2.
We have no issues with compile or runtime, the dependencies work as expected. The challenge we are having is at development time.
We'd like to ensure everyone on the team uses the commonslang3 APIs, but occasionally (because of the ancient artifact and Eclipse auto suggest), someone accidentally uses the commonslang2 APIs.
Normally, we would just force the desired version in our POM, but commonslang is a special snowflake. The package signature changed between comonslang2 and commonslang3, which means we would have compile failures if we excluded the older library. E.g.,
org.apache.commons.lang3.StringUtils
org.apache.commons.lang.StringUtils
My question is this, how can I configure maven/Eclipse, to use commonlang2 as needed during compile... but not populate it in the Eclipse class autosuggest list? My desired end state is that someone types 'stringuti' + ctrl + space, and the only option they see is commonslang3. I am aware that each developer can remove individual classes via (Window->Preferences->Java->Appearance->Type Filters) but that is not a viable solution for two reasons: 1) It's a large team with frequently changing resources... 2) I need an entire artifact removed, as in hundreds of classes.
Example Tree:
MyWar
-- MyModuleJar1
-- ...
-- MyModuleJar2
-- LibA
-- commonslang
-- ...
-- LibB
-- commonslang3
-- ...
-- LibC
-- commonslang3
-- ...
-- ...
In Eclipse:
Window->Preferences->Java->Appearance->Type Filters
Add org.apache.commons.lang.*
Because you want to affect auto-complete which is a function of the IDE, you are forced to change the setting in the IDE. You can export the preferences and share them of the rest of the team.
There is not much you can do about it in Eclipse other than type filters #JustinKSU mentioned.
But with Maven you can use Takari to access rules to prevent accidental inclusion of transitive dependencies. Of course this comes with a plethora of caveats with one ironically being that the Eclipse JDT compiler has to be used instead of plain javac.

Categories