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.
Related
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).)*$".
I have one file which contains rules for the project.
I want my unit tests methods to be allowed to have underscore in their names.
Like myMethod_should_call_someClass_someMehod. Currently I have one configuration, which is applied to all files in the project.
My question is it possible to somehow configure checkstyle, so, for example I specify specific rules for all files that are ending with *Test.java.
Currently the only solution I found is to provide SuppressionFilter and exclude all files ending with *Test.java. But is there a way I could provide a different MethodNameCheck module with different format for test files?
You must define the MethodName check twice, with one instance checking the regular methods, and the other checking the test methods. Note the id property, which we will use to restrict the checks to their respective domains:
<module name="MethodName">
<property name="id" value="MethodNameRegular"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<module name="MethodName">
<property name="id" value="MethodNameTest"/>
<property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
</module>
Next, the regular check must be suppressed for test methods and vice versa. This works only if you have a criterion by which to distinguish between the two kinds of classes. I use the Maven directory convention, which puts regular classes under src/main and test classes under src/test. Here is the suppression filter file:
<!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress files="[\\/]src[\\/]test[\\/].*" id="MethodNameRegular" />
<suppress files="[\\/]src[\\/]main[\\/].*" id="MethodNameTest" />
</suppressions>
Building on barfuin's answer, I preferred not to have (yet) another XML file floating around. However, it is possible to configure suppressions directly in the CheckStyle XML config file:
<module name="SuppressionSingleFilter">
<metadata name="net.sf.eclipsecs.core.comment" value="Suppress MethodNameRegular check on unit tests"/>
<property name="files" value=".*[\\/]src[\\/]test[\\/]"/>
<property name="id" value="MethodNameRegular"/>
</module>
<module name="SuppressionSingleFilter">
<metadata name="net.sf.eclipsecs.core.comment" value="Suppress MethodNameTest check except on unit tests"/>
<property name="files" value=".*[\\/]src[\\/](?!test[\\/])"/>
<property name="id" value="MethodNameTest"/>
</module>
(This would be in addition to the two MethodName checks.)
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.
Reference: https://wiki.jasig.org/display/CASUM/RESTful+API
I would like to change the logic behind POST /cas/v1/tickets How would I go about doing that?
Basically, I need the logic to make an API call to a different software. Depending on the response to that call I decide whether or not the user authenticates correctly or not.
I see that in reslet-servlet.xml there is a TicketResource object associated to /tickets. Do I start there by inheriting it? Where do I start? Am I looking at the write file?
<bean id="root" class="org.restlet.ext.spring.SpringRouter">
<property name="attachments">
<map>
<entry key="/tickets">
<bean class="org.restlet.ext.spring.SpringFinder">
<lookup-method name="createResource" bean="ticketResource" />
</bean>
Thanks in advance.
Yes, it's a good way to start : inheriting from TicketResource and implementing your own logic in acceptRepresentation method...
I have the following three components defined in the Caste-Windsor XML configuration for my application:
<component id="StringFactory"
service="IStringFactory, MyApp"
type="DefaultStringFactory, MyApp"
lifestyle="singleton"
/>
<component id="TheString"
type="System.String"
factoryId="StringFactory"
factoryCreate="CreateString"
>
<parameters>
<name>SomeString</name>
</parameters>
</component>
<component id="TheTarget"
service="ITarget, MyApp"
type="TheTarget, MyApp"
lifestyle="transient"
>
<parameters>
<aString>${TheString}</aString>
</parameters>
</component>
And the following facility defined:
<facility id="factory.support"
type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.MicroKernel"
/>
When I run the application and set a breakpoint in the constructor of the TheObject class, the value passed in as the aString parameter is "${TheString}" when I expect it to resolve to the value of the component with that name.
Also, I have a breakpoint in the StringFactory constructor and CreateString method, neither of which are hit. I know the configuration is being used as other components are resolving correctly.
What am I missing or doing wrong here?
UPDATE
In light of the huge tangient this topic has taken, I've refactored the code above to remove anything to do with connection strings. The original intent of this post was about injecting a property with the value returned from a method on another object. Somehow that point was lost in a discussion about why I'm using XML versus code-based configuration and if this is a good way to inject a connection string.
The above approach is far from an original idea and it was pulled from several other discussions on this topic and our requirements are what they are. I'd like help understanding why the configuration as it is in place (whether the right approach or not) isn't working as expected.
I did verify that the first two components are being instantiated correctly. When I call Container.Resolve("TheString"), I get the correct value back. For whatever reason, The parameter syntax is not working correctly.
Any ideas?
While not a definitive solution to what I need to do in my application, I believe I've figured out what is wrong with the code. Or at least I've found a way to make it work which hints at the original problem.
I replaced the String type for TheString with a custom class. That's it. Once I did that, everything worked fine.
My guess is that it has something to do with the fact that I was trying to use a ValueType (primitive) as a component. I guess Castle doesn't support it.
So, knowing that's the case, I can now move on to figuring out if this approach is really going to work or if we need to change direction.
UPDATE
For the sake of completeness, I thought I'd go ahead and explain what I did to solve my problem AND satisfy my requirements.
As before, I have access to my configuration settings through an IConfigurationService defined as:
<component id="ConfigurationService"
service="MyApp.IConfigurationService, MyApp"
type="MyApp.RuntimeConfigurationService, MyApp"
lifestyle="singleton"
/>
This is automatically injected into my (new) IConnectionFactory which is responsible for generating IDbConnection objects based on the connection strings defined in the application's configuration file. The factory is declared as:
<component id="ConnectionFactory"
service="MyApp.Factories.IConnectionFactory, MyApp"
type="MyApp.Factories.DefaultConnectionFactory, MyApp"
lifestyle="singleton"
/>
In order to resolve what connection is used by my repository, I declare each connection as a component using the ConnectionFactory to create each instance:
<component id="MyDbConnection"
type="System.Data.IDbConnection,
System.Data, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"
factoryId="ConnectionFactory"
factoryCreate="CreateConnection"
lifestyle="transient"
>
<parameters>
<connectionStringName>MyDB</connectionStringName>
</parameters>
</component>
Notice the fully described reference to System.Data. I found this is necessary whenever referencing assemblies in the GAC.
Finally, my repository is defined as:
<component id="MyRepository"
service="MyApp.Repositories.IMyRepository, MyApp"
type="MyApp.Sql.SqlMyRepository, MyApp.Sql"
lifestyle="transient"
>
<parameters>
<connection>${MyDbConnection}</connection>
</parameters>
</component>
Now everything resolves correctly and I don't have ANY hard-coded strings compiled into my code. No connection string names, app setting keys or whatever. The app is completely reconfigurable from the XML files which is a requirement I must satisfy. Plus, other devs that will be working with the solution can manage the actual connection strings in the way they are used to. Win-win.
Hope this helps anyone else that runs into a similar scenario.
You don't really need XML registrations here, since you probably don't need to swap components or change the method used without recompiling. Writing a configurable app does not imply having to use XML registrations.
The problem with this particular XML registration you posted is that the connection string is a parameter, but it's treated like a service.
Doing this with code registrations is much easier, e.g.:
var container = new WindsorContainer();
container.Register(Component.For<IConfigurationService>().ImplementedBy<RuntimeConfigurationService>());
container.Register(Component.For<ITheRepository>().ImplementedBy<TheRepository>()
.LifeStyle.Transient
.DynamicParameters((k, d) => {
var cfg = k.Resolve<IConfigurationService>();
d["connectionString"] = cfg.GetConnectionString();
k.ReleaseComponent(cfg);
}));
Or if you don't want to depend on IConfigurationService, you could do something like:
container.Register(Component.For<ITheRepository>().ImplementedBy<TheRepository>()
.LifeStyle.Transient
.DependsOn(Property.ForKey("connectionString")
.Is(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["connName"]].ConnectionString))