Misc v4.0.1

These checks address miscellaneous problems.

LocationReference

The LocationReference check helps in cases where the name of the current method or class must be used as an argument to a method call or as initial value of a declared variable. It compares the actual argument to the current method or class name, and flags it if a mismatch is detected.

Properties

methodCalls StringSet
Comma-separated list of method calls that should be covered by this check. Each element of the list must be the full method call as it occurs in the source file, ignoring whitespace and parentheses. For example, LogManager.getLogger. This property or variableNames must be set for this check to do anything. none (check is disabled)
variableNames StringSet
Comma-separated list of variable names whose declarations should be covered by this check. Each element of the list is a variable name as it occurs in the source file, For example, method. If a variable of one of the names specified by this property is declared anywhere, and its initial value is a String or Class literal, that literal is checked. This property or methodCalls must be set for this check to do anything. none (check is disabled)
location Location
The location information expected here. If set to method, the value is expected to be the exact name of the current method, or <init> in constructors, and <clinit> in static initializers. method
argumentPosition Integer
The position of the location reference as an index of the list of arguments of a method call, starting at zero. Negative values count from the end of the list, -1 being the last argument in the list. 0

Examples

The following example checks that the current method name is passed as the first argument to certain log methods, or given as a String literal in initializations of variables named method:

<module name="LocationReference">
  <property name="methodCalls" value="LOG.debug, LOG.enter, LOG.exit"/>
  <property name="variableNames" value="method"/>
</module>

In the next example, the getLogger method takes the current class as its first argument. The class shall be specified as a simple class object (e.g. MyClass.class). Just getClass() would not work. Calls where the argument is not a class object are ignored. Note the optional custom message, which allows tailoring the violation text to the particular use case:

<module name="LocationReference">
  <property name="methodCalls" value="LogManager.getLogger"/>
  <property name="location" value="classobject"/>
  <message key="locationreference.mismatch.classobject"
      value="Logger definition must reference the current class object, which is ''{0}.class''"/>
</module>

Parent Module

TreeWalker

ModuleDirectoryLayout

The ModuleDirectoryLayout check enforces a configurable directory structure in all modules of a project. It also checks that certain content is located in particular source folders. This is especially useful for large multi-module projects. By default, it is configured for a basic Maven Standard Directory Layout.

Overview

For the purposes of this check, the absolute path of any file checked by Checkstyle is composed of four parts:

D:\Projects\myproject\dir1\mymodule1\src\main\java\com\acme\MyClass.java

The example is given as a Windows path, but the same would work for UNIX style paths. In fact, it does not matter whether you specify the separators as slashes or backslashes.

This check uses a directories.json config file via the configFile property in order to list all possible MDL paths and the specific content they may contain.

Properties

baseDir String
Base directory to assume for the check execution, usually the project root .
configFile String
Location of the configuration file for this check. Relative paths are interpreted relative to the current directory of the Checkstyle analysis process, which is usually the project root. The configuration file is a JSON file with UTF-8 character set in the format described below.
If the specified file cannot be found or parsed, the check will be disabled.
Maven Directory Layout

Only these two properties are set in the check configuration. Everything else is configured via the directories.json file, which allows a central check definition (e.g. in SonarQube) to be used for many different projects, each of which features its own directories.json.

Format of directories.json

The configuration file is most easily understood by studying the default configuration, and using that as a starting point. The file must be UTF-8 encoded. It is composed of two mandatory sections: settings and structure.

settings:

structure:

The structure section contains a map whose keys are the MDL paths which can be present in each module. The value objects of the map may be empty, but they may also contain any of the following elements:

The allow and deny lists contain elements of the following form: { "type": "FileExtensions", "spec": "java" }. The type element may be one of the constants from MdlContentSpecType. The FromPath type may only occur in deny lists.

Validation

In order to be sure that your customized directories.json file is syntactically correct and does not violate any constraints, a small verification program is supplied for your convenience. Download a copy of checkstyle-addons-4.0.1-all.jar and checkstyle-8.0-all.jar (or any other compatible version), then run the validator from the command line:

java -cp checkstyle-addons-4.0.1-all.jar;checkstyle-8.0-all.jar com.thomasjensen.checkstyle.addons.checks.misc.MdlJsonConfigValidator path/to/my/directories.json

Examples

In the following example, the check is configured to ensure that a single-module project follows the Maven Directory Convention:

<module name="ModuleDirectoryLayout"/>

More typically, you will want to customize the check to allow for multi-module projects and specialized folder structures:

<module name="ModuleDirectoryLayout">
  <property name="baseDir" value="${workspace_loc}"/>
  <property name="configFile" value="config/directories.json"/>
</module>

The above example is for Eclipse, where ${workspace_loc} may be used to refer to the file system location of the current workspace. For SonarQube, you may use relative file paths. For the other environments, you may define a custom module property, which you dynamically set to the project directory. Example for Gradle:

checkstyle {
    configProperties 'workspace_loc': project.projectDir;
}

Parent Module

Important: This check goes directly under Checker, not under TreeWalker.

Checker

PropertyCatalog

The PropertyCatalog check helps to keep a property file in sync with a piece of code that contains the property keys. That piece of code is called the “property catalog”, and may be:

The property catalog and the properties file are expected to be connected to each other by a configurable naming convention.

Example

The property catalog code could look like this (other forms are possible, see below):

