How do I alter checkstyle configuration file when using sonar? - checkstyle

I'm trying to suppress specific checkstyle warnings in my code. The default way seems to be to wrap code in comments eg: // CHECKSTYLE:OFF ... // CHECKSTYLE:ON. At the very least I'd like to give a reason for which I found the follow post. I don't know where the configuration file would be when using sonar, can anyone help?
How can you suppress checkstyle checks within a block of code only for specific rules?
Recommend reading the documentation on SuppressionCommentFilter (it is buried at bit) for lots of examples.
An example of how to do configure the filter is:
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CSOFF: ([w|]+)"/>
<property name="onCommentFormat" value="CSON: ([w|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
You can then use the following to turn off the RequireThis check for a block of code:
// CSOFF: RequireThis
... code
// CSON: RequireThis

Login to Sonar as admin, then go to "Settings" (link at top-right, next to your username), select the "Java" category, then the "CheckStyle" tab.
After that, enter the <module> section from your post above into the "Filters" textarea.

Related

checkstyle disallow SuppressWarnings annotation unless there is a comment nearby

In our project, we sometimes have to have some warnings suppressed (e.g. "WeakerAccess" might be suppressed as project is also used as a lib in another project, or "expression is always false" for instanceof a checked exception that is thrown from a lib that masks the fact of throwing that exception).
On the other hand, it's not good to just add a suppression, as it might be unclear why is it there. So, I'd like to add a checkstyler rule that would only allow SuppressWarnings annotation if there is a comment nearby. That should be enough for people to start adding explanations.
But I can't find a way to do that. There is this block:
<module name="SuppressWarnings">
<property name="format"
value="^unchecked$|^unused$"/>
<property name="tokens"
value="
CLASS_DEF,INTERFACE_DEF,ENUM_DEF,
ANNOTATION_DEF,ANNOTATION_FIELD_DEF,
ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF
"/>
</module>
and some stuff about special comments to turn off checkstyler for a line, but it is just another suppress warnings thing that would need an explanation as well... But is there a way to say that suppression is OK if there is any comment nearby (on a line before or on the same line)?
I recommend using 2 checks in unison. Use SuppressWarningsCheck to flag the methods you want documented and display an error message that says it is a violation because it is not documented. Then use SuppressWithNearbyCommentFilter to suppress violations of the other check when documentation is added. For the filter to work, the documentation must start with a specific text so it doesn't falsely suppress SuppressWarnings that don't really have a documentation.
Example:
$ cat TestClass.java
public class TestClass {
//SuppressWarnings: this is my reason for the suppression
#SuppressWarnings("unchecked")
void method() {
}
//this is just a comment and not a reason
#SuppressWarnings("unused")
void method2() {
}
#SuppressWarnings("unused")
void noComment() {
}
}
$ cat TestConfig.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<module name="TreeWalker">
<module name="SuppressWarnings">
<property name="format" value="^(unchecked|unused)$"/>
<message key="suppressed.warning.not.allowed"
value="The warning ''{0}'' cannot be suppressed at this location unless a comment is given for the reason for the suppression." />
<property name="tokens" value="CLASS_DEF,INTERFACE_DEF,ENUM_DEF,ANNOTATION_DEF,ANNOTATION_FIELD_DEF,ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF"/>
</module>
<module name="SuppressWithNearbyCommentFilter">
<property name="commentFormat"
value="SuppressWarnings: .{10,}"/>
<property name="checkFormat" value="SuppressWarnings"/>
<property name="influenceFormat" value="3"/>
</module>
</module>
</module>
$ java -jar checkstyle-8.18-all.jar -c TestConfig.xml TestClass.java
Starting audit...
[ERROR] TestClass.java:8:23: The warning 'unused' cannot be suppressed at this location unless a comment is given for the reason for the suppression. [SuppressWarnings]
[ERROR] TestClass.java:12:23: The warning 'unused' cannot be suppressed at this location unless a comment is given for the reason for the suppression. [SuppressWarnings]
Audit done.
Checkstyle ends with 2 errors.
You'll notice there are 2 violations but 3 SuppressWarnings. The first example shows how to correctly suppress that there is no documentation. The 2nd shows just a comment but not a documentation on the suppression, and the 3rd shows no comment at all.
<property name="format" value="^(unchecked|unused)$"/>
This specifies only documentation will be required for unchecked and unused suppressions. If you want documentation for all types but those 2, I recommend the expression "^((?!unchecked|unused).)*$".

