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

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

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)

Use Hibernate Annotation on databean: Cannot add constraint to MySQL table

I try to add constraints to MySQL table via databeans using hibernate annotation:
package databean;
import javax.persistence.*;
#Entity
#Table(name = "ADMIN",
uniqueConstraints = {
#UniqueConstraint(columnNames = "userName"),
#UniqueConstraint(columnNames = "email")
})
public class AdminBean {
// Private fields
#Id #GeneratedValue
#Column(name = "adminId")
private int adminId; // PK
#Column(name = "userName")
private String userName;
I also have 2 xml files for mapping: hibernate.cfg.xml and Admin.hbm.xml
1)
mapping resource="hibernate/Admin.hbm.xml"/
2)
<hibernate-mapping>
<class name="databean.AdminBean" table="ADMIN">
<meta attribute="class-description">
This class contains the admin detail.
</meta>
<id name="adminId" type="int" column="adminId">
<generator class="native"/>
</id>
<property name="userName" column="userName" type="string"/>
<property name="firstName" column="firstName" type="string"/>
<property name="lastName" column="lastName" type="string"/>
<property name="email" column="email" type="string"/>
<property name="phone" column="phone" type="string"/>
<property name="password" column="password" type="string"/>
<property name="city" column="city" type="string"/>
<property name="zipCode" column="zipCode" type="string"/>
</class>
</hibernate-mapping>
According to what I've found online:
"So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations is the newest way to define mappings without a use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development." (http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm)
If I comment out the xml files mapping, I will get the exception of "Unknown entity: databean.AdminBean". Cannot even find the databean now.
Question:
1) Shouldn't the databean with hibernate annotations work even if there is no mapping in xml file? (So it does not even work now...)
2) If there is no hibernate annotation with databean, should I add constraints directly into the xml mapping file?
3) What is the best way to add constraints to MySQL tables? Since they are all automatically created when I run the application, it doesn't seem to make much sense to add constraints by building tables manually in mySQL first?
4) Is it really necessary to add constraints to both databean and (maybe) xml files?
Update:
Even when I try to set the property in xml file, mySQL database seems not to be able to "catch the constraints" and tables can still add duplicates items.
Now I doubt it might not be a problem with the way I add those constraints, but more like a "disconnection" with mySQL table and my code...though other parts can function pretty well. Anyone has faced similar situations before?
I find the reason: I did not drop the previous table when there is no constraint added when it is first created automatically by my app. Hope no one makes the same mistake. :)

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.

Java's checkstyle, MagicNumberCheck

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.