Checkstyle issuing an indentation warning on an annotation? - java

I have an annotation like:
#ComponentScan(
basePackages = {
"com.example.foo",
"com.example.bar"
} // <--- false positive reported in this line
)
public class FooBar extends WebMvcConfigurerAdapter {
...
}
And a Checkstyle configuration of:
<module name="AnnotationUseStyle" />
<module name="Indentation">
<property name="basicOffset" value="2" />
<property name="braceAdjustment" value="0" />
<property name="caseIndent" value="2" />
</module>
When I run my project through Checkstyle, I get an error stating "assign child at indentation level 2 not at correct indentation, 4". This is referencing line 5 of my code example above, i.e. the closing parenthetical for the basePackages property.
What configuration change to Checkstyle would I need to make for this annotation to validate correctly?

It's a known issue in checkstyle: github.com/checkstyle/checkstyle/issues/553
As a workaround you can set lineWrappingIndentation property to zero:
<module name="Indentation">
<property name="lineWrappingIndentation" value="0"/>
</module>
But in this case you will also need to remove extra indentations after line breaks, e.g.
return getCalculator().
calculate(...);
instead of
return getCalculator().
calculate(...);

Related

Why are java interface constants treated as non-public by ConstantName check in Checkstyle

In our project we want to ensure that the private constants always start with _ (underscore) and rest all do not start with an underscore.
The checkstyle check ConstantName fails to treat the interface constants as public and applies the rules of private modifier.
We are using checkstyle 8.35 in our gradle project to analyse java code (OpenJdk 11, Gradle 6.4).
Below is the code snippet of Interface with constants.
public interface MyInterface() {
int MAX_SIZE = 1024;
//Some methods here
}
Checkstyle configuration for ConstantName check is as below
<module name="ConstantName">
<property name="format" value="^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>
<property name="applyToPrivate" value="false"/>
</module>
<module name="ConstantName">
<property name="format" value="^_[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>
<property name="applyToPublic" value="false"/>
<property name="applyToProtected" value="false"/>
<property name="applyToPackage" value="false"/>
</module>
Post running the checkstyle analysis the error is reported for MAX_SIZE as Name 'MAX_SIZE' must match pattern '^_[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'. while our expectation is No Errors.
Judging by a quick scan of the source code, this is a bug. They're only considering the constant to be public if the keyword public is present (which is the case in classes, but not interfaces).
I would suggest reporting this as an issue at https://github.com/checkstyle/checkstyle/issues

How can I limit an annotation 's target only to be 'ElementType.TYPE_USE',

How can I limit an annotation 's target only to be 'ElementType.TYPE_USE', and any other use would be rejected by 'maven checkstyle' plugin
I could only think of RegexpMultiline, if you want to do it with Checkstyle. You might configure it like so (regex):
<module name="RegexpMultiline">
<property name="format" value="\bElementType\s*\.\s*(?!TYPE_USE)\w+\b"/>
<property name="message" value="Illegal ElementType. Only TYPE_USE is permitted."/>
<property name="fileExtensions" value="java"/>
</module>
This solution is far from perfect, as it will also trigger on comments, and is not limited to annotations. Write a custom check if you need more control.

Exclude getters and setters from method count in CheckStyle

I got custom checkstyle.xml file with entry for MethodCount like this:
<module name="MethodCount">
<property name="maxTotal" value="20"/>
<property name="maxPrivate" value="10"/>
<property name="maxPublic" value="10"/>
<property name="severity" value="error"/>
</module>
However this creates a problem for huge model classes with getters and setters, which are provided by another web service. Can i somehow exclude this methods? Or is this considered a bad practice to not count those?
You can create suppression.xml file:
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files="\w*(Dto.java|Entity.java)\b" checks="MethodCount"/>
</suppressions>
And point it in checkstyle.xml
<module name="SuppressionFilter">
<property name="file" value="./suppression.xml"/>
</module>
Then you will suppress check MethodCount for files ending with Entity.java or Dto.java
AFAIK you cannot suppress only getters/setters. Generally, for data structures like entities or dtos it is not a problem for having more than 5 fields with getters and setters.
But if you have real objects adding setter/getters for each field is considering a bad practice.
Not very sure if it's what you need but you can ignore getter and setter methods from inspections:
Goto Settings (CTRL+Alt+S),
then Editor->Inspections->Java->Class metrics->Class with too many methods

Checkstyle check RegexpHeader: Does not allow me to assign a regex to the value of its property header

I a using RegexpHeader check from Checkstyle. I have a property header whose value I have set to
^(.|\n)*#.*ParamsAreNonNull$ .
The checkstyle throws an error:
cannot initialize module RegexpHeader - Cannot set property 'header' to '^(.|\n)*#.*ParamsAreNonNull$' in module RegexpHeader'
What could be the reason? This regex works perfectly on regex101.com and is the one that I want.
I changed the check to Regexp since the above check is only for single line apparently.
<module name="Regexp">
<property name="format" value="^(.|\n)*#.*ParamsAreNonNull$"/>
<property name="message" value="Annotation Not Found"/>
<property name="ignoreComments" value="true"/>
<property name="severity" value="error"/>
</module>
Error:
java.util.regex.Pattern$Loop.match(Pattern.java:4785)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4717)
at java.util.regex.Pattern$BranchConn.match(Pattern.java:4568)
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3777)
at java.util.regex.Pattern$Branch.match(Pattern.java:4604)

Single line braces in checkstyle gives error

I want Checkstyle in Java to not give me any errors for the following line of code -
if (true) { return 1; }
But it gives me errors, '}' should have line break before. and '{' should have line break after. My LeftCurly block is as follows:
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
My RightCurly is as follows:
<module name="RightCurly">
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
My NeedBraces is as follows:
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, LITERAL_IF, LITERAL_ELSE"/>
</module>
How do I allow single line blocks to have opening and closing braces on the same line? Thanks!
I'm using the Gradle Checkstyle plugin, Checkstyle version: 6.7
Your right curly option "same" means something different:
The brace should be on the same line as the next part of a multi-block statement
So for your case you should use the option alone_or_singleline:
<property name="option" value="alone_or_singleline"/>
See rcurly for more.
Also it is always a good idea to think about a consistent code style which avoids having exceptions! So think about another developer that will insert code some month later into your block - would be easier when the block is not on the same line.

Categories