Java's checkstyle, MagicNumberCheck - checkstyle

I am using checkstyle to get reportings about my source-code. This question is about the MagicNumberCheck.
I am using Date/(org.joda.)DateTime in my source code like this:
DateTime dateTime = new DateTime(2013, 2, 27, 23, 0):
dateTime.plusHours(57);
Is there a way to suppress the MagicNumberCheck notifications if the magic number is within a Date or DateTime?

You can use SuppressionCommentFilter check to do this.
Configure the properties values like (in your checkstyle configuration file)
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="Check\:OFF\: ([\w\|]+)"/>
<property name="onCommentFormat" value="Check\:ON\: ([\w\|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
Now for the required lines, you can do like
//Check:OFF: MagicNumber
DateTime dateTime = new DateTime(2013, 2, 27, 23, 0):
dateTime.plusHours(57);
//Check:ON: MagicNumber
This will only suppress MagicNumber checks, the rest checks will work here.
You can suppress Multiple checcks too, like
//Check:OFF: MagicNumber|Indentation
Code Here
//Check:ON: MagicNumber|Indentation
this will suppress only MagicNumber and Indentation Checks. Other checks will work fine.

You can supress CheckStyle notifications by using the comment
//CHECKSTYLE:OFF
before those lines and
//CHECKSTYLE:ON
afterwards to reenable it.
This requires the module SuppressionCommentFilter to be enabled.
Of course you could also create your own module that does exactly what you want.

Related

Wildfly json-formatter class name metadata

Is it possible to configure a non-static value for the metadata field in the wildly json-formatter?
I didn't find anything about it in the wildfly documentation- it only has a simple static field example (meta-data=[#version=1])
For example, I would like to have a field "simpleClassName" - The class of the code calling the log method.
I also tried to use a similar syntax to pattern-formatter(example below) but it doesn't work
<formatter name="JSON">
<json-formatter>
<meta-data>
<property name="simpleClassName" value="%c{1}"/>
</meta-data>
</json-formatter>
</formatter>
No the meta-data is only static information. However what you're looking for seems to be the details of the caller. Note that this is an expensive operation should you should use it with caution. What you'd want to do is change the print-details to true. In CLI it would be something like:
/subsystem=logging/json-formatter=JSON:write-attribute(name=print-details, value=true)

Is there a checkstyle rule for forcing every field in a class to have an annotation?

We want to make compliance easy and for FedRAMP want something like this on all fields in our database objects
#FedRamp(confidentiality=LOW, integrity=MODERATE, availability=HIGH)
We want checkstyle to break the builds if people add data and forget to add these on 'any' field in the *Dbo.java class. Then, we can generate the FedRAMP compliance on each data item (and therefore the entire system). We run checkstyle on every class but only want this rule run on classes ending in *Dbo.java. Is this possible where we import some already existing checkstyle rule or plugin and add the class name filter to it?
thanks,
Dean
To report violations for such cases for any classes, you can use MatchXpathCheck (you need checkstyle 8.39+)
Config will look like:
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name = "Checker">
<module name="TreeWalker">
<module name="MatchXpath">
<property name="id" value="fedramp_check"/>
<property name="query" value="//CLASS_DEF/OBJBLOCK/VARIABLE_DEF/MODIFIERS/ANNOTATION/IDENT[not(#text='FedRamp')]"/>
<message key="matchxpath.match"
value="Field should have 'FedRamp' annotation."/>
</module>
</module>
</module>
This will report violations like this:
$ cat Test.java
class Test {
#FedRamp(confidentiality=LOW, integrity=MODERATE, availability=HIGH)
private int withAnnotation = 11; // no violation
#Fed(confidentiality=LOW, integrity=MODERATE, availability=HIGH)
private int without = 11; // violation
#NotNull
int without = 11; // violation
}
$ java -jar checkstyle-8.42-all.jar -c config.xml Test.java
Starting audit...
[ERROR] C:\workdir\Test.java:6:4: Field should have FedRamp annotation. [fedramp_check]
[ERROR] C:\workdir\Test.java:9:4: Field should have FedRamp annotation. [fedramp_check]
Audit done.
Checkstyle ends with 2 errors.
Second part of your question - narrow execution only to specific classes - can be solved in several ways.
Use a bit different xpath to filter class names (not files, since there can be many classes in single file)
<property name="query"
value="//CLASS_DEF[./IDENT[ends-with(#text,
'Dbo')]]/OBJBLOCK/VARIABLE_DEF/MODIFIERS/ANNOTATION/IDENT[not(#text='FedRamp')]"/>
Use BeforeExecutionExclusionFileFilter - it is filter for whole config and will work ok only if you have a separate config only for checking annotation thing.
Suppress violations for this check (by id, for example) for other class files, see doc

Checkstyle CustomImportOrder more than 3 definable groups?

My company's Java import order standard would require more than the three definable groups that I see in checkstle, which are STANDARD_JAVA_PACKAGE, THIRD_PARTY_PACKAGE, and SPECIAL_IMPORTS. My question has two parts:
Is there a way to define more custom regular expressions, or use regexes directly in the VALUE for customImportOrderRules?
Can I do this at all, since com.our_company is supposed to come after all the other com. imports.
The import rules are approximately
Static imports
java.*
javax.*
com.* EXCEPT our company
nthing.*
org.*
pthing.*
com.mycompany.*
anything else
Since we also enforce blank lines between groups, I can't combine 5, 6, and 7 into one and depend on sort order to keep things clean. Worst case is that we already have this defined in Intellij and just have to remember to auto-order imports every time.
Answering your questions:
According to this ticket it looks like there is no way to achieve what you need using just CustomImportOrder. Instead you should use ImportOrder, complete example below.
It is possible using ImportOrder
This should work for your case:
<module name="ImportOrder">
<property name="option" value="top"/>
<property name="groups" value="/^java\./,javax,/^com\.(?!mycompany)/,nthing.org,pthing,com.mycompany"/>
<property name="ordered" value="true"/>
<property name="separated" value="true"/>
<property name="separatedStaticGroups" value="true"/>
<property name="sortStaticImportsAlphabetically" value="true"/>
</module>
Small clarification. Inside the groups property there are two groups /^com\.(?!mycompany)/ and com.mycompany, first one is the regexp that use negative look-ahead, second one is just common prefix string for the import.

Checkstyle - limit method exit points to five

We are allowing up to five return statements pro method. Is there a check rule that would give me a waring if method has more then five return statements?
ps. please do not start discussion on "why would I allow more then one exit point" ;)
Yes, there is the ReturnCount check. Configure like this:
<module name="ReturnCount">
<property name="max" value="5"/>
</module>
You can also give it the names of methods that are ignored by the check (see linked docs).

How to create CheckStyle Check for validating Annotation Fields

#WebService(serviceName="TestImpl",
targetNamespace = "http://example.org"
)
public class TestImpl implements Test{
If my Test class is something like above my check should verify if the targetNamespace value always starts with "http://"
If no existing checks can do that how should my Custom check look like?
You can do this using Checkstyle out of the box by applying a RegexpMultiline check like this:
<module name="RegexpMultiline">
<property name="format"
value="(?s)#WebService\s*\(.*?targetNamespace\s*=\s*"(?!http:\/\/).{7}"/>
<property name="message"
value="Target namespace must start with "http://""/>
</module>
Here's an explanation of the regex.