### HTML Tag Start Example Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Illustrates the structure of an HTML start tag with attributes within a Javadoc comment. ```java
``` -------------------------------- ### HTML Tag Start Example Tree Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Shows the token tree for an HTML start tag within a Javadoc comment, including attributes. ```java HTML_ELEMENT -> HTML_ELEMENT |--HTML_TAG_START -> HTML_TAG_START | |--TAG_OPEN -> < | |--TAG_NAME -> a | |--HTML_ATTRIBUTES -> HTML_ATTRIBUTES | | `--HTML_ATTRIBUTE -> HTML_ATTRIBUTE | | |--TEXT -> | | |--TAG_ATTR_NAME -> href | | |--EQUALS -> = | | `--ATTRIBUTE_VALUE -> "https://example.com" | `--TAG_CLOSE -> > ``` -------------------------------- ### Finish Local Setup Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/XpathFileGeneratorAuditListener.html Placeholder method for finishing local setup. The default implementation does nothing. ```java @Override protected void finishLocalSetup() { // No code by default } ``` -------------------------------- ### Example package-info.java with Javadoc Source: https://checkstyle.org/checks/javadoc/missingjavadocpackage.html This example shows a correctly formatted package-info.java file with a Javadoc comment. ```java /** * Provides API classes */ package com.puppycrawl.tools.checkstyle.checks.javadoc.missingjavadocpackage.javadoc; ``` -------------------------------- ### Package Declaration AST Example Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/JavaAstVisitor.DetailAstPair.html Illustrates how a Java package declaration is transformed into an AST. The example shows the structure of the AST nodes and their relationships, starting from the PACKAGE_DEF root. ```plaintext PACKAGE_DEF -> package |--ANNOTATIONS -> ANNOTATIONS |--DOT -> . | |--DOT -> . | | |--DOT -> . | | | |--IDENT -> com | | | `--IDENT -> puppycrawl | | `--IDENT -> tools | `--IDENT -> checkstyle `--SEMI -> ; ``` -------------------------------- ### Custom Format Naming Examples Source: https://checkstyle.org/checks/naming/localvariablename.html Illustrates variable naming with a custom format requiring names to start with a lowercase letter. ```java class Example2 { void MyMethod() { for (int var = 1; var < 10; var++) {} for (int VAR = 1; VAR < 10; VAR++) {} // violation above, 'Name 'VAR' must match pattern*' for (int i = 1; i < 10; i++) {} for (int var_1 = 0; var_1 < 10; var_1++) {} } } ``` -------------------------------- ### ImportOrderOption: top example Source: https://checkstyle.org/property_types.html Example of 'top' import order policy where all static imports are at the beginning. ```java import static a.b.C.*; import static x.y.Z.*; import a.b.D; import x.y.Z; ``` -------------------------------- ### Example Violation: Content Starts on First Line (Default Setting) Source: https://checkstyle.org/checks/javadoc/javadoccontentlocation.html This example demonstrates violations when Javadoc content starts on the same line as the initial asterisks, while the check is configured for 'second_line' location. ```java class Example1 { // violation below 'Javadoc content should start from the next line.' /** This comment causes a violation because it starts from the first line * and spans several lines. */ private int field1; /** * This comment is OK because it starts from the second line. */ private int field12; /** This comment is OK because it is on the single-line. */ private int field3; } ``` -------------------------------- ### setupChild Method Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.html Handles the setup of child configurations. By default, it throws an exception, indicating that children are not supported unless overridden. ```APIDOC ## setupChild(Configuration childConf) ### Description Called by configure() for every child of this component's Configuration. The default implementation throws `CheckstyleException` if `childConf` is not null, as it doesn't support children. This method must be overridden to validate and support desired children. ### Method `protected void setupChild(Configuration childConf)` ### Parameters * **childConf** (Configuration) - A child of this component's Configuration. ### Throws * **CheckstyleException** - If `childConf` is not null, indicating that children are not supported by default. ### See Also * `Configuration#getChildren` ``` -------------------------------- ### Example Violation: Content Starts on Second Line ('first_line' Setting) Source: https://checkstyle.org/checks/javadoc/javadoccontentlocation.html This example shows violations when Javadoc content starts on the line following the initial asterisks, while the check is configured for 'first_line' location. ```java class Example2 { /** This comment is OK because it starts on the first line. * There may be additional text. */ private int field1; // violation below, 'Javadoc content should start from the same line.' /** * This comment causes a violation because it starts on the second line. */ private int field2; /** This single-line comment also is OK. */ private int field3; } ``` -------------------------------- ### Example Import Order Source: https://checkstyle.org/checks/imports/customimportorder.html An example demonstrating a typical import order, including static imports, standard Java packages, and third-party packages. ```java package com.puppycrawl.tools.checkstyle.checks.imports.customimportorder; import org.apache.commons.io.FileUtils; import static java.util.Collections.*; import java.time.*; import static java.io.File.separator; import com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck; import com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck; ``` -------------------------------- ### LineWrappingHandler.getLineStart Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the starting line number for a given expression. ```APIDOC ## LineWrappingHandler.getLineStart ### Description Get the start of the line for the given expression. ### Method Signature `private int LineWrappingHandler.getLineStart(DetailAST ast)` ``` -------------------------------- ### AbstractExpressionHandler.getLineStart Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the starting line number for a given expression. ```APIDOC ## AbstractExpressionHandler.getLineStart ### Description Get the start of the line for the given expression. ### Method Signature `protected final int AbstractExpressionHandler.getLineStart(DetailAST ast)` ``` -------------------------------- ### getNextToken Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the next token to start counting lines from. ```APIDOC ## getNextToken(DetailAST checkedStatement) ### Description Get the token to start counting the number of lines to add to the distance aim from. ### Method Signature `private DetailAST getNextToken(DetailAST checkedStatement)` ``` -------------------------------- ### Configuration and Setup Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/Checker.html Methods for configuring the Checker and its components. ```APIDOC ## addFileSetCheck(FileSetCheck fileSetCheck) ### Description Adds a FileSetCheck to the list of FileSetChecks that is executed in process(). ### Method `void addFileSetCheck(FileSetCheck fileSetCheck)` ### Parameters #### Path Parameters - **fileSetCheck** (FileSetCheck) - Required - The FileSetCheck to add. ``` ```APIDOC ## addFilter(Filter filter) ### Description Adds a filter to the end of the audit event filter chain. ### Method `void addFilter(Filter filter)` ### Parameters #### Path Parameters - **filter** (Filter) - Required - The filter to add. ``` ```APIDOC ## addListener(AuditListener listener) ### Description Add the listener that will be used to receive events from the audit. ### Method `final void addListener(AuditListener listener)` ### Parameters #### Path Parameters - **listener** (AuditListener) - Required - The listener to add. ``` ```APIDOC ## setBasedir(String basedir) ### Description Sets base directory. ### Method `void setBasedir(String basedir)` ### Parameters #### Path Parameters - **basedir** (String) - Required - The base directory path. ``` ```APIDOC ## setCacheFile(String fileName) ### Description Sets cache file. ### Method `void setCacheFile(String fileName)` ### Parameters #### Path Parameters - **fileName** (String) - Required - The name of the cache file. ``` ```APIDOC ## setCharset(String charset) ### Description Sets a named charset. ### Method `void setCharset(String charset)` ### Parameters #### Path Parameters - **charset** (String) - Required - The name of the charset. ``` ```APIDOC ## setFileExtensions(String... extensions) ### Description Sets the file extensions that identify the files that pass the filter of this FileSetCheck. ### Method `final void setFileExtensions(String... extensions)` ### Parameters #### Path Parameters - **extensions** (String...) - Required - The file extensions. ``` ```APIDOC ## setHaltOnException(boolean haltOnException) ### Description Sets the field haltOnException. ### Method `void setHaltOnException(boolean haltOnException)` ### Parameters #### Path Parameters - **haltOnException** (boolean) - Required - Whether to halt on exception. ``` ```APIDOC ## setLocaleCountry(String localeCountry) ### Description Sets locale country. ### Method `void setLocaleCountry(String localeCountry)` ### Parameters #### Path Parameters - **localeCountry** (String) - Required - The locale country code. ``` ```APIDOC ## setLocaleLanguage(String localeLanguage) ### Description Sets locale language. ### Method `void setLocaleLanguage(String localeLanguage)` ### Parameters #### Path Parameters - **localeLanguage** (String) - Required - The locale language code. ``` ```APIDOC ## setModuleClassLoader(ClassLoader moduleClassLoader) ### Description Sets the classloader used to load Checkstyle core and custom module classes when the module tree is being built up. ### Method `final void setModuleClassLoader(ClassLoader moduleClassLoader)` ### Parameters #### Path Parameters - **moduleClassLoader** (ClassLoader) - Required - The module classloader. ``` ```APIDOC ## setModuleFactory(ModuleFactory moduleFactory) ### Description Sets the module factory. ### Method `void setModuleFactory(ModuleFactory moduleFactory)` ### Parameters #### Path Parameters - **moduleFactory** (ModuleFactory) - Required - The module factory. ``` -------------------------------- ### Example Properties File with Order Source: https://checkstyle.org/checks/misc/orderedproperties.html Illustrates a properties file where key order is checked. Violations occur when keys are not in ascending binary order (case-insensitive). ```properties A=65 a=97 key=107 than nothing key.sub=k is 107 and dot is 46 key.png=value # // violation above 'Property key 'key.png' is not in the right order with previous property 'key.sub'' ``` -------------------------------- ### Example with Tab Width Configuration Source: https://checkstyle.org/checks/javadoc/javadocleadingasteriskalign.html Demonstrates Javadoc alignment when the tabWidth property is set, showing examples with both tabs and spaces. It highlights correct and incorrect alignments based on the configured tab width. ```java /** * Example with `tabWidth` property. * This example contains Tabs as well as Spaces. */ public class Example3 { /** <- Preceded with Tabs. * <- Preceded with Tabs & Spaces. */ // <- Preceded with Tabs & Spaces. private String name; /** <- Preceded with Spaces. * <- Preceded with Tabs. */ // <- Preceded with Tabs. private void foo() {} /** * // violation */ // violation private Example3() {} private enum tabsExample { /** * Incorrect indentation for leading asterisk. // violation */ ONE, /** This javadoc is allowed because there is no leading asterisk. */ TWO } } ``` -------------------------------- ### Checkstyle Configuration for SuppressionXpathFilter (Example 14) Source: https://checkstyle.org/filters/suppressionxpathfilter.html Configuration of the SuppressionXpathFilter for a different suppression file. This setup is similar to Example 13 but uses a distinct suppression file. ```xml ``` -------------------------------- ### Example of TrailingComment Suppressing Comments Starting With Legal Strings Source: https://checkstyle.org/checks/misc/trailingcomment.html Shows that comments starting with 'SUPPRESS CHECKSTYLE', 'NOPMD', or 'NOSONAR' are allowed, even with extra text. ```java public class Example4 { int a; // SUPPRESS CHECKSTYLE - OK, comment starts with " SUPPRESS CHECKSTYLE" int b; // NOPMD - OK, comment starts with " NOPMD" int c; // NOSONAR - OK, comment starts with " NOSONAR" int d; // violation, not suppressed } ``` -------------------------------- ### Build Checkstyle JARs and Launch CLI Source: https://checkstyle.org/cmdline.html Build all Checkstyle JAR files, including the assembly, and then launch the command-line interface from the new build, specifying a configuration and a Java file. ```bash ./mvnw clean package -Passembly,no-validations java -jar target/checkstyle-X.X-SNAPSHOT-all.jar -c /sun_checks.xml MyClass.java ``` -------------------------------- ### MethodDefHandler.getMethodDefLineStart Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the starting line number of a method definition, excluding any annotations. ```APIDOC ## MethodDefHandler.getMethodDefLineStart ### Description Gets the start line of the method, excluding any annotations. ### Method Signature `private static int MethodDefHandler.getMethodDefLineStart(DetailAST mainAst)` ``` -------------------------------- ### Javadoc LPAREN Token Example Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Demonstrates the use of the LPAREN token, typically found in Javadoc references like method calls. ```java * {@link String#length()} ``` -------------------------------- ### getStartColumn Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/checks/indentation/DetailAstSet.html Gets the starting column number for the AST node on a given line. ```APIDOC ## getStartColumn(int lineNum) ### Description Get starting column number for the ast. ### Parameters * `lineNum` (int) - the line number as key ### Returns Integer - start column for ast ``` -------------------------------- ### Java Source File Example Source: https://checkstyle.org/styleguides/sun-code-conventions-19990420/CodeConventions.doc10.html Demonstrates the standard formatting for a Java source file, including package declarations, imports, class definitions, and various types of comments (documentation, implementation, and variable comments). ```Java /* * @(#)Blah.java 1.82 99/03/18 * * Copyright (c) 1994-1999 Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. */ package java.blah; import java.blah.blahdy.BlahBlah; /** * _Class description goes here_. * * @version 1.82 18 Mar 1999 * @author _Firstname Lastname */ public class Blah extends SomeClass { /* A class implementation comment can go here. */ /** _classVar1 documentation comment_ */ public static int classVar1; /** * _classVar2 documentation comment that happens to be * more than one line long */ private static Object classVar2; /** _instanceVar1 documentation comment_ */ public Object instanceVar1; /** _instanceVar2 documentation comment_ */ protected int instanceVar2; /** _instanceVar3 documentation comment_ */ private Object[] instanceVar3; /** * ..._constructor Blah documentation comment... */ public Blah() { // ...implementation goes here... } /** * ..._method doSomething documentation comment... */ public void doSomething() { // ...implementation goes here... } /** * ...method doSomethingElse _documentation comment... * @param someParam _description */ public void doSomethingElse(Object someParam) { // ...implementation goes here... } } ``` -------------------------------- ### Run Checkstyle UI Viewer Source: https://checkstyle.org/cmdline.html Launch the Checkstyle UI viewer for AST tree analysis directly from the JAR file. The path to the Java file is optional. ```bash java -cp checkstyle-13.4.2-all.jar com.puppycrawl.tools.checkstyle.gui.Main MyClass.java ``` -------------------------------- ### Get Column Number of Code Start Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.html Calculates the starting column number of code on a given line by skipping leading whitespace. This is a helper method for indentation checks. ```java private int getLineStart(int lineNo) { final char[] line = getLines()[lineNo - 1].toCharArray(); int lineStart = 0; while (Character.isWhitespace(line[lineStart])) { lineStart++; } return lineStart; } ``` -------------------------------- ### Example with Custom Format Allowing 'log' and 'logger' Source: https://checkstyle.org/checks/naming/constantname.html Demonstrates constant declarations with the custom format that allows 'log' and 'logger'. ```java class Example2 { public final static int FIRST_CONSTANT1 = 10; protected final static int SECOND_CONSTANT2 = 100; final static int third_Constant3 = 1000; // violation 'must match pattern' private final static int fourth_Const4 = 50; // violation 'must match pattern' public final static int log = 10; protected final static int logger = 50; final static int loggerMYSELF = 5; // violation 'must match pattern' final static int MYSELF = 100; protected final static int myselfConstant = 1; // violation 'must match pattern' } ``` -------------------------------- ### TypeName Check Lowercase Start and Suppressed Public/Package Example Source: https://checkstyle.org/checks/naming/typename.html Demonstrates violations when using a custom format requiring lowercase starts and checks are suppressed for public and package-private types. ```java class Example4 { public interface FirstName {} public class SecondName {} protected class ThirdName {} // violation 'Name 'ThirdName' must match pattern' private class FourthName {} // violation 'Name 'FourthName' must match pattern' } ``` -------------------------------- ### HTML Tag Start Token Example Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Demonstrates the TAG_OPEN token, representing the opening '<' symbol of an HTML start tag. Used when parsing HTML elements within Javadoc. ```html < div class="container" lang="en"> < /div> ``` -------------------------------- ### DetailAstImpl Initialization Methods Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/DetailAstImpl.html Methods for initializing a DetailAstImpl with token information. ```APIDOC ## initialize(int tokenType, String tokenText) ### Description Initializes this DetailAstImpl with a token type and text. ### Method public void initialize(int tokenType, String tokenText) ### Parameters * `tokenType` (int) - the type of this DetailAstImpl * `tokenText` (String) - the text of this DetailAstImpl ``` ```APIDOC ## initialize(org.antlr.v4.runtime.Token token) ### Description Initializes this DetailAstImpl from an ANTLR Token. ### Method public void initialize(org.antlr.v4.runtime.Token token) ### Parameters * `token` (org.antlr.v4.runtime.Token) - the token to generate this DetailAstImpl from ``` -------------------------------- ### At-Sign for Block Tags Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Shows an example of an at-sign starting a block tag in Javadoc. ```plaintext * @author name ``` -------------------------------- ### setupChild Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.html Called by the `configure()` method for each child configuration. Subclasses can override this method to perform specific setup for child components. ```APIDOC ## setupChild ### Description Called by configure() for every child of this component's Configuration. ### Method ```java protected void setupChild(Configuration childConf) ``` ### Parameters * **childConf** (Configuration) - The configuration for a child component. ``` -------------------------------- ### Example with File Extension Filtering Source: https://checkstyle.org/checks/sizes/linelength.html Demonstrates code that would be checked if the file extension was 'xml' or 'properties'. This example shows the structure of a class that would be subject to line length checks under the specified configuration. ```java package com.puppycrawl.tools.checkstyle.checks.sizes.linelength; import static com.puppycrawl.tools.checkstyle.checks.sizes.LineLengthCheck.MSG_KEY; /** * This is a short Javadoc comment. * ThisJavadocCommentIsAReallyLongWordThatExceedsDefaultLineLimitOfEightyCharacters. */ class Example4 { void testMethod(String str) { str = MSG_KEY; System.out.println("This is a short line."); System.out.println("This line is long and exceeds the default limit of 80 characters."); } } ``` -------------------------------- ### LineWrappingHandler.expandedTabsColumnNo Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the column number for the start of a given expression, expanding tabs into spaces. ```APIDOC ## LineWrappingHandler.expandedTabsColumnNo ### Description Get the column number for the start of a given expression, expanding tabs out into spaces in the process. ### Method Signature `private int LineWrappingHandler.expandedTabsColumnNo(DetailAST ast)` ``` -------------------------------- ### Example with Third-Party Package Regex Source: https://checkstyle.org/checks/imports/customimportorder.html Demonstrates an import block with violations related to third-party package ordering and separation, based on the 'com.' regex configuration. ```java package com.puppycrawl.tools.checkstyle.checks.imports.customimportorder; import static java.util.Collections.*; import static java.io.File.separator; import java.time.*; import javax.net.*; import org.apache.commons.io.FileUtils; // violation, 'should be placed at the end' import com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck; // violation, 'should be separated' import com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck; ``` -------------------------------- ### DetailAstSet.expandedTabsColumnNo Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the column number for the start of a given expression, expanding tabs into spaces. ```APIDOC ## DetailAstSet.expandedTabsColumnNo ### Description Get the column number for the start of a given expression, expanding tabs out into spaces in the process. ### Method Signature `protected final int DetailAstSet.expandedTabsColumnNo(DetailAST ast)` ``` -------------------------------- ### LPAREN Token Example Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html Demonstrates the parsed structure for a left parenthesis. ```java Integer val = new Integer(); while (false) { val += (-3); } ``` ```plaintext | |--VARIABLE_DEF -> VARIABLE_DEF | |--MODIFIERS -> MODIFIERS | |--TYPE -> TYPE | | `--IDENT -> Integer | |--IDENT -> val | `--ASSIGN -> = | `--EXPR -> EXPR | `--LITERAL_NEW -> new | |--IDENT -> Integer | |--LPAREN -> ( | |--ELIST -> ELIST | `--RPAREN -> ) |--SEMI -> ; |--LITERAL_WHILE -> while | |--LPAREN -> ( | |--EXPR -> EXPR | | `--LITERAL_FALSE -> false | |--RPAREN -> ) | `--SLIST -> { | |--EXPR -> EXPR | | `--PLUS_ASSIGN -> += | | |--IDENT -> val | | |--LPAREN -> ( | | |--UNARY_MINUS -> - | | | `--NUM_INT -> 3 | | `--RPAREN -> ) | |--SEMI -> ; | `--RCURLY -> } ``` -------------------------------- ### AbstractExpressionHandler.expandedTabsColumnNo Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the column number for the start of a given expression, expanding tabs into spaces. ```APIDOC ## AbstractExpressionHandler.expandedTabsColumnNo ### Description Get the column number for the start of a given expression, expanding tabs out into spaces in the process. ### Method Signature `protected final int AbstractExpressionHandler.expandedTabsColumnNo(DetailAST ast)` ``` -------------------------------- ### CommentsIndentationCheck.getNextToken Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/class-use/DetailAST.html Gets the token used to start counting the number of lines to add to the distance aim from. ```APIDOC ## CommentsIndentationCheck.getNextToken ### Description Get the token to start counting the number of lines to add to the distance aim from. ### Method Signature `private DetailAST CommentsIndentationCheck.getNextToken(DetailAST checkedStatement)` ``` -------------------------------- ### Javadoc @see Tag Example Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Demonstrates the Javadoc @see tag, used to link to other classes, methods, or documentation. ```java * @see SomeClass#Field ``` -------------------------------- ### Example with Custom Import Order Rules Source: https://checkstyle.org/checks/imports/customimportorder.html Demonstrates an import block that violates the configured order (static, standard Java, third-party), highlighting a 'wrong order' violation. ```java package com.puppycrawl.tools.checkstyle.checks.imports.customimportorder; import static java.util.Collections.*; import java.time.*; import javax.net.*; import static java.io.File.separator; // violation, 'wrong order' import org.apache.commons.io.FileUtils; import com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck; import com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck; ``` -------------------------------- ### HTML Comment Token Example Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Demonstrates the HTML_COMMENT token, marking the start of an HTML comment within Javadoc. This token represents a complete HTML comment, including its start, content, and end. ```html * ``` -------------------------------- ### Get Module Since Version Tag Start Node Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/site/ModuleJavadocParsingUtil.html Retrieves the starting node of the \u0040since version tag within a module's Javadoc. This is useful for identifying and processing version information. ```APIDOC ## getModuleSinceVersionTagStartNode ### Description Gets the node representing the start of the {@code @since} version tag in the module's Javadoc. ### Method Signature public static DetailNode getModuleSinceVersionTagStartNode(DetailNode moduleJavadoc) ### Parameters * **moduleJavadoc** (DetailNode) - the root Javadoc node of the module ### Returns * **DetailNode** - the {@code @since} tag start node, or {@code null} if not found ``` -------------------------------- ### Finish Local Setup Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/TreeWalker.html Completes the local setup for the TreeWalker by creating and configuring a DefaultContext. This context is used to pass information to child modules. ```java public void finishLocalSetup() { final DefaultContext checkContext = new DefaultContext(); checkContext.add("severity", getSeverity()); checkContext.add("tabWidth", String.valueOf(getTabWidth())); childContext = checkContext; } ``` -------------------------------- ### finishLocalSetup Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.html Provides a hook for subclasses to perform additional setup after standard bean introspection. ```APIDOC ## finishLocalSetup ### Description Provides a hook to finish the part of this component's setup that was not handled by the bean introspection. The default implementation does nothing. ### Method protected void finishLocalSetup() throws CheckstyleException ### Throws CheckstyleException - if there is a configuration error. ``` -------------------------------- ### Get Next Token Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.html Retrieves the next token, which serves as the starting point for calculating the distance to the aim. ```java private DetailAST getNextToken(DetailAST checkedStatement) Get the token to start counting the number of lines to add to the distance aim from. Parameters: `checkedStatement` - the checked statement. Returns: the token to start counting the number of lines to add to the distance aim from. ``` -------------------------------- ### JavadocContentLocationOption: SECOND_LINE example Source: https://checkstyle.org/property_types.html Illustrates the 'SECOND_LINE' policy for Javadoc content, where it starts on the line after '/**'. This is common in Java projects. ```java /** * Summary text. * More details. */ public void method(); ``` -------------------------------- ### ExampleMacro Configuration Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/site/ExampleMacro.html This snippet shows the definition of the ExampleMacro, a Maven Doxia macro used to insert code or configuration snippets from files into documentation. It extends AbstractMacro and is annotated with @Component. ```java package com.puppycrawl.tools.checkstyle.site; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.maven.doxia.macro.AbstractMacro; import org.apache.maven.doxia.macro.Macro; import org.apache.maven.doxia.macro.MacroExecutionException; import org.apache.maven.doxia.macro.MacroRequest; import org.apache.maven.doxia.sink.Sink; import org.codehaus.plexus.component.annotations.Component; /** * A macro that inserts a snippet of code or configuration from a file. */ @Component(role = Macro.class, hint = "example") public class ExampleMacro extends AbstractMacro { /** Starting delimiter for config snippets. */ private static final String XML_CONFIG_START = "/*xml"; /** Ending delimiter for config snippets. */ private static final String XML_CONFIG_END = "*/"; /** Starting delimiter for code snippets. */ private static final String CODE_SNIPPET_START = "// xdoc section -- start"; /** Ending delimiter for code snippets. */ private static final String CODE_SNIPPET_END = "// xdoc section -- end"; /** The pattern of xml code blocks. */ private static final Pattern XML_PATTERN = Pattern.compile( "^\\s*(|<\\?xml\\s+.*?>|)\\s*", Pattern.DOTALL ); /** The path of the last file. */ private String lastPath = ""; /** The line contents of the last file. */ private List lastLines = new ArrayList<>(); @Override public void execute(Sink sink, MacroRequest request) throws MacroExecutionException { final String path = (String) request.getParameter("path"); final String type = (String) request.getParameter("type"); List lines = lastLines; if (!path.equals(lastPath)) { lines = readFile("src/xdocs-examples/" + path); lastPath = path; lastLines = lines; } if ("config".equals(type)) { final String config = getConfigSnippet(lines); if (config.isBlank()) { final String message = String.format(Locale.ROOT, "Empty config snippet from %s, check" + " for xml config snippet delimiters in input file.", path ); throw new MacroExecutionException(message); } writeSnippet(sink, config); } else if ("code".equals(type)) { String code = getCodeSnippet(lines); // Replace tabs with spaces for FileTabCharacterCheck examples if (path.contains("filetabcharacter")) { code = code.replace("\t", " "); } if (code.isBlank()) { final String message = String.format(Locale.ROOT, "Empty code snippet from %s, check" + " for code snippet delimiters in input file.", path ); throw new MacroExecutionException(message); } writeSnippet(sink, code); } else if ("raw".equals(type)) { final String content = String.join(ModuleJavadocParsingUtil.NEWLINE, lines); writeSnippet(sink, content); } else { final String message = String.format(Locale.ROOT, "Unknown example type: %s", type); ``` -------------------------------- ### Example with Multi-line Javadoc Phrase Source: https://checkstyle.org/checks/design/designforextension.html Demonstrates the DesignForExtension check's behavior with a multi-line Javadoc phrase, allowing for more complex documentation requirements. ```java public abstract class Example4 { private int bar; public int m1() {return 2;} // violation public int m2() {return 8;} // violation private void m3() {m4();} protected void m4() { } // ok, No implementation. public abstract void m5(); // ok, Abstract method. /** * This implementation ... @return some int value. */ public int m6() {return 1;} // ok, Have required javadoc. /** * Some comments ... */ public int m7() {return 1;} // violation /** * This * implementation ... */ public int m8() {return 2;} // ok, Have required javadoc. @Override // violation public String toString() { return ""; } } ``` -------------------------------- ### JavadocContentLocationOption: FIRST_LINE example Source: https://checkstyle.org/property_types.html Illustrates the 'FIRST_LINE' policy for Javadoc content, where it starts on the same line as '/**'. This is also known as 'scala' style. ```java /** Summary text. * More details. */ public void method(); ``` -------------------------------- ### Example File with Multiline Header Source: https://checkstyle.org/checks/regexp/regexp.html An example of a Java file that conforms to the multiline header format specified by the Regexp check. This demonstrates the expected structure for copyright and rights reserved lines. ```java // Copyright (C) 2004 MyCompany // All rights reserved public class Example11 {} ``` -------------------------------- ### FallThrough Example with Default Settings Source: https://checkstyle.org/checks/coding/fallthrough.html Demonstrates various scenarios of fall-through in switch statements, including cases with breaks, returns, throws, continues, and intentional fall-throughs. It also shows how comments can suppress warnings. ```java class Example1 { public void foo() throws Exception { int i = 0; while (i >= 0) { switch (i) { case 1: i++; /* block */ /* fallthru */ // comment case 2: // ok, ReliefPattern is present in above line. i++; break; case 3: i++; return; case 4: i++; throw new Exception(); case 5: i++; // no break by design case 6: // violation 'Fall\ through from previous branch of the switch' case 7: i++; continue; case 11: i++; } } } } ``` -------------------------------- ### Block Comment Begin Token Type Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/TokenTypes.html Represents the start of a block comment, denoted by '/*'. Shows an example of its structure and parsing. ```java public static final int BLOCK_COMMENT_BEGIN = JavaLanguageLexer.BLOCK_COMMENT_BEGIN; ``` ```java /\* Comment content *\/ ``` ```java --BLOCK_COMMENT_BEGIN -> /\* |--COMMENT_CONTENT -> Comment content\r\n `--BLOCK_COMMENT_END -> \*/ ``` -------------------------------- ### ImportControl Configuration Example Source: https://checkstyle.org/checks/imports/importcontrol.html This example shows a basic ImportControl configuration with package-level and subpackage-level rules. It allows specific classes and disallows others within defined subpackages. ```xml ``` -------------------------------- ### FIRST_LINE Javadoc Style Example Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocContentLocationOption.html Illustrates the Javadoc content starting on the same line as the `/**` tag. This style is often referred to as 'scala' style. ```java /** Summary text. * More details. */ public void method(); ``` -------------------------------- ### Example of HTML Comment in Javadoc Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Illustrates the structure of an HTML comment within a Javadoc, showing the start, content, and end delimiters. ```java * ``` -------------------------------- ### Parameter Definition Example Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html Illustrates a parameter definition, including handling of variable-length parameters with ELLIPSIS. ```java void foo(SomeType SomeType.this, int firstParameter, int... secondParameter) {} ``` ```plaintext METHOD_DEF -> METHOD_DEF |--MODIFIERS -> MODIFIERS |--TYPE -> TYPE | `--LITERAL_VOID -> void |--IDENT -> foo |--LPAREN -> ( |--PARAMETERS -> PARAMETERS | |--PARAMETER_DEF -> PARAMETER_DEF | | |--MODIFIERS -> MODIFIERS | | |--TYPE -> TYPE | | | `--IDENT -> SomeType | | `--DOT -> . | | |--IDENT -> SomeType | | `--LITERAL_THIS -> this | |--COMMA -> , | |--PARAMETER_DEF -> PARAMETER_DEF | | |--MODIFIERS -> MODIFIERS | | |--TYPE -> TYPE | | | `--LITERAL_INT -> int | | `--IDENT -> firstParameter | |--COMMA -> , | `--PARAMETER_DEF -> PARAMETER_DEF | |--MODIFIERS -> MODIFIERS | |--TYPE -> TYPE | | `--LITERAL_INT -> int | |--ELLIPSIS -> ... | `--IDENT -> secondParameter |--RPAREN -> ) `--SLIST -> { `--RCURLY -> } ``` -------------------------------- ### Constructor Call Example Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/TokenTypes.html Demonstrates the parsing of a constructor call using 'this'. ```java this(1); ``` ```plaintext CTOR_CALL -> this |--LPAREN -> ( |--ELIST -> ELIST | `--EXPR -> EXPR | `--NUM_INT -> 1 |--RPAREN -> ) `--SEMI -> ; ``` -------------------------------- ### Get Line Start Column Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.html Retrieves the column number where code begins on a given line. This is a helper method for indentation checks. ```java private int getLineStart(int lineNo) Get a column number where a code starts. Parameters: `lineNo` - the line number to get column number in. Returns: the column number where a code starts. ``` -------------------------------- ### DetectorOptions Builder Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/checks/regexp/class-use/DetectorOptions.html Demonstrates how to build a DetectorOptions instance. ```APIDOC ## DetectorOptions.Builder.build() ### Description Returns new DetectorOptions instance. ### Method ```java DetectorOptions build() ``` ``` -------------------------------- ### Configuration Example Source: https://checkstyle.org/checks/coding/unnecessarynullcheckwithinstanceof.html This snippet shows how to configure the UnnecessaryNullCheckWithInstanceOf check within a Checkstyle setup. Ensure this module is placed within the TreeWalker module. ```xml ``` -------------------------------- ### Content of universal.header File Source: https://checkstyle.org/checks/header/regexpheader.html Example content for the universal.header file, using a regex that matches any line. ```regexp ^.* ``` -------------------------------- ### TypeName Check Default Pattern Example Source: https://checkstyle.org/checks/naming/typename.html Demonstrates violations of the default type name pattern (starts with an uppercase letter, followed by letters and numbers). ```java class Example1 { public interface FirstName {} protected class SecondName {} enum Third_Name {} // violation 'Name 'Third_Name' must match pattern' private class FourthName_ {} // violation 'Name 'FourthName_' must match pattern' } ``` -------------------------------- ### Method Call Example Source: https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html Demonstrates a static method call with a string literal argument. ```java Integer.parseInt("123"); ``` ```plaintext |--EXPR -> EXPR | `--METHOD_CALL -> ( | |--DOT -> . | | |--IDENT -> Integer | | `--IDENT -> parseInt | |--ELIST -> ELIST | | `--EXPR -> EXPR | | `--STRING_LITERAL -> "123" | `--RPAREN -> ) |--SEMI -> ; ``` -------------------------------- ### ParameterName Check with Custom Format Example Source: https://checkstyle.org/checks/naming/parametername.html Illustrates violations when parameter names do not match the custom format (lowercase start, then letters, digits, underscores). ```java class Example2 { void method1(int v1) {} void method2(int v_2) {} @Override public boolean equals(Object V3) { // violation 'Name 'V3' must match pattern' return true; } } ``` -------------------------------- ### Javadoc Comment Parsing Example Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html Demonstrates how a simple Javadoc comment is parsed into its constituent token types, including block start, content, and end. ```plaintext --BLOCK_COMMENT_BEGIN -> /** |--COMMENT_CONTENT -> *\r\n * This is a Javadoc line.\r\n | `--JAVADOC_CONTENT -> JAVADOC_CONTENT | |--NEWLINE -> \r\n | |--LEADING_ASTERISK -> * | |--TEXT -> This is a Javadoc line. | |--NEWLINE -> \r\n | `--TEXT -> `--BLOCK_COMMENT_END -> * ``` -------------------------------- ### init Method Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.FileContext.html Initializes the check. This method can be overridden by subclasses to perform setup tasks when the check is initialized. The default implementation does nothing. ```APIDOC ## init Method ### Description Initializes the check. Should be overridden only by demand at subclasses. ### Signature @Override public void init() ``` -------------------------------- ### Check Initialization Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/AbstractCheck.FileContext.html The `init` method is called to initialize the check. This is the appropriate place to perform any setup or validation required before the check starts processing code. ```APIDOC ## init ### Description Initialize the check. This is the time to verify that the check has everything required to perform its job. ### Method Signature `public void init()` ``` -------------------------------- ### Java Module Import Example Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/TokenTypes.html Demonstrates the structure of a module import statement in Java and its parsed token representation. ```java import module java.base; ``` ```java MODULE_IMPORT -> import |--LITERAL_MODULE -> module |--DOT -> . | |--IDENT -> java | `--IDENT -> base `--SEMI -> ; ``` -------------------------------- ### Pattern Property Set Example Source: https://checkstyle.org/property_types.html Demonstrates how to specify multiple patterns for a property. This can be done by separating patterns with commas or by supplying the property multiple times. ```xml ``` ```xml ``` -------------------------------- ### Get Resource From Classpath Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/utils/CommonUtil.html Retrieves a resource from the classpath, handling both absolute paths starting with '/' and relative paths. Throws CheckstyleException if the resource is not found. ```java public static URI getResourceFromClassPath(String filename) throws CheckstyleException { final URL configUrl; if (filename.charAt(0) == '/') { configUrl = getCheckstyleResource(filename); } else { configUrl = ClassLoader.getSystemResource(filename); } if (configUrl == null) { throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename); } final URI uri; try { uri = configUrl.toURI(); } catch (final URISyntaxException exc) { throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename, exc); } return uri; } ``` -------------------------------- ### Get Lines to Position Map in Checkstyle GUI Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.html Provides an unmodifiable list of line start positions. This prevents external modification and reduces overhead. ```java public List getLinesToPosition() { return new ArrayList<>(linesToPosition); } ``` -------------------------------- ### Example: Basic Record Declaration Source: https://checkstyle.org/apidocs/src-html/com/puppycrawl/tools/checkstyle/api/TokenTypes.html Demonstrates a simple record declaration with no components. This serves as a minimal valid record structure. ```java public record MyRecord () { } ``` -------------------------------- ### Correct Text Block Formatting Examples Source: https://checkstyle.org/checks/coding/textblockgooglestyleformatting.html Demonstrates valid usage of Java text blocks that comply with the Google Java Style Guide formatting. ```java public class Example1 { public String testMethod1() { final String simpleScript = """ contents of Text block """; final String simpleScript1 = """ contents of Text block """; String stringFollowedBy = """ Hello there """ + getName(); getData( """ Hello, This is a multi-line message. """, 0); return """ this is sample text """; } public void getData(String text, int num) {} public String getName() { return null; } } ``` -------------------------------- ### Complex Import Control Configuration Example Source: https://checkstyle.org/checks/imports/importcontrol.html Demonstrates advanced import control rules using package and class-level disallows/allows, subpackage restrictions, and regular expressions for flexible matching. ```xml ``` -------------------------------- ### TypeName Check Interface Name Pattern Example Source: https://checkstyle.org/checks/naming/typename.html Demonstrates violations of the interface name pattern that requires names to start with 'I_' followed by letters and digits. ```java class Example3 { public interface I_firstName {} interface SecondName {} // violation 'Name 'SecondName' must match pattern' } ```