### Example of init Method Implementation Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/abstract-cacheable-formatter.md An example demonstrating how a subclass can call the superclass's initCfg method to set up common configurations before initializing formatter-specific state. ```java @Override public void init(Map options, ConfigurationSource cfg) { super.initCfg(cfg); // Sets log and encoding // Initialize formatter-specific state... } ``` -------------------------------- ### JavaScript Example Source: https://github.com/revelc/formatter-maven-plugin/blob/main/src/test/resources/someFile.html A simple JavaScript function call. This snippet is for demonstration purposes and does not require specific setup. ```javascript doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomething(); doSomethingdoSomethingdoSomethingdoSomethingdoSomethingdoSomethingdoSomething(); ``` -------------------------------- ### Example Usage of addCollectionFiles() Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/formatter-mojo.md Demonstrates how to use the addCollectionFiles method to collect files from a source directory. ```java List files = mojo.addCollectionFiles(Paths.get("src/main/java")); ``` -------------------------------- ### Input JSON (Minified) Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/json-formatter.md Example of a minified JSON string before formatting. ```json {"name":"Alice","age":30,"city":"New York","active":true} ``` -------------------------------- ### Configuration Not Found Error Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md Example error message indicating a configuration file could not be found. Check file paths and existence. ```text [ERROR] Cannot find config file [formatter-maven-plugin/eclipse/java.xml] ``` -------------------------------- ### Handling Build Failures with MojoExecutionException Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md This example demonstrates the typical command-line interaction when a build fails due to a MojoExecutionException and how to fix and retry the build. ```bash # Build fails with error mvn formatter:format # [ERROR] Cannot find config file [myformat.xml] # [ERROR] Build failure # Fix and retry mvn formatter:format ``` -------------------------------- ### Example XML with Missing Profiles Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md This XML snippet demonstrates a configuration file missing the required '' element, which triggers a ConfigReadException. ```xml ``` -------------------------------- ### Handle ConfigReadException Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Example of how to catch and handle a ConfigReadException. This demonstrates wrapping the call to ConfigReader.read() in a try-catch block to log errors when the formatter configuration fails to load. ```java try { Map config = new ConfigReader().read(input); } catch (ConfigReadException e) { logger.error("Failed to read formatter config: " + e.getMessage()); } ``` -------------------------------- ### Maven Configuration for Validate Goal Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/validate-mojo.md Example Maven configuration in pom.xml to bind the 'validate' goal of the formatter-maven-plugin to a specific execution. This setup includes specifying the configuration file, encoding, and enabling aggregator mode for multi-module builds. ```xml net.revelc.code.formatter formatter-maven-plugin 2.30.0 validate eclipse-formatter.xml UTF-8 true ``` -------------------------------- ### Example Eclipse Formatter Configuration Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/java-formatter.md An excerpt from an Eclipse formatter XML file, defining code style settings for Java. ```xml ``` -------------------------------- ### Version Mismatch Configuration Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md Example Maven configuration to set Java compiler source, compliance, and target versions. ```xml 11 11 11 ``` -------------------------------- ### Java: Example of fixLineEnding Usage Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/abstract-cacheable-formatter.md Demonstrates how to use the fixLineEnding method to convert mixed line endings to Unix style (LF). ```java String code = "line1\r\nline2\rline3\nline4"; String result = fixLineEnding(code, LineEnding.LF); // Result: "line1\nline2\nline3\nline4" ``` -------------------------------- ### Cache File Format Example Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/configuration.md Illustrates the properties file format used for storing cached file hashes. Ensure file paths are relative and hashes are correctly generated. ```properties /src/main/java/MyClass.java=a1b2c3d4e5f6... /src/test/java/MyClassTest.java=f6e5d4c3b2a1... ``` -------------------------------- ### Mock ConfigurationSource for Testing Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Implement the ConfigurationSource interface to create a mock for unit testing. This example provides mock implementations for logger, compiler settings, target directory, and encoding. ```java class TestConfigurationSource implements ConfigurationSource { @Override public Log getLog() { return new TestLog(); // Mock logger } @Override public String getCompilerSources() { return "11"; } @Override public String getCompilerCompliance() { return "11"; } @Override public String getCompilerCodegenTargetPlatform() { return "11"; } @Override public Path getTargetDirectory() { return Paths.get("/tmp/target"); } @Override public Charset getEncoding() { return StandardCharsets.UTF_8; } } ``` ```java @Test public void testFormatterInit() { Formatter formatter = new JavaFormatter(); ConfigurationSource config = new TestConfigurationSource(); Map options = new HashMap<>(); formatter.init(options, config); assertTrue(formatter.isInitialized()); } ``` -------------------------------- ### Formatted HTML with indentAmount=2 Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/html-formatter.md Example of HTML formatted with an indentation of 2 spaces. ```html Test

