Class ImportControlCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
,ExternalResourceHolder
public class ImportControlCheck extends AbstractCheck implements ExternalResourceHolder
Controls what can be imported in each package and file. Useful for ensuring that application layering rules are not violated, especially on large projects.You can control imports based on the package name or based on the file name. When controlling packages, all files and sub-packages in the declared package will be controlled by this check. To specify differences between a main package and a sub-package, you must define the sub-package inside the main package. When controlling file, only the file name is considered and only files processed by TreeWalker. The file's extension is ignored.
Short description of the behaviour:
-
Check starts checking from the longest matching subpackage (later 'current subpackage') or
the first file name match described inside import control file to package defined in class file.
- The longest matching subpackage is found by starting with the root package and examining if any of the sub-packages or file definitions match the current class' package or file name.
- If a file name is matched first, that is considered the longest match and becomes the current file/subpackage.
- If another subpackage is matched, then it's subpackages and file names are examined for the next longest match and the process repeats recursively.
- If no subpackages or file names are matched, the current subpackage is then used.
- Order of rules in the same subpackage/root are defined by the order of declaration in the XML file, which is from top (first) to bottom (last).
- If there is matching allow/disallow rule inside the current file/subpackage then the Check returns the first "allowed" or "disallowed" message.
- If there is no matching allow/disallow rule inside the current file/subpackage then it continues checking in the parent subpackage.
- If there is no matching allow/disallow rule in any of the files/subpackages, including the root level (import-control), then the import is disallowed by default.
The DTD for an import control XML document is at https://checkstyle.org/dtds/import_control_1_4.dtd. It contains documentation on each of the elements and attributes.
The check validates a XML document when it loads the document. To validate against the above DTD, include the following document type declaration in your XML document:
<!DOCTYPE import-control PUBLIC "-//Checkstyle//DTD ImportControl Configuration 1.4//EN" "https://checkstyle.org/dtds/import_control_1_4.dtd">
-
Property
file
- Specify the location of the file containing the import control configuration. It can be a regular file, URL or resource path. It will try loading the path as a URL first, then as a file, and finally as a resource. Type isjava.net.URI
. Default value isnull
. -
Property
path
- Specify the regular expression of file paths to which this check should apply. Files that don't match the pattern will not be checked. The pattern will be matched against the full absolute file path. Type isjava.util.regex.Pattern
. Default value is".*"
.
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
import.control.disallowed
-
import.control.missing.file
-
import.control.unknown.pkg
- Since:
- 4.0
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private AbstractImportControl
currentImportControl
The package controller for the current file.private URI
file
Specify the location of the file containing the import control configuration.private String
fileName
The file name doing the import.static String
MSG_DISALLOWED
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_MISSING_FILE
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_UNKNOWN_PKG
A key is pointing to the warning message text in "messages.properties" file.private String
packageName
The package doing the import.private Pattern
path
Specify the regular expression of file paths to which this check should apply.private boolean
processCurrentFile
Whether to process the current file.private PkgImportControl
root
The root package controller.private static String
UNABLE_TO_LOAD
A part of message for exception.
-
Constructor Summary
Constructors Constructor Description ImportControlCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
beginTree(DetailAST rootAST)
Called before the starting to process a tree.int[]
getAcceptableTokens()
The configurable token set.int[]
getDefaultTokens()
Returns the default token a check is interested in.Set<String>
getExternalResourceLocations()
Returns a set of external configuration resource locations which are used by the module.private static String
getImportText(DetailAST ast)
Returns import text.private static String
getPackageText(DetailAST ast)
Returns package text.int[]
getRequiredTokens()
The tokens that this check must be registered for.void
setFile(URI uri)
Setter to specify the location of the file containing the import control configuration.void
setPath(Pattern pattern)
Setter to specify the regular expression of file paths to which this check should apply.void
visitToken(DetailAST ast)
Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_MISSING_FILE
public static final String MSG_MISSING_FILE
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_UNKNOWN_PKG
public static final String MSG_UNKNOWN_PKG
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_DISALLOWED
public static final String MSG_DISALLOWED
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
UNABLE_TO_LOAD
private static final String UNABLE_TO_LOAD
A part of message for exception.- See Also:
- Constant Field Values
-
file
private URI file
Specify the location of the file containing the import control configuration. It can be a regular file, URL or resource path. It will try loading the path as a URL first, then as a file, and finally as a resource.
-
path
private Pattern path
Specify the regular expression of file paths to which this check should apply. Files that don't match the pattern will not be checked. The pattern will be matched against the full absolute file path.
-
processCurrentFile
private boolean processCurrentFile
Whether to process the current file.
-
root
private PkgImportControl root
The root package controller.
-
packageName
private String packageName
The package doing the import.
-
currentImportControl
private AbstractImportControl currentImportControl
The package controller for the current file. Used for performance optimisation.
-
-
Constructor Detail
-
ImportControlCheck
public ImportControlCheck()
-
-
Method Detail
-
getDefaultTokens
public int[] getDefaultTokens()
Description copied from class:AbstractCheck
Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokens
in classAbstractCheck
- Returns:
- the default tokens
- See Also:
TokenTypes
-
getAcceptableTokens
public int[] getAcceptableTokens()
Description copied from class:AbstractCheck
The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.- Specified by:
getAcceptableTokens
in classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
TokenTypes
-
getRequiredTokens
public int[] getRequiredTokens()
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
beginTree
public void beginTree(DetailAST rootAST)
Description copied from class:AbstractCheck
Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTree
in classAbstractCheck
- Parameters:
rootAST
- the root of the tree
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
getExternalResourceLocations
public Set<String> getExternalResourceLocations()
Description copied from interface:ExternalResourceHolder
Returns a set of external configuration resource locations which are used by the module. ATTENTION! If 'getExternalResourceLocations()' return null, there will beNullPointerException
inChecker
. Such behaviour will signal that your module (check or filter) is designed incorrectly. It makes sense to return an empty set from 'getExternalResourceLocations()' only for composite modules likeTreeWalker
.- Specified by:
getExternalResourceLocations
in interfaceExternalResourceHolder
- Returns:
- a set of external configuration resource locations which are used by the module.
-
getPackageText
private static String getPackageText(DetailAST ast)
Returns package text.- Parameters:
ast
- PACKAGE_DEF ast node- Returns:
- String that represents full package name
-
getImportText
private static String getImportText(DetailAST ast)
Returns import text.- Parameters:
ast
- ast node that represents import- Returns:
- String that represents importing class
-
setFile
public void setFile(URI uri)
Setter to specify the location of the file containing the import control configuration. It can be a regular file, URL or resource path. It will try loading the path as a URL first, then as a file, and finally as a resource.- Parameters:
uri
- the uri of the file to load.- Throws:
IllegalArgumentException
- on error loading the file.- Since:
- 4.0
-
setPath
public void setPath(Pattern pattern)
Setter to specify the regular expression of file paths to which this check should apply. Files that don't match the pattern will not be checked. The pattern will be matched against the full absolute file path.- Parameters:
pattern
- the file path regex this check should apply to.- Since:
- 7.5
-
-