checkstyle - prohibit initializing object of type

suppose I have an external library with a class called Foo. I can't change Foo to have a private constructor, but I have a FooFactory class that I wrote.
So I have FooFactory.getAFoo() but I want checkstyle to catch any new Foo() in the rest of my code, to force using the factory.
I have this:
<module name="IllegalTokenText">
<property name="tokens" value="LITERAL_NEW"/>
<property name="format" value="Foo"/>
</module>
but this doesn't seem to detect a new Foo().
I could use a regex but this is much cleaner.
I had a similar problem with preventing extending a class:
<module name="IllegalTokenText">
<property name="tokens" value="EXTENDS_CLAUSE"/>
<property name="format" value="AndroidTestCase"/>
</module>
Neither of these checkstyle module seem to do anything at all.
What am I doing wrong?
IllegalTokenText checks for illegal text on the token itself, not on subsequent IDENT tokens or some such. So that is why it seems to do nothing in your case.
In your case, you may want to try using the SevNTU Checkstyle extension, which offers a check called ForbidInstantiation which might solve your problem. They have no documentation that I am aware of, so I am linking the source code with Javadoc. When you use SevNTU Checkstyle, be sure to use the right versions of regular Checkstyle and SevNTU Checkstyle, because not all combinations are compatible (overview).
If that does not help, you will have to roll your own.

CAS primaryAuthenticationHandler ldapAuthenticationHandler

I think I've exhausted searching and need to ask this seemingly very popular question about CAS configuration for Active Directory. I followed the steps on CAS docs to modify the deployerConfigContext.xml to include the ldapAuthenticationHandler bean.
But seems like CAS is continuing to use AcceptUsersAuthenticationHandler defined in the same file in the primaryAuthenticationHandler tag.
Question: So basically I need to replace AcceptUsersAuthenticationHandler with ldapAuthenticationHandler as the default authenticator. What is the correct syntax to do so in the following snippet?
<bean id="primaryAuthenticationHandler"
class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">
<property name="users">
<map>
<entry key="casuser" value="Mellon"/>
</map>
</property>
</bean>
This is what I have tried so far:
<bean id="primaryAuthenticationHandler" class="org.jasig.cas.authentication.LdapAuthenticationHandler"></bean>
java.lang.NoSuchMethodException: org.jasig.cas.authentication.LdapAuthenticationHandler.<init>()
<bean id="primaryAuthenticationHandler" class="org.jasig.cas.authentication.ldapAuthenticationHandler"></bean>
java.lang.ClassNotFoundException: org.jasig.cas.authentication.ldapAuthenticationHandler
<bean id="primaryAuthenticationHandler" class="ldapAuthenticationHandler"></bean>
java.lang.ClassNotFoundException: ldapAuthenticationHandler
Did you add the dependency in pom.xml?
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-support-ldap</artifactId>
<version>${cas.version}</version>
</dependency>
Indeed, LdapAuthenticationHandler doesn't implement a default constructor, you need to configure a org.ldaptive.auth.Authenticator on the attribute c:authenticator-ref:
<bean id="ldapAuthenticationHandler"
class="org.jasig.cas.authentication.LdapAuthenticationHandler"
p:principalIdAttribute="mail"
c:authenticator-ref="authenticator"/>
LDAP authentication is not as simple as the default hardcoded user/password authentication handler. In this link you can see an example on how to configure a connection to Active Directory: Active Directory Authentication
Following the example, you will find in "LDAP Properties Starter" some properties defined. You will need to copy them to the file cas.properties on the same folder as deployerConfigContext.xml. You have to adjust the properties to your usecase and be aware that some of the properties names don't correspond with the ones on the xml examples.