Hello

World

``` -------------------------------- ### Get Formatter Options Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/javascript-formatter.md Retrieves the formatter options that were set during initialization. Useful for inspecting or reusing configuration. ```java Map options = formatter.getOptions(); String indentSize = options.get("org.eclipse.wst.jsdt.core.formatter.indent_size"); ``` -------------------------------- ### Configure Formatter Maven Plugin: Format Goal Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/README.md Example Maven configuration for the formatter-maven-plugin's 'format' goal, specifying a custom configuration file. ```xml net.revelc.code.formatter formatter-maven-plugin 2.30.0 eclipse-formatter.xml ``` -------------------------------- ### Get Settings Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Retrieves all settings associated with this formatter profile. The settings are returned as a map where keys are setting IDs and values are their configurations. ```java public Map getSettings() ``` -------------------------------- ### Formatted HTML with indentAmount=4 Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/html-formatter.md Example of HTML formatted with an indentation of 4 spaces. ```html Test

Hello

World

``` -------------------------------- ### Read Formatter Configuration Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/config-reader.md Reads formatter configuration from an XML input stream and returns a map of settings. This example demonstrates how to use ConfigReader to load settings from a file and handle potential exceptions. ```java ConfigReader reader = new ConfigReader(); try (InputStream input = Files.newInputStream(Paths.get("formatter.xml"))) { Map settings = reader.read(input); // Use settings to initialize formatter formatter.init(settings, configSource); } catch (IOException e) { logger.error("Cannot read formatter configuration file", e); } catch (SAXException e) { logger.error("Invalid XML in formatter configuration", e); } catch (ConfigReadException e) { logger.error("Formatter configuration error: " + e.getMessage()); } ``` -------------------------------- ### Get Formatter Options Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/java-formatter.md Retrieves the formatter options that were passed during initialization. This returns a map of Eclipse formatter configuration options. ```java public Map getOptions() ``` ```java Map options = formatter.getOptions(); String sourceVersion = options.get("org.eclipse.jdt.core.compiler.source"); ``` -------------------------------- ### Configure Formatter Maven Plugin: Validate Goal Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/README.md Example Maven configuration for the formatter-maven-plugin's 'validate' goal, specifying a configuration file and enabling aggregation. ```xml net.revelc.code.formatter formatter-maven-plugin 2.30.0 eclipse-formatter.xml true ``` -------------------------------- ### Get Target Directory Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Returns the path to the project's target directory, typically used for build outputs. This is essential for locating generated files or build artifacts. ```java Path getTargetDirectory() ``` -------------------------------- ### Example XML with Wrong Profile Kind Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md This XML snippet shows a configuration file with a '' element but an incorrect 'kind' attribute for the profile, leading to a ConfigReadException. ```xml ``` -------------------------------- ### Invalid XML Syntax Example Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/config-reader.md This XML contains a syntax error: a missing closing tag for the `` element. Ensure all XML tags are properly closed. ```xml ``` -------------------------------- ### Maven Plugin Configuration with Custom configFile Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/config-reader.md Example of how to configure the formatter-maven-plugin in your pom.xml to use a custom formatter profile. The configFile can point to a file within your project, an absolute path, or a classpath resource. ```xml net.revelc.code.formatter formatter-maven-plugin 2.30.0 src/main/resources/my-formatter.xml /etc/formatter-profiles/corporate-standard.xml com/mycompany/formatter/company-formatter.xml ``` -------------------------------- ### Example Eclipse JavaScript Formatter Configuration Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/javascript-formatter.md This XML file defines formatting settings for JavaScript code using Eclipse JSDT. Configure indentation, line wrapping, and ECMAScript version. ```xml ``` -------------------------------- ### Get Display Name of File Type Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Returns the human-readable display name for a given file type. Example usage shows how to retrieve names for JAVA and CSS types. ```java @Override public String toString() ``` ```java Type.JAVA.toString(); // Returns "Java" Type.CSS.toString(); // Returns "CSS" ``` -------------------------------- ### JavaFormatter Implementation using ConfigurationSource Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Demonstrates how a Java formatter can initialize itself using a ConfigurationSource to retrieve compiler settings and other options. It merges settings from the source with provided options. ```java public class JavaFormatter extends AbstractCacheableFormatter implements Formatter { private CodeFormatter formatter; protected Log log; protected Charset encoding; @Override public void init(Map options, ConfigurationSource cfg) { super.initCfg(cfg); // Sets log and encoding from cfg // Merge compiler versions from configuration source String source = cfg.getCompilerSources(); String compliance = cfg.getCompilerCompliance(); String target = cfg.getCompilerCodegenTargetPlatform(); Map config = new HashMap<>(options); config.put(JavaCore.COMPILER_SOURCE, source); config.put(JavaCore.COMPILER_COMPLIANCE, compliance); config.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, target); this.formatter = ToolFactory.createCodeFormatter(config); this.log.debug("Initialized JavaFormatter for Java " + source); } @Override public String formatFile(Path file, String originalCode, LineEnding ending) { this.log.debug("Formatting file: " + file); String formatted = // ... formatting logic ... return formatted; } } ``` -------------------------------- ### Get Line Ending Characters Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Retrieves the actual characters representing a specific line ending. ```java public String getChars() ``` -------------------------------- ### Format Sources Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/formatter-mojo.md Execute the formatter-maven-plugin to format source files. Use the default goal or specify a named configuration. ```bash mvn formatter:format ``` ```bash mvn formatter:format@format-sources ``` -------------------------------- ### execute() Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/formatter-mojo.md The main entry point for the Formatter Mojo, invoked by Maven. It orchestrates the file formatting process, including validation, file collection, formatter initialization, processing, caching, and reporting. ```APIDOC ## execute() ### Description Executes the formatter mojo. This is the main entry point called by Maven. Performs the following: 1. Validates file encoding 2. Collects source files matching include/exclude patterns 3. Initializes formatters for enabled file types 4. Processes each file, applying formatting 5. Caches file hashes to avoid re-formatting unchanged files 6. Reports results (formatted, skipped, unchanged, failed, readonly counts) ### Method ```java public void execute() throws MojoExecutionException, MojoFailureException ``` ### Throws - `MojoExecutionException` — if there are I/O errors or formatter initialization errors - `MojoFailureException` — if formatting cannot proceed ### Example ```java // Executed automatically by Maven during build // mvn formatter:format ``` ``` -------------------------------- ### getOptions() Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/javascript-formatter.md Retrieves the formatter options that were provided during its initialization. This is useful for inspecting the current configuration of the formatter. ```APIDOC ## getOptions() ### Description Returns the formatter options that were passed during initialization. ### Method GET (conceptual) ### Endpoint N/A (SDK method) ### Returns Map - A map containing Eclipse JSDT formatter configuration options. ### Example ```java Map options = formatter.getOptions(); String indentSize = options.get("org.eclipse.wst.jsdt.core.formatter.indent_size"); ``` ``` -------------------------------- ### Get Log Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Returns the Maven logger instance for the current project. This is useful for logging messages during the formatting process. ```java Log getLog() ``` -------------------------------- ### Helper initCfg Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/abstract-cacheable-formatter.md Helper method for subclasses to initialize common configuration like logger and encoding. It extracts these from the ConfigurationSource. ```java protected void initCfg(final ConfigurationSource cfg) ``` -------------------------------- ### Run Maven Formatter Plugin: Format Goal Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/README.md Executes the default 'format' goal of the formatter-maven-plugin to format source files and write changes to disk. ```bash mvn formatter:format ``` -------------------------------- ### Non-existent Config File Configuration Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md This XML configuration attempts to use a non-existent configuration file, resulting in a MojoExecutionException. ```xml non-existent-formatter.xml ``` -------------------------------- ### Correct XML Profile Structure Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/config-reader.md This XML demonstrates the correct structure for a configuration file, including the root `` element and a `` with the specified kind. ```xml ``` -------------------------------- ### Get Kind Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Returns the kind or type of the formatter profile. This can be used to differentiate between different types of profiles, such as code formatter profiles. ```java public String getKind() ``` -------------------------------- ### Skipping All Formatters Configuration Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md This configuration skips all formatters, leading to a MojoExecutionException because no configuration files are provided for any language. ```xml true true ``` -------------------------------- ### Format JSON File with Options Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/json-formatter.md Demonstrates formatting a package.json file using JsonFormatter with custom options for indentation and alphabetical ordering. It reads the file, formats its content, and writes back if the formatted content differs from the original. Supports different line endings. ```java JsonFormatter formatter = new JsonFormatter(); Map options = new HashMap<>(); options.put("indent", "2"); options.put("alphabeticalOrder", "true"); formatter.init(options, config); Path jsonFile = Paths.get("package.json"); String content = Files.readString(jsonFile); String formatted = formatter.formatFile(jsonFile, content, LineEnding.LF); if (formatted != null && !formatted.equals(content)) { Files.writeString(jsonFile, formatted); } ``` -------------------------------- ### Get Compiler Compliance Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Retrieves the Java compiler compliance version for the project. This indicates the Java version the code is expected to comply with. ```java String getCompilerCompliance() ``` -------------------------------- ### ValidateMojo Configuration for Multi-Module Builds Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/configuration.md Example configuration for the `validate` goal in multi-module Maven projects. Set `aggregator` to true to only validate in the reactor root. ```xml true eclipse-formatter.xml ``` -------------------------------- ### Get Compiler Sources Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Retrieves the Java compiler source version configured for the project. This helps in understanding the language level of the source code. ```java String getCompilerSources() ``` -------------------------------- ### Format CSS File with Options Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/css-formatter.md Demonstrates how to initialize and use the CssFormatter to format a CSS file with custom options like indentation and RGB color conversion. It reads the file content, formats it, and writes it back if changes were made. Ensure the CSS file exists and the formatter is properly initialized. ```java CssFormatter formatter = new CssFormatter(); Map options = new HashMap<>(); options.put("indent", "2"); options.put("rgbAsHex", "true"); formatter.init(options, config); Path cssFile = Paths.get("styles.css"); String content = Files.readString(cssFile); String formatted = formatter.formatFile(cssFile, content, LineEnding.LF); if (formatted != null && !formatted.equals(content)) { Files.writeString(cssFile, formatted); } ``` -------------------------------- ### Formatter Initialization Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/formatter-interface.md Initializes the formatter with configuration options and access to Maven project configuration. Use this method to set up formatter-specific settings like indentation and line endings. ```java void init(Map options, ConfigurationSource cfg) ``` ```java Formatter javaFormatter = new JavaFormatter(); Map options = new HashMap<>(); options.put("indent", "4"); options.put("lineending", "\n"); javaFormatter.init(options, configurationSource); ``` -------------------------------- ### Format File with AbstractCacheableFormatter Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/abstract-cacheable-formatter.md Use this method as the main entry point for formatting a file. It handles line-ending detection and conversion, with error recovery. Ensure the formatter is initialized before calling. ```java AbstractCacheableFormatter formatter = new JavaFormatter(); formatter.init(options, config); String result = formatter.formatFile( Paths.get("MyClass.java"), sourceCode, LineEnding.KEEP // Auto-detect original line endings ); ``` -------------------------------- ### Configure Encoding and Line Ending via Environment Variables Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/configuration.md The plugin can use environment variables for configuration by leveraging Maven's property substitution. Ensure the environment variables FILE_ENCODING and LINE_ENDING are set. ```xml ${env.FILE_ENCODING} ${env.LINE_ENDING} ``` -------------------------------- ### Get Encoding Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Returns the character encoding used for reading and writing files within the project. Consistent encoding is crucial for avoiding character corruption. ```java Charset getEncoding() ``` -------------------------------- ### Get File Encoding Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Retrieve the file encoding (charset) for reading and writing source files, ensuring consistency. Common values include UTF-8, ISO-8859-1, and Windows-1252. ```java Charset encoding = cfg.getEncoding(); // StandardCharsets.UTF_8 Path file = Paths.get("MyClass.java"); String content = Files.readString(file, encoding); ``` -------------------------------- ### FormatterMojo Implementation of ConfigurationSource Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Shows how a Maven plugin (FormatterMojo) can implement the ConfigurationSource interface by adapting its Maven mojo parameters. This allows the plugin to expose its configuration to other components that expect a ConfigurationSource. ```java @Mojo(name = "format", ...) public class FormatterMojo extends AbstractMojo implements ConfigurationSource { @Parameter(defaultValue = "1.8", property = "maven.compiler.source", required = true) private String compilerSource; @Parameter(defaultValue = "1.8", property = "maven.compiler.source", required = true) private String compilerCompliance; @Parameter(defaultValue = "1.8", property = "maven.compiler.target", required = true) private String compilerTargetPlatform; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) private File targetDirectory; @Parameter(property = "project.build.sourceEncoding", required = true) private String encoding; @Override public String getCompilerSources() { return this.compilerSource; } @Override public String getCompilerCompliance() { return this.compilerCompliance; } @Override public String getCompilerCodegenTargetPlatform() { return this.compilerTargetPlatform; } @Override public Path getTargetDirectory() { return this.targetDirectory.toPath(); } @Override public Charset getEncoding() { return Charset.forName(this.encoding); } @Override public Log getLog() { return super.getLog(); } } ``` -------------------------------- ### Get Maven Logger Instance Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Retrieve the Maven logger for outputting debug, info, warning, and error messages. Useful for logging within formatter initialization or processing. ```java void init(Map options, ConfigurationSource cfg) { Log log = cfg.getLog(); log.debug("Initializing formatter"); log.info("Formatter initialized"); } ``` -------------------------------- ### Initialize XMLFormatter with Options Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/xml-formatter.md Initializes the XML formatter with specific formatting preferences and line-ending settings. Configure options like line length, indentation, attribute splitting, and validation. ```java XMLFormatter formatter = new XMLFormatter(); Map options = new HashMap<>(); options.put("maxLineLength", "100"); options.put("wrapLongLines", "true"); options.put("tabInsteadOfSpaces", "false"); options.put("tabWidth", "2"); options.put("lineending", "\n"); formatter.init(options, mavenConfig); ``` -------------------------------- ### Format Minified CSS Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/css-formatter.md Demonstrates the input minified CSS before formatting. ```css body{color:rgb(255,128,0);margin:0;padding:10px}h1{font-size:24px;color:#333333} ``` -------------------------------- ### Abstract init Method Signature Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/abstract-cacheable-formatter.md Abstract method that subclasses must implement to initialize the formatter with specific options. ```java protected abstract void init(Map options, ConfigurationSource cfg) ``` -------------------------------- ### Get Compiler Codegen Target Platform Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Retrieves the Java compiler target platform version for code generation. This specifies the JVM version the compiled code will run on. ```java String getCompilerCodegenTargetPlatform() ``` -------------------------------- ### Check Formatting Operation Result Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Demonstrates how to check the result of a formatting operation using the Result enum. This example increments counters based on whether the operation was successful, skipped, or failed. ```java if (Result.SUCCESS.equals(result)) { successCount++; } else if (Result.SKIPPED.equals(result)) { skippedCount++; } else { // Result.FAIL failCount++; } ``` -------------------------------- ### FormatterMojo ConfigReader Usage Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/config-reader.md Shows how FormatterMojo uses ConfigReader to read configuration from a file, wrapping potential exceptions in MojoExecutionException. ```java private Map getOptionsFromConfigFile(final String newConfigFile) throws MojoExecutionException { try (var configInput = this.resourceManager.getResourceAsInputStream(newConfigFile)) { return new ConfigReader().read(configInput); } catch (final ConfigReadException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (final IOException e) { throw new MojoExecutionException("Cannot read config file [" + newConfigFile + "]", e); } catch (final SAXException e) { throw new MojoExecutionException("Cannot parse config file [" + newConfigFile + "]", e); } } ``` -------------------------------- ### Validate Formatter XML Configuration Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md Use the `xmllint` command-line tool to validate your `formatter.xml` configuration file for correctness. This is a useful step in configuration recovery. ```bash xmllint formatter.xml ``` -------------------------------- ### Formatter Mojo execute() Method Signature Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/formatter-mojo.md The main entry point for the Formatter Mojo, executed automatically by Maven during the build process. It handles file validation, collection, formatting, caching, and reporting. ```java public void execute() throws MojoExecutionException, MojoFailureException ``` -------------------------------- ### Valid Eclipse Formatter Profile XML Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/config-reader.md An example of a valid Eclipse formatter profile XML structure. This profile includes basic settings for Java source, compliance, and target platform versions. ```xml ``` -------------------------------- ### Default File Includes for Formatting Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/configuration.md If no explicit `` element is provided in the configuration, the plugin defaults to including files with common web and programming language extensions. This ensures standard project files are formatted. ```xml **/*.css **/*.json **/*.html **/*.java **/*.js **/*.xml ``` -------------------------------- ### Measure and Report Execution Time in FormatterMojo Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/time-util.md Demonstrates how to use `TimeUtil.printDuration` to report the execution time of the formatting process within the `FormatterMojo`. It measures time using `System.nanoTime` and logs the results. ```java final var startClock = System.nanoTime(); // ... formatting work ... final var duration = NANOSECONDS.toMillis(System.nanoTime() - startClock); final var elapsed = TimeUtil.printDuration(duration); final var results = String.format( "Processed %d files in %s (Formatted: %d, Skipped: %d, Unchanged: %d, Failed: %d, Readonly: %d)", numberOfFiles, elapsed, rc.successCount, rc.skippedCount, rc.unchangedCount, rc.failCount, rc.readOnlyCount); log.info(results); ``` -------------------------------- ### Validation Failure Error Message Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/validate-mojo.md An example of the error message displayed when the ValidateMojo detects unformatted files. It clearly indicates the problematic file and suggests how to resolve the issue by running the format goal. ```text File 'path/to/file.java' has not been previously formatted. Please format file (for example by invoking `mvn net.revelc.code.formatter:formatter-maven-plugin:2.30.0:format`) and commit before running validation! ``` -------------------------------- ### Get Java Compiler Compliance Version Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Retrieve the Java compiler compliance version, which specifies the Java language features allowed in the source code. This usually matches the source version but can be lower. ```java String compliance = cfg.getCompilerCompliance(); // "11" options.put("org.eclipse.jdt.core.compiler.compliance", compliance); ``` -------------------------------- ### Get Maven Project Target Directory Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Retrieve the path to the Maven project's build target directory (e.g., "target/"). This is commonly used as the default location for formatter cache files. ```java Path targetDir = cfg.getTargetDirectory(); // Paths.get("/project/target") Path cacheFile = targetDir.resolve("formatter-maven-cache.properties"); ``` -------------------------------- ### Skip Formatting in CI using Maven Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/README.md Command to skip code formatting during Continuous Integration builds by setting the 'formatter.skip' property to true. ```bash mvn formatter:validate -Dformatter.skip=true ``` -------------------------------- ### Get Java Compiler Codegen Target Platform Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Retrieve the Java compiler target platform version, determining the minimum JVM version for the compiled bytecode. This typically matches the source/compliance version but can be lower for compatibility. ```java String target = cfg.getCompilerCodegenTargetPlatform(); // "11" options.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", target); ``` -------------------------------- ### formatFile Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/abstract-cacheable-formatter.md The main entry point for formatting a file. It handles line-ending detection and conversion with error recovery, providing a robust way to format code. ```APIDOC ## formatFile(Path, String, LineEnding) ### Description Main entry point for formatting a file. Handles line-ending detection and conversion with error recovery. ### Method Signature ```java public String formatFile(final Path file, final String originalCode, final LineEnding ending) ``` ### Parameters #### Path Parameters - **file** (Path) - Required - Path to source file (for logging) - **originalCode** (String) - Required - Original source code as string - **ending** (LineEnding) - Required - Line ending style ### Returns - Formatted code if formatting succeeded - Original code if no changes needed or formatting failed gracefully - Never returns null ### Process 1. Logs processing start with file path and line ending 2. If ending is KEEP, auto-detects line ending from file content 3. Calls subclass's doFormat() method for actual formatting 4. If doFormat returns null and formatter type is CSS/HTML/XML, attempts line-ending-only fix 5. If no formatting occurred, falls back to fixLineEnding() 6. Returns original code if all formatting attempts produce no useful changes ### Example ```java AbstractCacheableFormatter formatter = new JavaFormatter(); formatter.init(options, config); String result = formatter.formatFile( Paths.get("MyClass.java"), sourceCode, LineEnding.KEEP // Auto-detect original line endings ); ``` ### Error Handling - Catches IOException, MalformedTreeException, BadLocationException - Logs warnings instead of throwing - Returns null from formatFile to signal formatting failure to caller ``` -------------------------------- ### Get Java Compiler Source Version Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/configuration-source.md Retrieve the Java compiler source version (e.g., "1.8", "11", "17"). This is used to configure Eclipse formatter options to match the project's source code syntax level. ```java String sourceVersion = cfg.getCompilerSources(); // "11" options.put("org.eclipse.jdt.core.compiler.source", sourceVersion); ``` -------------------------------- ### HTMLFormatter Initialization Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/html-formatter.md Initializes the HTML formatter with Jsoup output settings. This method configures the formatter based on provided options and a configuration source. ```APIDOC ## init(Map, ConfigurationSource) ### Description Initializes the HTML formatter with Jsoup output settings. ### Method Signature ```java @Override public void init(final Map options, final ConfigurationSource cfg) ``` ### Parameters #### Options - **charset** (string) - Optional - Output character encoding. Default: `UTF-8` - **escapeMode** (string) - Optional - Entity escape mode: `base`, `extended`, `xhtml`. Default: `xhtml` - **indentAmount** (integer) - Optional - Spaces per indentation level. Default: `4` - **maxPaddingWidth** (integer) - Optional - Maximum padding width (-1 = unlimited). Default: `-1` - **outlineMode** (boolean) - Optional - Use outline mode for output. Default: `true` - **pretty** (boolean) - Optional - Enable pretty-printing. Default: `true` - **syntax** (string) - Optional - Output syntax: `html`, `xml`. Default: `html` ### Request Example ```java HTMLFormatter formatter = new HTMLFormatter(); Map options = new HashMap<>(); options.put("charset", "UTF-8"); options.put("escapeMode", "xhtml"); options.put("indentAmount", "2"); options.put("pretty", "true"); formatter.init(options, mavenConfig); ``` ``` -------------------------------- ### Maven Command to Execute Formatter Mojo Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/formatter-mojo.md This is the command used to trigger the formatter mojo execution via Maven. ```bash // Executed automatically by Maven during build // mvn formatter:format ``` -------------------------------- ### XMLFormatter Initialization Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/xml-formatter.md Initializes the XML formatter with formatting preferences and line-ending settings. This method configures how the XML content will be formatted. ```APIDOC ## init(Map, ConfigurationSource) ### Description Initializes the XML formatter with formatting preferences and line-ending settings. ### Method Signature ```java public void init(final Map options, final ConfigurationSource cfg) ``` ### Parameters #### Options - **maxLineLength** (integer) - Optional - Maximum line length before wrapping. Default: `120` - **wrapLongLines** (boolean) - Optional - Whether to wrap lines exceeding maxLineLength. Default: `true` - **tabInsteadOfSpaces** (boolean) - Optional - Use tabs instead of spaces for indentation. Default: `true` - **tabWidth** (integer) - Optional - Width of indentation (spaces or tab width). Default: `4` - **splitMultiAttrs** (boolean) - Optional - Split multiple attributes onto separate lines. Default: `false` - **wellFormedValidation** (string) - Optional - Validation level: `ERROR`, `WARN`, or `IGNORE`. Default: `WARN` - **deleteBlankLines** (boolean) - Optional - Remove blank lines in output. Default: `false` - **lineending** (string) - Optional - Line ending to use in output. Default: `System.lineSeparator()` #### ConfigurationSource - **cfg** (ConfigurationSource) - Required - Maven configuration source ### Request Example ```java XMLFormatter formatter = new XMLFormatter(); Map options = new HashMap<>(); options.put("maxLineLength", "100"); options.put("wrapLongLines", "true"); options.put("tabInsteadOfSpaces", "false"); options.put("tabWidth", "2"); options.put("lineending", "\n"); formatter.init(options, mavenConfig); ``` ``` -------------------------------- ### Initialize Java Formatter Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/java-formatter.md Initializes the Java formatter with Eclipse formatter options and Maven configuration. Ensure the options map contains relevant Eclipse formatter preferences. ```java JavaFormatter formatter = new JavaFormatter(); Map options = new HashMap<>(); options.put("org.eclipse.jdt.core.compiler.source", "11"); options.put("org.eclipse.jdt.core.compiler.compliance", "11"); formatter.init(options, mavenConfig); ``` -------------------------------- ### Format Unformatted Files Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md Use this command to format files that have not been previously formatted. This is typically the first step before running validation. ```bash # Run formatter to fix mvn formatter:format ``` -------------------------------- ### doFormat(String, LineEnding) Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/css-formatter.md Performs the core CSS formatting logic using ph-css CSSOMParser. This is a protected method. ```APIDOC ## doFormat(String, LineEnding) ### Description Core formatting logic using ph-css CSSOMParser. This method is intended for internal use. ### Parameters #### Path Parameters - **code** (String) - Required - CSS source code to format - **ending** (LineEnding) - Required - Line ending style (unused by formatter) ### Returns Formatted CSS string, or null if no changes were made. ### Throws - `IOException` — if CSS parsing or formatting fails ### Process 1. Parses CSS input using CSSOMParser with SAC parser 2. Extracts CSSStyleSheet from parse result 3. Generates formatted CSS text using CSSFormat settings 4. Applies IE 7/8/9 hack preservation (tab character handling) 5. Ensures newline at end of file 6. Compares with original and returns null if identical ### Special Handling - Converts `\t;` back to `\9;` for IE hacks (CSS parser converts `\9` to tab during parsing) - Adds final newline if missing - Preserves CSS syntax validity ### Example ```java // Called internally by formatFile() String formatted = formatter.doFormat(cssSource, LineEnding.LF); ``` ``` -------------------------------- ### Formatted CSS with useSourceStringValues=true Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/css-formatter.md Illustrates CSS formatting where original string representations and quote styles are maintained. ```css /* Preserves original quote style and string representations where applicable. */ ``` -------------------------------- ### Catching ConfigReadException and Other Errors Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/errors.md This Java code demonstrates how to catch ConfigReadException, IOException, and SAXException when reading formatter configuration. It shows basic error logging and suggests handling options. ```java try { ConfigReader reader = new ConfigReader(); Map options = reader.read(configInput); } catch (ConfigReadException e) { logger.error("Failed to read formatter configuration: " + e.getMessage()); // Handle gracefully - may want to use defaults or fail build } catch (IOException e) { logger.error("I/O error reading config file", e); } catch (SAXException e) { logger.error("XML parsing error in config file", e); } ``` -------------------------------- ### Initialize HTMLFormatter Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/html-formatter.md Initializes the HTML formatter with Jsoup output settings. Configure options like charset, escape mode, and indentation. ```java HTMLFormatter formatter = new HTMLFormatter(); Map options = new HashMap<>(); options.put("charset", "UTF-8"); options.put("escapeMode", "xhtml"); options.put("indentAmount", "2"); options.put("pretty", "true"); formatter.init(options, mavenConfig); ``` -------------------------------- ### Check Formatter Initialization Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/javascript-formatter.md Verifies if the CodeFormatter instance has been successfully created and initialized. ```java @Override public boolean isInitialized() ``` -------------------------------- ### formatFile(Path, String, LineEnding) Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/xml-formatter.md Formats XML code and handles line endings for a given file. It takes the file path, original code, and desired line ending style as input. ```APIDOC ## formatFile(Path, String, LineEnding) ### Description Formats XML code and handles line endings. ### Parameters #### Path Parameters - **file** (Path) - Required - Path to XML source file - **originalCode** (String) - Required - Original XML source code - **ending** (LineEnding) - Required - Desired line ending style ### Returns Formatted XML or original if no changes ### Example ```java Path xmlFile = Paths.get("pom.xml"); String source = Files.readString(xmlFile); String formatted = formatter.formatFile(xmlFile, source, LineEnding.LF); ``` ``` -------------------------------- ### Format HTML File with Custom Options Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/html-formatter.md This Java snippet demonstrates how to initialize and use the HTMLFormatter to format an HTML file. It shows setting custom options like indent amount and escape mode, reading file content, formatting it, and writing the formatted content back to the file if it has changed. Ensure the Jsoup library is available as a dependency. ```java HTMLFormatter formatter = new HTMLFormatter(); Map options = new HashMap<>(); options.put("indentAmount", "2"); options.put("escapeMode", "xhtml"); formatter.init(options, config); Path htmlFile = Paths.get("index.html"); String content = Files.readString(htmlFile); String formatted = formatter.formatFile(htmlFile, content, LineEnding.LF); if (formatted != null && !formatted.equals(content)) { Files.writeString(htmlFile, formatted); } ``` -------------------------------- ### Initialize CssFormatter Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/api-reference/css-formatter.md Initializes the CSS formatter with specific formatting options. Configure indentation, RGB to hex conversion, and source string value preservation. ```java CssFormatter formatter = new CssFormatter(); Map options = new HashMap<>(); options.put("indent", "2"); options.put("rgbAsHex", "true"); options.put("useSourceStringValues", "false"); formatter.init(options, mavenConfig); ``` -------------------------------- ### Add Setting Method Source: https://github.com/revelc/formatter-maven-plugin/blob/main/_autodocs/types.md Adds a specific setting to the formatter profile. Each setting consists of an ID and its corresponding value. ```java public void addSetting(final Setting setting) ```