public enum PropertyCatalog {
  SomeConstant("zero"),
  AnotherConstant("two"),
  AThirdConstant("two"),  // Duplicate!
  YetAnotherConstant("three");

  private final int code;
  private PropertyCatalog(final int pCode) { code = pCode; }
  public int getKey() { return code; }
}

The constructor arguments of the enum constants are the keys to the property file, which in turn looks like this:

zero = Some text
one = Some more text
two = Could be anything
three = These values do not matter for the check.

In this example, the property with key one is orphaned, because it is not referenced by the property catalog. It would be flagged along with the duplicate reference to two.

Other forms of property catalogs

In a property catalog, the enum constants themselves may also be used as keys:

public enum PropertyCatalog {
  zero, one, two, three;
}

The property catalog can also consist of normal constants. Private constants are ignored.

public final class PropertyCatalog {
    public static final String SOME_CONSTANT = "zero";
    public static final String ANOTHER_CONSTANT = "one";
    public static final String A_THIRD_CONSTANT = "two";
    public static final String YET_ANOTHER_CONSTANT = "three";
}

Important: The keys in a property catalog must be simple literals of type String, int, long, or boolean. No arithmetic allowed, no method calls, no references to other constants. Just simple literals. Remember that Checkstyle works on source code.

Overview of the check

The check roughly works like this:

  1. Select the Java source files (called the property catalogs) to check. Only types which match the regular expression specified in selection are checked.
  2. The constants defined in the property catalog are read. Constants that match excludedFields are ignored.
  3. Using the template specified as propertyFile, the corresponding property file is located.
  4. Then, keys from the property catalog are compared to keys in the property file. Warnings are logged if any problems are found.

If the property catalog is a class or interface, the values of the defined constants are the property keys. If the property catalog is an enum, you can choose whether the enum constant itself shall be the key, or the first parameter passed to the enum constant’s constructor (via enumArgument). In a class, private constants are never considered.

This check find duplicate keys in the Java code, but not in the property file. Use UniqueProperties for that. It also does not help keep the translations of your property files in sync (e.g. file.properties, file_de.properties, file_fr.properties, etc.). Use Translation for that, and configure this check only for one of the property files.

Properties

selection regular expression
Select the Java files that are property catalogs. Each of these files must have a corresponding property file. The regular expression must match somewhere in the binary name of the type, so a property catalog may also be an inner class. Binary names are basically fully qualified class names; the simple names of inner classes are appended by $ signs, for example com.foo.Outer$Inner. ^(?!x)x (check is disabled)
excludedFields regular expression
Regex that matches excluded fields which should not be considered part of the property catalog. Choose the regex so that it matches the entire field name. Keep in mind that excludedFields is applied to the name of the constant, not the key. With the exception of an enum constant used as key, constant and key are two separate things (see examples above). serialVersionUID
enumArgument Boolean
Determines whether the property key shall be the enum constant itself (false), or the first argument of the enum constant's constructor (true). When the property catalog is not an enum, then this property is ignored. false
baseDir String
Base directory to assume for the check execution, usually the project root .
propertyFile String
Template for the property file path. Relative paths are resolved against the baseDir. In this template, the following placeholders may be used (examples are for com.foo.Bar$Inner):
{0}
the original binary class name (com.foo.Bar$Inner)
{1}
the binary class name as a path (com/foo/Bar/Inner)
{2}
fully qualified name of the outer class (com.foo.Bar)
{3}
fully qualified name of the outer class as a path (com/foo/Bar)
{4}
fully qualified name of the outer class as a path of ..'s (../../..)
{5}
the package name as a path (com/foo)
{6}
simple name of the outer class (Bar)
{7}
simple name of the inner class (Inner)
{8}
simple name of the first subdirectory below the baseDir on the path to the message catalog (subdir1). This placeholder, as well as {9} and {10} are useful if your project being analyzed consists of submodules.
{9}
simple name of the next subdirectory on the path to the message catalog (subdir2)
{10}
simple name of the third subdirectory on the path to the message catalog (subdir3)
{11}
This placeholder is special because it is dynamic. It is replaced by the empty String, {8}/, {8}/{9}/, and {8}/{9}/{10}/ (in that order). Once the property file is found, the location is used. If not, the next variation is checked. This is useful when the same Checkstyle configuration is used for multiple projects with different structures.
{12}
the relative path fragment between the baseDir and the package directories (e.g. module1/src/main/java)
(not set)
propertyFileEncoding String
Character encoding of the property file UTF-8
reportDuplicates Boolean
Report if two code references point to the same property? true
reportOrphans Boolean
Report if property entries are not referenced in the code? true
caseSensitive Boolean
If true, the property keys are treated as case sensitive; if false, case is ignored. true

Examples

In the following example, it is assumed that you have a naming convention which requires all property catalogs to have a type name that ends in Catalog. The corresponding property file is assumed to share the name of the Java file and reside in the same package, but under src/main/resources:

<module name="PropertyCatalog">
  <property name="selection" value="\wCatalog$"/>
  <property name="baseDir" value="${workspace_loc}"/>
  <property name="propertyFile" value="MyProject/src/main/resources/{1}.properties"/>
</module>

The above example is for Eclipse, where ${workspace_loc} may be used to refer to the file system location of the current workspace. For SonarQube, you may use relative file paths. For the other environments, you may define a custom module property, which you dynamically set to the project directory. Example for Gradle:

checkstyle {
    configProperties 'workspace_loc': project.projectDir;
}

Parent Module

TreeWalker