How can I add Snapshot and test variations to my ivy.xml

I'm using ant+ivy+nexus to build and publish my java OSGi projects (just good old jars if you're unfamiliar with OSGi). After the usual mind-melting period one has when engaging with new tech I've got a mostly functional system. But, I now have two dimensions of artifact variation: snapshot/release and main/test.
The main/test dimension speaks for itself really. The snapshot/release is essential for publishing into nexus in a maven-friendly way. (Extremely useful for integration with open-source OSGi runtimes). So, I have the following artifacts on a per-project basis, and I have many many projects:
project-revision.xml (bp)
project-test-revision.xml (b)
project-revision-SNAPSHOT.xml (bp)
project-test-revision-SNAPSHOT.xml (b)
b = successfully building
p = successfully publishing
(I haven't yet got the test stuff publishing correctly)
It's taken me a while to get that far without duplicating code everywhere in my build scripts, but I've managed it... with one big caveat. For the SNAPSHOT branch I append "-SNAPSHOT" to all revisions. In ant I manage to achieve this programatically, but for ivy I'm using a duplicated ivy.xml; ivy-SNAPSHOT.xml. This has
<info ... revision="x.x-SNAPSHOT">
Notice the -SNAPSHOT. Without this I could never get my
<ivy:deliver>
<ivy:resolve>
<ivy:publish>
chain of commands to correctly publish artifact and maven pom. (Remember I have a requirement to make this maven friendly... I'll be damned if I actually end up using maven to build it mind!)
Now I'm stuck introducing the test/main dimension. I'm ideally looking to publish
project-test-revision(-SNAPSHOT).jar
(Note the optional snapshot). I really don't want to do this by specifying
<info ... module="project-test" ... >
as opposed to <info ... module="project" ... > in yet another ivy file. If I went this route (like I've already started) then I simply end up with loads of ivy-Option1-Option2...-OptionN.xml files. With each new two-value variation doubling the number of build and ivy files. That's crap. There's got to be a better way. I just can't find it.
If you have managed to successfully get ivy publishing artifacts with embellished names from one ivy file, would you mind posting the configuration snippets that achieve this? Would be extremely useful. (Don't forget maven won't know about configurations so I need to get the variations into the filename and pom).
Many thanks
Alastair
Ok, update: I've now got the artifact publishing. I struggled a little while I had the test conf extending the default conf. I'd get a complaint during publishing that the default configuration artifacts weren't present... something I don't care about while only publishing the test case. By making them independent but overlapping I get back fine-grain control of what to publish.
BUT!!!!! There's no viable test pom - that's NOT publishing yet. Well, actually it does publish, but it contains data for the non-test case. So this is still not maven friendly. If anyone has suggestions on this that'd be great.
either way, the code I'm now using, in case it helps you too:
ivy.xml:
<info
organisation="MY_ORGANISATION"
module="MY_PROJECT"
status="integration"
revision="1.0-SNAPSHOT">
</info>
<configurations>
<conf name="default" description="Default compilation configuration; main classes only" visibility="public"/>
<conf name="test" description="Test-inclusive compilation configuration. Don't forget to also add Default compilation configuration where needed. This does not extend default conf" visibility="public"/>
</configurations>
<publications>
<artifact name="MY_PROJECT type="jar" ext="jar" conf="default"/>
<artifact name="MY_PROJECT type="pom" ext="pom" conf="default"/>
<artifact name="MY_PROJECT-test" type="jar" ext="jar" conf="test"/>
<artifact name="MY_PROJECT-test" type="pom" ext="pom" conf="test"/>
</publications>
<dependencies>
<dependency org="MY_ORGANISATION" name="ANOTHER_PROJECT" rev="1.0-SNAPSHOT" transitive="true" conf="*"/>
<dependency org="junit" name="junit" rev="[4,)" transitive="true" conf="test->*"/>
</dependencies>
build.xml:
<property name="project.generated.ivy.file" value="SNAPSHOT_OR_RELEASE_IVY_XML_FILE" />
<property name="ivy.publish.status" value="RELEASE_OR_INTEGRATION" />
<property name="project.qualifier" value="-SNAPSHOT_OR_EMPTY" />
<property name="ivy.configuration" value="DEFAULT_OR_TEST" />
<target name="publish" depends="init-publish">
<ivy:deliver
deliverpattern="${project.generated.ivy.file}"
organisation="${project.organisation}"
module="${project.artifact}"
status="${ivy.publish.status}"
revision="${project.revision}${project.qualifier}"
pubrevision="${project.revision}${project.qualifier}"
conf="${ivy.configuration}"
/>
<ivy:resolve conf="${ivy.configuration}" />
<ivy:makepom
ivyfile="${project.generated.ivy.file}"
pomfile="${project.pom.file}"
/>
<ivy:publish
resolver="${ivy.omnicache.publisher}"
module="${project.artifact}"
organisation="${project.organisation}"
revision="${project.revision}${project.qualifier}"
pubrevision="${project.revision}${project.qualifier}"
pubdate="now"
overwrite="true"
publishivy="true"
status="${ivy.publish.status}"
artifactspattern="${project.artifact.dir}/[artifact]-[revision](-[classifier]).[ext]"
conf="${ivy.configuration}"
/>
</target>

JavadocPackage usage in checkstyle

I am in the process of converting my checkstyle version 4.0 configurations to version 5.0. Hence, I have added the following to replace older "PackageHtml",
<module name="JavadocPackage">
<metadata name="com.atlassw.tools.eclipse.checkstyle.lastEnabledSeverity" value="info"/>
<property name="allowLegacy" value="true"/>
<property name="severity" value="info"/>
</module>
What happens is, I get a info message saying "Missing package-info.java" even though I have the following comments on top of my java file,
/*
* File: Test.java
* System: PF Tools
* Module: com.research.usage
* Author: jadaaih
* Copyright: Jadaaih
* Last modified by: jadaaih
* Date: 2009-03-02 15:30:24
* Version: 1.1
* Description:
* Preconditions:
*/
I am sorry the display is distorted, the comments have newline at the end.
Please advise on how to get rid of that checkstyle info message in Checkstyle 5.0 compliant with 4.0.
Browsing the documentation it looks to me that your metadata element is pointless. Perhaps it even provokes the checkstyle parser to ignore the JavadocPackage configuration.
Also, when the allowLegacy property is set (it's false by default), you specify that you want to use a package.html file. It is not allowed to have both a package.html and package-info.java files.
Edit:
I have just tested the above. It seems that the error is misleading. What it actually means is that a package.html file is missing :) Just add it and the warning will disappear.
In my case it was just missing the file package-info.java inside the particular package.
Since I use Eclipse, I have created it by creating a new package, ticking the box "Create package-info.java" and then moving the package-info.java into the package where I was getting the Checkstyle warning. If not using Eclipse then you can manually create a file called package-info.java.
The content of my package-info.java looks like
/**
*
*/
/**
* #author Me
*
*/
Cheers!
The package-info.java is a separate java file that is used for package-level documentation. You can manually create one, it simply contains any information about the java files that your package is going to have. This information will be a part of the generated javadoc.
If you're using an IDE like eclipse or netbeans, you get an option while you create a new package, like this -
The file looks like this-
/**
* package description to be a part of java-doc
*/
/**
* #author shashi
*
*/
package com.checkstyle.test;