diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..a2ac6cca --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +end_of_line = lf +insert_final_newline = true \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..f36d7dff --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,18 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "daily" + open-pull-requests-limit: 10 + - package-ecosystem: "github-actions" + # Workflow files stored in the + # default location of `.github/workflows` + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index f567670f..8d94afb3 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -5,7 +5,8 @@ name: Java CI with Maven on: push: - branches: [ '**' ] + branches-ignore: + - 'dependabot/**' pull_request: branches: [ '**' ] @@ -29,3 +30,19 @@ jobs: cache: 'maven' - name: Build and Test with Java ${{ matrix.java }} run: mvn -B clean verify + + format-check: + runs-on: ubuntu-latest + timeout-minutes: 30 + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + java-version: 11 + distribution: 'temurin' + cache: 'maven' + - name: Validate Formatting + run: | + mvn -B validate -Pformat-check -Denforcer.skip=true diff --git a/.gitignore b/.gitignore index d86c5f65..a7c3f8b6 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ *.iml .idea target +.cache /test-output /.settings /.project diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 00000000..3bd96bee --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,2 @@ +* @dmlloyd +* @jamezp diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..367aa46b --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,132 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +James Perkins and/or David Lloyd . +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc new file mode 100644 index 00000000..c4862e40 --- /dev/null +++ b/CONTRIBUTING.adoc @@ -0,0 +1,65 @@ +:toc: + += Contributing Guide + +Want to contribute to the jboss-logmanager? We try to make it easy, and all contributions, even the smaller ones, +are more than welcome. This includes bug reports, fixes, documentation, etc. First though, please read this page +(including the small print at the end). + +== Legal + +All original contributions to jboss-logmanager are licensed under the +https://www.apache.org/licenses/LICENSE-2.0[ASL - Apache License], version 2.0 or later, or, if another license is +specified as governing the file or directory being modified, such other license. + +All contributions are subject to the https://developercertificate.org/[Developer Certificate of Origin (DCO)]. +The DCO text is also included verbatim in the [dco.txt](dco.txt) file in the root directory of the repository. + +== Reporting an issue + +This project uses https://issues.redhat.com/browse/LOGMGR[JIRA] for filing issues. + +If you believe you found a bug, and it's likely possible, please indicate a way to reproduce it, what you are seeing and +what you would expect to see. + +== Before you contribute + +To contribute, use GitHub Pull Requests, from your **own** fork. + +Also, make sure you have set up your Git authorship correctly: + +---- +git config --global user.name "Your Full Name" +git config --global user.email your.email@example.com +---- + +If you use different computers to contribute, please make sure the name is the same on all your computers. + +We use this information to acknowledge your contributions in release announcements. + +== Setup + +If you have not done so on this machine, you need to: + +* Install Git and configure your GitHub access +* Install Java SDK 11+ (OpenJDK recommended) + +=== IDE Config and Code Style + +jboss-logmanager has a strictly enforced code style. Code formatting is done by the Eclipse code formatter, using the config files +found in the https://github.com/jboss-logging/logging-dev-tools/blob/main/ide-config/src/main/resources/[eclipse-code-formatter.xml] +file. By default, when you run `mvn verify`, the code will be formatted automatically. +When submitting a pull request the CI build will fail if running the formatter results in any code changes, so it is +recommended that you always run a full Maven build before submitting a pull request. + +==== Eclipse Setup + +Open the *Preferences* window, and then navigate to _Java_ -> _Code Style_ -> _Formatter_. Click _Import_ and then +select the `eclipse-code-formatter.xml` downloaded from the above link or clone the repository and navigate to the file. + +Next navigate to _Java_ -> _Code Style_ -> _Organize Imports_. Click _Import_ and select the `eclipse.importorder` file. + +==== IDEA Setup + +Install the https://plugins.jetbrains.com/plugin/6546-adapter-for-eclipse-code-formatter/[Adapter for Eclipse Code Formatter]. +See the https://github.com/krasa/EclipseCodeFormatter#instructions[documentation] on how to configure the plugin. diff --git a/README.adoc b/README.adoc new file mode 100644 index 00000000..ef46c69a --- /dev/null +++ b/README.adoc @@ -0,0 +1,141 @@ += JBoss Log Manager + +The JBoss Log Manager is an extension of Java Util Logging (JUL). To use the log manager you must set the +`java.util.logging.manager` system property to `org.jboss.logmanager.LogManager`. + +== Usage + +To use the project you must set the `java.util.logging.manager` system property to `org.jboss.logmanager.LogManager` +and include the library on your class path. + +=== Maven +[source,xml] +---- + + org.jboss.logmanager + jboss-logmanager + ${version.org.jboss.logmanager} + +---- + +=== Logging Configuration + +==== `logging.properties` Configuration File + +* *Logger options* +** loggers=[,,...] - Specify a comma-separated list of logger categories which will be configured. Any categories not listed here will not be configured from the following properties. +** logger..level= - Specify the level for a category. The level can be one of the valid <>. If unspecified, the nearest parent's level will be inherited. +** logger..handlers=[,,...] - Specify a comma-separated list of the handler names to attach to this logger. The handlers must be configured in the same properties file. +** logger..filter= - Specify a filter for a category. See the <> for details on defining a filter. +** logger..useParentHandlers=(true|false) - Specify whether log messages should cascade up to parent handlers. The default value is true. + +* *Handler options* +** handler.= - [red]#(Required)# Specify the class name of the handler to instantiate. +** handler..module= - Specify the module name where the handler to instantiate is located. +** handler..level= - Restrict the level of this handler. If unspecified, the default value of ALL is retained. +** handler..encoding= - Specify the character encoding, if it is supported by this handler type. If not specified, a handler-specific default is used. +** handler..errorManager= - Specify the name of the error manager to use. The error manager must be configured in the same properties file. If unspecified, no error manager is configured. +** handler..filter= - Specify a filter for a category. See the <> for details on defining a filter. +** handler..formatter= - Specify the name of the formatter to use, if it is supported by this handler type. The formatter must be configured in the same properties file. If not specified, messages will not be logged for most handler types. +** handler..properties=[,,...] - Specify a list of JavaBean-style properties to additionally configure. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** handler..constructorProperties=[,,...] - Specify a list of properties that should be used as construction parameters. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** handler..= - Set the value of the named property. A POJO name can also be used as a value to use the instance of the <> for the value of the property. + +* *Error manager options* +** errorManager.= - [red]#(Required)# Specify the class name of the error manager to instantiate. +** errorManager..module= - Specify the module name where the error manager to instantiate is located. +** errorManager..properties=[,,...] - Specify a list of JavaBean-style properties to additionally configure. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** errorManager..constructorProperties=[,,...] - Specify a list of properties that should be used as construction parameters. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** errorManager..= - Set the value of the named property. A POJO name can also be used as a value to use the instance of the <> for the value of the property. + +* *Formatter options* +** formatter.= - [red]#(Required)# Specify the class name of the formatter to instantiate. +** formatter..module= - Specify the module name where the formatter to instantiate is located. +** formatter..properties=[,,...] - Specify a list of JavaBean-style properties to additionally configure. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** formatter..constructorProperties=[,,...] - Specify a list of properties that should be used as construction parameters. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** formatter..= - Set the value of the named property. A POJO name can also be used as a value to use the instance of the <> for the value of the property. + +* [[pojo]]*POJO options* +** pojo.= - [red]#(Required)# Specify the class name of the POJO to instantiate. +** pojo..module= - Specify the module name where the POJO to instantiate is located. +** pojo..properties=[,,...] - Specify a list of JavaBean-style properties to additionally configure. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** pojo..constructorProperties=[,,...] - Specify a list of properties that should be used as construction parameters. A rudimentary type introspection is done to ascertain the appropriate conversion for the given property. +** pojo..= - Set the value of the named property. A POJO name can also be used as a value to use the instance of the <> for the value of the property. + +==== [[log-levels]] Log Levels + +* `ALL` +* `FATAL` +* `SEVERE` +* `ERROR` +* `WARNING` +* `WARN` +* `INFO` +* `CONFIG` +* `FINE` +* `DEBUG` +* `FINER` +* `TRACE` +* `FINEST` +* `OFF` + +==== [[filter-expressions]] Filter Expressions + +[options="header"] +|==== +| Filter Type | Expression | Description | Parameter(s) +| accept | `accept` | Accepts all log messages. | None +| deny | `deny` | enies all log messages. | None +| not | `not(filterExpression)` | Accepts a filter as an argument and inverts the returned value. | The expression takes a single filter for it's argument. +| all | `all(filterExpressions)` | A filter consisting of several filters in a chain. If any filter find the log message to be unloggable, the message will not be logged and subsequent filters will not be checked. | The expression takes a comma delimited list of filters for it's argument. +| any | `any(filterExpressions)` | A filter consisting of several filters in a chain. If any filter fins the log message to be loggable, the message will be logged and the subsequent filters will not be checked. | The expression takes a comma delimited list of filters for it's argument. +| levelChange | `levelChange(level)` | A filter which modifies the log record with a new level. | The expression takes a single string based level for it's argument. +| levels | `levels(levels)` | A filter which includes log messages with a level that is listed in the list of levels. | The expression takes a comma delimited list of string based levels for it's argument. +| levelRange | `levelRange([minLevel,maxLevel])` | A filter which logs records that are within the level range. | The filter expression uses a "[" to indicate a minimum inclusive level and a "]" to indicate a maximum inclusive level. Otherwise use "(" or ")" respectively indicate exclusive. The first argument for the expression is the minimum level allowed, the second argument is the maximum level allowed. +| match | `match("pattern")` | A regular-expression based filter. The raw unformatted message is used against the pattern. | The expression takes a regular expression for it's argument.` +| substitute | `substitute("pattern", "replacement value")` | A filter which replaces the first match to the pattern with the replacement value. | The first argument for the expression is the pattern the second argument is the replacement text. +| substituteAll | `substituteAll("pattern", "replacement value")` | A filter which replaces all matches of the pattern with the replacement value. | The first argument for the expression is the pattern the second argument is the replacement text. +|==== + +==== Example configuration + +This is an example logging.properties that you can use to get started. + +---- +# Additional logger names to configure (root logger is always configured) +loggers=org.foo.bar,org.foo.baz + +# Root logger level +logger.level=DEBUG + +# Declare handlers for the root logger +logger.handlers=CONSOLE,FILE + +# Declare handlers for additional loggers +logger.org.foo.bar.handlers=FILE +logger.org.foo.bar.useParentHandlers=false + +# Console handler configuration +handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler +handler.CONSOLE.properties=autoFlush +handler.CONSOLE.level=INFO +handler.CONSOLE.autoFlush=true +handler.CONSOLE.formatter=PATTERN + +# File handler configuration +handler.FILE=org.jboss.logmanager.handlers.FileHandler +handler.FILE.level=DEBUG +handler.FILE.properties=autoFlush,fileName +handler.FILE.autoFlush=true +handler.FILE.fileName=${jboss.server.log.dir}/project.log +handler.FILE.formatter=PATTERN + +# The log format pattern for both logs +formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter +formatter.PATTERN.properties=pattern +formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c{1}] %m%n +---- + +== Contributing + +See the link:CONTRIBUTING.adoc[contributing guide]. diff --git a/pom.xml b/pom.xml index af9e8334..400c88ab 100644 --- a/pom.xml +++ b/pom.xml @@ -24,9 +24,9 @@ 4.0.0 - org.jboss - jboss-parent - 39 + org.jboss.logging + logging-parent + 1.0.0.Final JBoss Log Manager @@ -38,11 +38,20 @@ Apache License 2.0 - http://repository.jboss.org/licenses/apache-2.0.txt + https://repository.jboss.org/licenses/apache-2.0.txt repo + + + scm:git:git://github.com/jboss-logging/jboss-logmanager.git + scm:git:git@github.com:jboss-logging/jboss-logmanager.git + https://github.com/jboss-logging/jboss-logmanager/tree/main/ + HEAD + + 1.11.0 @@ -63,10 +72,6 @@ ${skipTests} ${skipTests} - 11 - 11 - - 11 @@ -187,9 +192,14 @@ maven-compiler-plugin - - 11 - + + + net.revelc.code.formatter + formatter-maven-plugin + + + net.revelc.code + impsort-maven-plugin maven-failsafe-plugin @@ -271,4 +281,41 @@ + + + + format-check + + + + + net.revelc.code.formatter + formatter-maven-plugin + + + validate-format + validate + + validate + + + + + + net.revelc.code + impsort-maven-plugin + + + check-import-sort + validate + + check + + + + + + + + diff --git a/security.txt b/security.txt new file mode 100644 index 00000000..0c146a97 --- /dev/null +++ b/security.txt @@ -0,0 +1,13 @@ +# Security Policy + +## Security Contacts and Procedures + +The RESTEasy community takes security very seriously, and we aim to take immediate action to address serious +security-related problems that involve our products or services. + +Please report any suspected security vulnerability in this project to Red Hat Product Security at secalert@redhat.com. +You can use our GPG key to communicate with us securely. + +To report an issue in any Red Hat branded website or online service, please contact Red Hat Information Security at +site-security@redhat.com. +https://access.redhat.com/security/team/contact diff --git a/src/main/java/org/jboss/logmanager/AtomicArray.java b/src/main/java/org/jboss/logmanager/AtomicArray.java index b03582b5..cd450b11 100644 --- a/src/main/java/org/jboss/logmanager/AtomicArray.java +++ b/src/main/java/org/jboss/logmanager/AtomicArray.java @@ -23,15 +23,14 @@ import java.util.Arrays; import java.util.Comparator; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - import java.util.logging.Handler; /** - * Utility for snapshot/copy-on-write arrays. To use these methods, two things are required: an immutable array + * Utility for snapshot/copy-on-write arrays. To use these methods, two things are required: an immutable array * stored on a volatile field, and an instance of * {@link java.util.concurrent.atomic.AtomicReferenceFieldUpdater AtomicReferenceFieldUpdater} - * which corresponds to that field. Some of these methods perform multi-step operations; if the array field value is - * changed in the middle of such an operation, the operation is retried. To avoid spinning, in some situations it + * which corresponds to that field. Some of these methods perform multi-step operations; if the array field value is + * changed in the middle of such an operation, the operation is retried. To avoid spinning, in some situations it * may be advisable to hold a write lock to prevent multiple concurrent updates. * * @param the type which contains the target field @@ -46,7 +45,7 @@ final class AtomicArray { /** * Construct an instance. * - * @param updater the field updater + * @param updater the field updater * @param componentType the component class */ public AtomicArray(AtomicReferenceFieldUpdater updater, Class componentType) { @@ -58,18 +57,18 @@ public AtomicArray(AtomicReferenceFieldUpdater updater, Class compone /** * Convenience method to create an instance. * - * @param updater the field updater + * @param updater the field updater * @param componentType the component class - * @param the type which contains the target field - * @param the array value type + * @param the type which contains the target field + * @param the array value type * @return the new instance */ public static AtomicArray create(AtomicReferenceFieldUpdater updater, Class componentType) { - return new AtomicArray(updater, componentType); + return new AtomicArray(updater, componentType); } /** - * Convenience method to set the field value to the empty array. Empty array instances are shared. + * Convenience method to set the field value to the empty array. Empty array instances are shared. * * @param instance the instance holding the field */ @@ -81,7 +80,7 @@ public void clear(T instance) { * Update the value of this array. * * @param instance the instance holding the field - * @param value the new value + * @param value the new value */ public void set(T instance, V[] value) { updater.set(instance, value); @@ -91,7 +90,7 @@ public void set(T instance, V[] value) { * Atomically get and update the value of this array. * * @param instance the instance holding the field - * @param value the new value + * @param value the new value */ public V[] getAndSet(T instance, V[] value) { return updater.getAndSet(instance, value); @@ -108,7 +107,7 @@ private static V[] copyOf(final Class componentType, V[] old, int newLen) * Atomically replace the array with a new array which is one element longer, and which includes the given value. * * @param instance the instance holding the field - * @param value the updated value + * @param value the updated value */ public void add(T instance, V value) { final AtomicReferenceFieldUpdater updater = this.updater; @@ -125,11 +124,12 @@ public void add(T instance, V value) { /** * Atomically replace the array with a new array which is one element longer, and which includes the given value, - * if the value is not already present within the array. This method does a linear search for the target value. + * if the value is not already present within the array. This method does a linear search for the target value. * * @param instance the instance holding the field - * @param value the updated value - * @param identity {@code true} if comparisons should be done using reference identity, or {@code false} to use the {@code equals()} method + * @param value the updated value + * @param identity {@code true} if comparisons should be done using reference identity, or {@code false} to use the + * {@code equals()} method * @return {@code true} if the value was added, or {@code false} if it was already present */ public boolean addIfAbsent(T instance, V value, boolean identity) { @@ -163,8 +163,9 @@ public boolean addIfAbsent(T instance, V value, boolean identity) { * the value is present in the array. * * @param instance the instance holding the field - * @param value the updated value - * @param identity {@code true} if comparisons should be done using reference identity, or {@code false} to use the {@code equals()} method + * @param value the updated value + * @param identity {@code true} if comparisons should be done using reference identity, or {@code false} to use the + * {@code equals()} method * @return {@code true} if the value was removed, or {@code false} if it was not present */ public boolean remove(T instance, V value, boolean identity) { @@ -209,8 +210,9 @@ public boolean remove(T instance, V value, boolean identity) { * the value is present in the array. * * @param instance the instance holding the field - * @param value the updated value - * @param identity {@code true} if comparisons should be done using reference identity, or {@code false} to use the {@code equals()} method + * @param value the updated value + * @param identity {@code true} if comparisons should be done using reference identity, or {@code false} to use the + * {@code equals()} method * @return the number of values removed */ public int removeAll(T instance, V value, boolean identity) { @@ -247,8 +249,8 @@ public int removeAll(T instance, V value, boolean identity) { newVal = emptyArray; } else { newVal = newInstance(componentType, newLen); - for (int i = 0, j = 0; i < oldLen; i ++) { - if (! removeSlots[i]) { + for (int i = 0, j = 0; i < oldLen; i++) { + if (!removeSlots[i]) { newVal[j++] = oldVal[i]; } } @@ -261,10 +263,10 @@ public int removeAll(T instance, V value, boolean identity) { } /** - * Add a value to a sorted array. Does not check for duplicates. + * Add a value to a sorted array. Does not check for duplicates. * - * @param instance the instance holding the field - * @param value the value to add + * @param instance the instance holding the field + * @param value the value to add * @param comparator a comparator, or {@code null} to use natural ordering */ public void add(T instance, V value, Comparator comparator) { @@ -284,10 +286,10 @@ public void add(T instance, V value, Comparator comparator) { } /** - * Add a value to a sorted array if it is not already present. Does not check for duplicates. + * Add a value to a sorted array if it is not already present. Does not check for duplicates. * - * @param instance the instance holding the field - * @param value the value to add + * @param instance the instance holding the field + * @param value the value to add * @param comparator a comparator, or {@code null} to use natural ordering */ public boolean addIfAbsent(T instance, V value, Comparator comparator) { @@ -310,11 +312,11 @@ public boolean addIfAbsent(T instance, V value, Comparator comparator } /** - * Remove a value to a sorted array. Does not check for duplicates. If there are multiple occurrences of a value, + * Remove a value to a sorted array. Does not check for duplicates. If there are multiple occurrences of a value, * there is no guarantee as to which one is removed. * - * @param instance the instance holding the field - * @param value the value to remove + * @param instance the instance holding the field + * @param value the value to remove * @param comparator a comparator, or {@code null} to use natural ordering */ public boolean remove(T instance, V value, Comparator comparator) { @@ -342,7 +344,7 @@ public boolean remove(T instance, V value, Comparator comparator) { /** * Sort an array. * - * @param instance the instance holding the field + * @param instance the instance holding the field * @param comparator a comparator, or {@code null} to use natural ordering */ public void sort(T instance, Comparator comparator) { @@ -361,7 +363,7 @@ public void sort(T instance, Comparator comparator) { } private static int insertionPoint(int searchResult) { - return searchResult > 0 ? searchResult : - (searchResult + 1); + return searchResult > 0 ? searchResult : -(searchResult + 1); } @SuppressWarnings({ "unchecked" }) @@ -379,8 +381,8 @@ private static V[] newInstance(Class componentType, int length) { * Compare and set the array. * * @param instance the instance holding the field - * @param expect the expected value - * @param update the update value + * @param expect the expected value + * @param update the update value * @return {@code true} if the value was updated or {@code false} if the expected value did not match */ public boolean compareAndSet(final T instance, final V[] expect, final V[] update) { diff --git a/src/main/java/org/jboss/logmanager/CallerClassLoaderLogContextSelector.java b/src/main/java/org/jboss/logmanager/CallerClassLoaderLogContextSelector.java index ea98f153..ad0293be 100644 --- a/src/main/java/org/jboss/logmanager/CallerClassLoaderLogContextSelector.java +++ b/src/main/java/org/jboss/logmanager/CallerClassLoaderLogContextSelector.java @@ -31,7 +31,7 @@ * a {@linkplain #addLogApiClassLoader(ClassLoader) log API} or does not have a {@code null} classloader will be the * class loader used. */ -@SuppressWarnings({"WeakerAccess", "unused"}) +@SuppressWarnings({ "WeakerAccess", "unused" }) public final class CallerClassLoaderLogContextSelector implements LogContextSelector { private static final Permission REGISTER_LOG_CONTEXT_PERMISSION = new RuntimePermission("registerLogContext", null); @@ -39,7 +39,7 @@ public final class CallerClassLoaderLogContextSelector implements LogContextSele private static final Permission LOG_API_PERMISSION = new RuntimePermission("logApiPermission", null); /** - * Construct a new instance. If no matching log context is found, the provided default selector is consulted. + * Construct a new instance. If no matching log context is found, the provided default selector is consulted. * * @param defaultSelector the selector to consult if no matching log context is found */ @@ -48,7 +48,7 @@ public CallerClassLoaderLogContextSelector(final LogContextSelector defaultSelec } /** - * Construct a new instance. If no matching log context is found, the provided default selector is consulted. + * Construct a new instance. If no matching log context is found, the provided default selector is consulted. *

* If the {@code checkParentClassLoaders} is set to {@code true} this selector recursively searches the class loader * parents until a match is found or a {@code null} parent is found. @@ -59,20 +59,21 @@ public CallerClassLoaderLogContextSelector(final LogContextSelector defaultSelec * found for the class loader and the {@link ClassLoader#getParent() parent class * loader} should be checked */ - public CallerClassLoaderLogContextSelector(final LogContextSelector defaultSelector, final boolean checkParentClassLoaders) { + public CallerClassLoaderLogContextSelector(final LogContextSelector defaultSelector, + final boolean checkParentClassLoaders) { this.defaultSelector = defaultSelector == null ? LogContext.DEFAULT_LOG_CONTEXT_SELECTOR : defaultSelector; this.checkParentClassLoaders = checkParentClassLoaders; } /** - * Construct a new instance. If no matching log context is found, the system context is used. + * Construct a new instance. If no matching log context is found, the system context is used. */ public CallerClassLoaderLogContextSelector() { this(false); } /** - * Construct a new instance. If no matching log context is found, the system context is used. + * Construct a new instance. If no matching log context is found, the system context is used. *

* If the {@code checkParentClassLoaders} is set to {@code true} this selector recursively searches the class loader * parents until a match is found or a {@code null} parent is found. @@ -104,7 +105,7 @@ private LogContext check(final ClassLoader classLoader) { return context; } final ClassLoader parent = classLoader.getParent(); - if (parent != null && checkParentClassLoaders && ! logApiClassLoaders.contains(parent)) { + if (parent != null && checkParentClassLoaders && !logApiClassLoaders.contains(parent)) { return check(parent); } return defaultSelector.getLogContext(); @@ -118,8 +119,7 @@ private LogContext check(final ClassLoader classLoader) { */ @Override public LogContext getLogContext() { - return System.getSecurityManager() == null? logContextAction.run() : - AccessController.doPrivileged(logContextAction); + return System.getSecurityManager() == null ? logContextAction.run() : AccessController.doPrivileged(logContextAction); } /** @@ -154,7 +154,8 @@ public boolean removeLogApiClassLoader(ClassLoader apiClassLoader) { } /** - * Register a class loader with a log context. This method requires the {@code registerLogContext} {@link RuntimePermission}. + * Register a class loader with a log context. This method requires the {@code registerLogContext} + * {@link RuntimePermission}. * * @param classLoader the classloader * @param logContext the log context @@ -167,12 +168,14 @@ public void registerLogContext(ClassLoader classLoader, LogContext logContext) t sm.checkPermission(REGISTER_LOG_CONTEXT_PERMISSION); } if (contextMap.putIfAbsent(classLoader, logContext) != null) { - throw new IllegalArgumentException("ClassLoader instance is already registered to a log context (" + classLoader + ")"); + throw new IllegalArgumentException( + "ClassLoader instance is already registered to a log context (" + classLoader + ")"); } } /** - * Unregister a class loader/log context association. This method requires the {@code unregisterLogContext} {@link RuntimePermission}. + * Unregister a class loader/log context association. This method requires the {@code unregisterLogContext} + * {@link RuntimePermission}. * * @param classLoader the classloader * @param logContext the log context diff --git a/src/main/java/org/jboss/logmanager/ClassLoaderLogContextSelector.java b/src/main/java/org/jboss/logmanager/ClassLoaderLogContextSelector.java index 4a7f2a41..5cc53bb1 100644 --- a/src/main/java/org/jboss/logmanager/ClassLoaderLogContextSelector.java +++ b/src/main/java/org/jboss/logmanager/ClassLoaderLogContextSelector.java @@ -20,8 +20,8 @@ package org.jboss.logmanager; import java.security.AccessController; -import java.security.PrivilegedAction; import java.security.Permission; +import java.security.PrivilegedAction; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentMap; @@ -37,7 +37,7 @@ public final class ClassLoaderLogContextSelector implements LogContextSelector { private static final Permission LOG_API_PERMISSION = new RuntimePermission("logApiPermission", null); /** - * Construct a new instance. If no matching log context is found, the provided default selector is consulted. + * Construct a new instance. If no matching log context is found, the provided default selector is consulted. * * @param defaultSelector the selector to consult if no matching log context is found */ @@ -46,7 +46,7 @@ public ClassLoaderLogContextSelector(final LogContextSelector defaultSelector) { } /** - * Construct a new instance. If no matching log context is found, the provided default selector is consulted. + * Construct a new instance. If no matching log context is found, the provided default selector is consulted. *

* If the {@code checkParentClassLoaders} is set to {@code true} this selector recursively searches the class loader * parents until a match is found or a {@code null} parent is found. @@ -62,14 +62,14 @@ public ClassLoaderLogContextSelector(final LogContextSelector defaultSelector, f } /** - * Construct a new instance. If no matching log context is found, the system context is used. + * Construct a new instance. If no matching log context is found, the system context is used. */ public ClassLoaderLogContextSelector() { this(false); } /** - * Construct a new instance. If no matching log context is found, the system context is used. + * Construct a new instance. If no matching log context is found, the system context is used. *

* If the {@code checkParentClassLoaders} is set to {@code true} this selector recursively searches the class loader * parents until a match is found or a {@code null} parent is found. @@ -115,12 +115,11 @@ public LogContext run() { }; /** - * {@inheritDoc} This instance will consult the call stack to see if any calling classloader is associated + * {@inheritDoc} This instance will consult the call stack to see if any calling classloader is associated * with any log context. */ public LogContext getLogContext() { - return System.getSecurityManager() == null? logContextAction.run() : - AccessController.doPrivileged(logContextAction); + return System.getSecurityManager() == null ? logContextAction.run() : AccessController.doPrivileged(logContextAction); } /** @@ -153,10 +152,11 @@ public boolean removeLogApiClassLoader(ClassLoader apiClassLoader) { } /** - * Register a class loader with a log context. This method requires the {@code registerLogContext} {@link RuntimePermission}. + * Register a class loader with a log context. This method requires the {@code registerLogContext} + * {@link RuntimePermission}. * * @param classLoader the classloader - * @param logContext the log context + * @param logContext the log context * @throws IllegalArgumentException if the classloader is already associated with a log context */ public void registerLogContext(ClassLoader classLoader, LogContext logContext) throws IllegalArgumentException { @@ -165,15 +165,17 @@ public void registerLogContext(ClassLoader classLoader, LogContext logContext) t sm.checkPermission(REGISTER_LOG_CONTEXT_PERMISSION); } if (contextMap.putIfAbsent(classLoader, logContext) != null) { - throw new IllegalArgumentException("ClassLoader instance is already registered to a log context (" + classLoader + ")"); + throw new IllegalArgumentException( + "ClassLoader instance is already registered to a log context (" + classLoader + ")"); } } /** - * Unregister a class loader/log context association. This method requires the {@code unregisterLogContext} {@link RuntimePermission}. + * Unregister a class loader/log context association. This method requires the {@code unregisterLogContext} + * {@link RuntimePermission}. * * @param classLoader the classloader - * @param logContext the log context + * @param logContext the log context * @return {@code true} if the association exists and was removed, {@code false} otherwise */ public boolean unregisterLogContext(ClassLoader classLoader, LogContext logContext) { diff --git a/src/main/java/org/jboss/logmanager/ContextClassLoaderLogContextSelector.java b/src/main/java/org/jboss/logmanager/ContextClassLoaderLogContextSelector.java index 27b08aae..dc2ff407 100644 --- a/src/main/java/org/jboss/logmanager/ContextClassLoaderLogContextSelector.java +++ b/src/main/java/org/jboss/logmanager/ContextClassLoaderLogContextSelector.java @@ -19,14 +19,14 @@ package org.jboss.logmanager; -import java.security.Permission; -import java.security.PrivilegedAction; -import java.util.concurrent.ConcurrentMap; - import static java.lang.System.getSecurityManager; import static java.lang.Thread.currentThread; import static java.security.AccessController.doPrivileged; +import java.security.Permission; +import java.security.PrivilegedAction; +import java.util.concurrent.ConcurrentMap; + /** * A log context selector which chooses a log context based on the thread context classloader. */ @@ -36,7 +36,7 @@ public final class ContextClassLoaderLogContextSelector implements LogContextSel private static final Permission UNREGISTER_LOG_CONTEXT_PERMISSION = new RuntimePermission("unregisterLogContext", null); /** - * Construct a new instance. If no matching log context is found, the provided default selector is consulted. + * Construct a new instance. If no matching log context is found, the provided default selector is consulted. * * @param defaultSelector the selector to consult if no matching log context is found */ @@ -45,7 +45,7 @@ public ContextClassLoaderLogContextSelector(final LogContextSelector defaultSele } /** - * Construct a new instance. If no matching log context is found, the system context is used. + * Construct a new instance. If no matching log context is found, the system context is used. */ public ContextClassLoaderLogContextSelector() { this(LogContext.DEFAULT_LOG_CONTEXT_SELECTOR); @@ -69,15 +69,15 @@ public LogContext run() { }; public LogContext getLogContext() { - return System.getSecurityManager() == null? logContextAction.run() : - doPrivileged(logContextAction); + return System.getSecurityManager() == null ? logContextAction.run() : doPrivileged(logContextAction); } /** - * Register a class loader with a log context. This method requires the {@code registerLogContext} {@link RuntimePermission}. + * Register a class loader with a log context. This method requires the {@code registerLogContext} + * {@link RuntimePermission}. * * @param classLoader the classloader - * @param logContext the log context + * @param logContext the log context * @throws IllegalArgumentException if the classloader is already associated with a log context */ public void registerLogContext(ClassLoader classLoader, LogContext logContext) throws IllegalArgumentException { @@ -86,15 +86,17 @@ public void registerLogContext(ClassLoader classLoader, LogContext logContext) t sm.checkPermission(REGISTER_LOG_CONTEXT_PERMISSION); } if (contextMap.putIfAbsent(classLoader, logContext) != null) { - throw new IllegalArgumentException("ClassLoader instance is already registered to a log context (" + classLoader + ")"); + throw new IllegalArgumentException( + "ClassLoader instance is already registered to a log context (" + classLoader + ")"); } } /** - * Unregister a class loader/log context association. This method requires the {@code unregisterLogContext} {@link RuntimePermission}. + * Unregister a class loader/log context association. This method requires the {@code unregisterLogContext} + * {@link RuntimePermission}. * * @param classLoader the classloader - * @param logContext the log context + * @param logContext the log context * @return {@code true} if the association exists and was removed, {@code false} otherwise */ public boolean unregisterLogContext(ClassLoader classLoader, LogContext logContext) { diff --git a/src/main/java/org/jboss/logmanager/CopyOnWriteMap.java b/src/main/java/org/jboss/logmanager/CopyOnWriteMap.java index 5d6a8138..3ef6d81a 100644 --- a/src/main/java/org/jboss/logmanager/CopyOnWriteMap.java +++ b/src/main/java/org/jboss/logmanager/CopyOnWriteMap.java @@ -33,7 +33,8 @@ final class CopyOnWriteMap extends AbstractMap implements Concurrent @SuppressWarnings("unchecked") private volatile FastCopyHashMap map = EMPTY; - private static final AtomicReferenceFieldUpdater mapUpdater = AtomicReferenceFieldUpdater.newUpdater(CopyOnWriteMap.class, FastCopyHashMap.class, "map"); + private static final AtomicReferenceFieldUpdater mapUpdater = AtomicReferenceFieldUpdater + .newUpdater(CopyOnWriteMap.class, FastCopyHashMap.class, "map"); public V get(final Object key) { return map.get(key); @@ -63,7 +64,7 @@ public V put(final K key, final V value) { oldVal = map; newVal = oldVal.clone(); result = newVal.put(key, value); - } while (! mapUpdater.compareAndSet(this, oldVal, newVal)); + } while (!mapUpdater.compareAndSet(this, oldVal, newVal)); return result; } @@ -72,12 +73,12 @@ public V remove(final Object key) { V result; do { oldVal = map; - if (! oldVal.containsKey(key)) { + if (!oldVal.containsKey(key)) { return null; } newVal = oldVal.clone(); result = newVal.remove(key); - } while (! mapUpdater.compareAndSet(this, oldVal, newVal)); + } while (!mapUpdater.compareAndSet(this, oldVal, newVal)); return result; } @@ -99,7 +100,7 @@ public V putIfAbsent(final K key, final V value) { } newVal = oldVal.clone(); newVal.put(key, value); - } while (! mapUpdater.compareAndSet(this, oldVal, newVal)); + } while (!mapUpdater.compareAndSet(this, oldVal, newVal)); return null; } @@ -118,7 +119,7 @@ public boolean remove(final Object key, final Object value) { } else { return false; } - } while (! mapUpdater.compareAndSet(this, oldVal, newVal)); + } while (!mapUpdater.compareAndSet(this, oldVal, newVal)); return true; } @@ -132,7 +133,7 @@ public boolean replace(final K key, final V oldValue, final V newValue) { } else { return false; } - } while (! mapUpdater.compareAndSet(this, oldVal, newVal)); + } while (!mapUpdater.compareAndSet(this, oldVal, newVal)); return true; } @@ -147,7 +148,7 @@ public V replace(final K key, final V value) { } else { return null; } - } while (! mapUpdater.compareAndSet(this, oldVal, newVal)); + } while (!mapUpdater.compareAndSet(this, oldVal, newVal)); return result; } diff --git a/src/main/java/org/jboss/logmanager/CopyOnWriteWeakMap.java b/src/main/java/org/jboss/logmanager/CopyOnWriteWeakMap.java index 6d5b1fe2..55f46d24 100644 --- a/src/main/java/org/jboss/logmanager/CopyOnWriteWeakMap.java +++ b/src/main/java/org/jboss/logmanager/CopyOnWriteWeakMap.java @@ -35,7 +35,9 @@ final class CopyOnWriteWeakMap extends AbstractMap implements Concur private static final FastCopyHashMap EMPTY = new FastCopyHashMap(32, 0.25f); @SuppressWarnings({ "unchecked" }) - private FastCopyHashMap> empty() { return (FastCopyHashMap>) EMPTY; } + private FastCopyHashMap> empty() { + return (FastCopyHashMap>) EMPTY; + } private volatile FastCopyHashMap> map = empty(); @@ -96,10 +98,11 @@ public V putIfAbsent(final K key, final V value) { final Node oldNode = map.get(key); if (oldNode != null) { final V val = oldNode.get(); - if (val != null) return val; + if (val != null) + return val; } final FastCopyHashMap> newMap = cleanCopyForMod(); - newMap.put(key, new Node(key, value, queue)); + newMap.put(key, new Node(key, value, queue)); map = newMap; return null; } @@ -168,7 +171,8 @@ public boolean containsKey(final Object key) { } public boolean containsValue(final Object value) { - if (value == null) return false; + if (value == null) + return false; for (Node node : map.values()) { if (value.equals(node.get())) { return true; @@ -198,7 +202,8 @@ public V put(final K key, final V value) { } public V remove(final Object key) { - if (key == null) return null; + if (key == null) + return null; synchronized (this) { final FastCopyHashMap> newMap = cleanCopyForRemove(); final Node old = newMap.remove(key); @@ -218,7 +223,8 @@ public Set> entrySet() { final Map copyMap = new HashMap(); for (Node node : snapshot.values()) { final V value = node.get(); - if (value == null) continue; + if (value == null) + continue; final K key = node.getKey(); copyMap.put(key, value); } @@ -245,7 +251,8 @@ public Node poll() { } void clear() { - while (poll() != null); + while (poll() != null) + ; } } } diff --git a/src/main/java/org/jboss/logmanager/ExtErrorManager.java b/src/main/java/org/jboss/logmanager/ExtErrorManager.java index 0abb2eb2..0b8e6f69 100644 --- a/src/main/java/org/jboss/logmanager/ExtErrorManager.java +++ b/src/main/java/org/jboss/logmanager/ExtErrorManager.java @@ -15,13 +15,20 @@ public abstract class ExtErrorManager extends ErrorManager { */ protected String nameForCode(int code) { switch (code) { - case CLOSE_FAILURE: return "CLOSE_FAILURE"; - case FLUSH_FAILURE: return "FLUSH_FAILURE"; - case FORMAT_FAILURE: return "FORMAT_FAILURE"; - case GENERIC_FAILURE: return "GENERIC_FAILURE"; - case OPEN_FAILURE: return "OPEN_FAILURE"; - case WRITE_FAILURE: return "WRITE_FAILURE"; - default: return "INVALID (" + code + ")"; + case CLOSE_FAILURE: + return "CLOSE_FAILURE"; + case FLUSH_FAILURE: + return "FLUSH_FAILURE"; + case FORMAT_FAILURE: + return "FORMAT_FAILURE"; + case GENERIC_FAILURE: + return "GENERIC_FAILURE"; + case OPEN_FAILURE: + return "OPEN_FAILURE"; + case WRITE_FAILURE: + return "WRITE_FAILURE"; + default: + return "INVALID (" + code + ")"; } } @@ -30,21 +37,22 @@ public void error(final String msg, final Exception ex, final int code) { } /** - * Convert the given error to a log record which can be published to handler(s) or stored. Care should + * Convert the given error to a log record which can be published to handler(s) or stored. Care should * be taken not to publish the log record to a logger that writes to the same handler that produced the error. * - * @param msg the error message (possibly {@code null}) - * @param ex the error exception (possibly {@code null}) + * @param msg the error message (possibly {@code null}) + * @param ex the error exception (possibly {@code null}) * @param code the error code * @return the log record (not {@code null}) */ protected ExtLogRecord errorToLogRecord(String msg, Exception ex, int code) { - final ExtLogRecord record = new ExtLogRecord(Level.ERROR, "Failed to publish log record (%s[%d]): %s", ExtLogRecord.FormatStyle.PRINTF, getClass().getName()); + final ExtLogRecord record = new ExtLogRecord(Level.ERROR, "Failed to publish log record (%s[%d]): %s", + ExtLogRecord.FormatStyle.PRINTF, getClass().getName()); final String codeStr = nameForCode(code); record.setParameters(new Object[] { - codeStr, - Integer.valueOf(code), - msg, + codeStr, + Integer.valueOf(code), + msg, }); record.setThrown(ex); record.setLoggerName(""); diff --git a/src/main/java/org/jboss/logmanager/ExtFormatter.java b/src/main/java/org/jboss/logmanager/ExtFormatter.java index 1219711f..752c4723 100644 --- a/src/main/java/org/jboss/logmanager/ExtFormatter.java +++ b/src/main/java/org/jboss/logmanager/ExtFormatter.java @@ -41,12 +41,12 @@ public ExtFormatter() { * Wrap an existing formatter with an {@link ExtFormatter}, optionally replacing message formatting with * the default extended message formatting capability. * - * @param formatter the formatter to wrap (must not be {@code null}) + * @param formatter the formatter to wrap (must not be {@code null}) * @param formatMessages {@code true} to replace message formatting, {@code false} to let the original formatter do it * @return the extended formatter (not {@code null}) */ public static ExtFormatter wrap(Formatter formatter, boolean formatMessages) { - if (formatter instanceof ExtFormatter && ! formatMessages) { + if (formatter instanceof ExtFormatter && !formatMessages) { return (ExtFormatter) formatter; } else { return new WrappedFormatter(formatter, formatMessages); @@ -112,7 +112,7 @@ public boolean isCallerCalculationRequired() { } /** - * Format the message text as if there are no parameters. The default implementation delegates to + * Format the message text as if there are no parameters. The default implementation delegates to * {@link LogRecord#getMessage() record.getMessage()}. * * @param record the record to format @@ -123,7 +123,7 @@ protected String formatMessageNone(LogRecord record) { } /** - * Format the message text as if there are no parameters. The default implementation delegates to + * Format the message text as if there are no parameters. The default implementation delegates to * {@link MessageFormat#format(String, Object[]) MessageFormat.format(record.getMessage(),record.getParameters())}. * * @param record the record to format @@ -134,7 +134,7 @@ protected String formatMessageLegacy(LogRecord record) { } /** - * Format the message text as if there are no parameters. The default implementation delegates to + * Format the message text as if there are no parameters. The default implementation delegates to * {@link String#format(String, Object[]) String.format(record.getMessage(),record.getParameters())}. * * @param record the record to format diff --git a/src/main/java/org/jboss/logmanager/ExtHandler.java b/src/main/java/org/jboss/logmanager/ExtHandler.java index 4933677d..1a679466 100644 --- a/src/main/java/org/jboss/logmanager/ExtHandler.java +++ b/src/main/java/org/jboss/logmanager/ExtHandler.java @@ -37,7 +37,7 @@ import org.jboss.logmanager.errormanager.OnlyOnceErrorManager; /** - * An extended logger handler. Use this class as a base class for log handlers which require {@code ExtLogRecord} + * An extended logger handler. Use this class as a base class for log handlers which require {@code ExtLogRecord} * instances. */ public abstract class ExtHandler extends Handler implements AutoCloseable, Flushable { @@ -60,7 +60,7 @@ public abstract class ExtHandler extends Handler implements AutoCloseable, Flush private volatile Charset charset = Charset.defaultCharset(); /** - * The sub-handlers for this handler. May only be updated using the {@link #handlersUpdater} atomic updater. The array + * The sub-handlers for this handler. May only be updated using the {@link #handlersUpdater} atomic updater. The array * instance should not be modified (treat as immutable). */ @SuppressWarnings("unused") @@ -69,7 +69,8 @@ public abstract class ExtHandler extends Handler implements AutoCloseable, Flush /** * The atomic updater for the {@link #handlers} field. */ - protected static final AtomicArray handlersUpdater = AtomicArray.create(AtomicReferenceFieldUpdater.newUpdater(ExtHandler.class, Handler[].class, "handlers"), Handler.class); + protected static final AtomicArray handlersUpdater = AtomicArray + .create(AtomicReferenceFieldUpdater.newUpdater(ExtHandler.class, Handler[].class, "handlers"), Handler.class); /** * Construct a new instance. @@ -98,12 +99,13 @@ public void publish(final LogRecord record) { * @param record the log record to publish */ public void publish(final ExtLogRecord record) { - if (enabled && record != null && isLoggable(record)) try { - doPublish(record); - } catch (Exception e) { - reportError("Handler publication threw an exception", e, ErrorManager.WRITE_FAILURE); - } catch (Throwable ignored) { - } + if (enabled && record != null && isLoggable(record)) + try { + doPublish(record); + } catch (Exception e) { + reportError("Handler publication threw an exception", e, ErrorManager.WRITE_FAILURE); + } catch (Throwable ignored) { + } } /** @@ -113,30 +115,32 @@ public void publish(final ExtLogRecord record) { */ protected void publishToNestedHandlers(final ExtLogRecord record) { if (record != null) { - for (Handler handler : getHandlers()) try { - if (handler != null) { - handler.publish(record); + for (Handler handler : getHandlers()) + try { + if (handler != null) { + handler.publish(record); + } + } catch (Exception e) { + reportError(handler, "Nested handler publication threw an exception", e, ErrorManager.WRITE_FAILURE); + } catch (Throwable ignored) { } - } catch (Exception e) { - reportError(handler, "Nested handler publication threw an exception", e, ErrorManager.WRITE_FAILURE); - } catch (Throwable ignored) { - } } } /** - * Do the actual work of publication; the record will have been filtered already. The default implementation + * Do the actual work of publication; the record will have been filtered already. The default implementation * does nothing except to flush if the {@code autoFlush} property is set to {@code true}; if this behavior is to be * preserved in a subclass then this method should be called after the record is physically written. * * @param record the log record to publish */ protected void doPublish(final ExtLogRecord record) { - if (autoFlush) flush(); + if (autoFlush) + flush(); } /** - * Add a sub-handler to this handler. Some handler types do not utilize sub-handlers. + * Add a sub-handler to this handler. Some handler types do not utilize sub-handlers. * * @param handler the handler to add * @@ -152,7 +156,7 @@ public void addHandler(Handler handler) throws SecurityException { } /** - * Remove a sub-handler from this handler. Some handler types do not utilize sub-handlers. + * Remove a sub-handler from this handler. Some handler types do not utilize sub-handlers. * * @param handler the handler to remove * @@ -168,7 +172,7 @@ public void removeHandler(Handler handler) throws SecurityException { } /** - * Get a copy of the sub-handlers array. Since the returned value is a copy, it may be freely modified. + * Get a copy of the sub-handlers array. Since the returned value is a copy, it may be freely modified. * * @return a copy of the sub-handlers array */ @@ -265,7 +269,7 @@ public final boolean isEnabled() { * Indicates whether or not children handlers should be closed when this handler is {@linkplain #close() closed}. * * @return {@code true} if the children handlers should be closed when this handler is closed, {@code false} if - * children handlers should not be closed when this handler is closed + * children handlers should not be closed when this handler is closed */ public boolean isCloseChildren() { return closeChildren; @@ -286,7 +290,8 @@ public void setCloseChildren(final boolean closeChildren) { /** * Check access. * - * @throws SecurityException if a security manager is installed and the caller does not have the {@code "control" LoggingPermission} + * @throws SecurityException if a security manager is installed and the caller does not have the + * {@code "control" LoggingPermission} */ protected static void checkAccess() throws SecurityException { final SecurityManager sm = System.getSecurityManager(); @@ -313,11 +318,13 @@ protected static void checkAccess(final ExtHandler handler) throws SecurityExcep */ @Override public void flush() { - for (Handler handler : handlers) try { - handler.flush(); - } catch (Exception ex) { - reportError("Failed to flush child handler", ex, ErrorManager.FLUSH_FAILURE); - } catch (Throwable ignored) {} + for (Handler handler : handlers) + try { + handler.flush(); + } catch (Exception ex) { + reportError("Failed to flush child handler", ex, ErrorManager.FLUSH_FAILURE); + } catch (Throwable ignored) { + } } /** @@ -371,22 +378,25 @@ public Filter getFilter() { } /** - * Set the handler's character set by name. This is roughly equivalent to calling {@link #setCharset(Charset)} with + * Set the handler's character set by name. This is roughly equivalent to calling {@link #setCharset(Charset)} with * the results of {@link Charset#forName(String)}. * * @param encoding the name of the encoding - * @throws SecurityException if a security manager is installed and the caller does not have the {@code "control" LoggingPermission} + * @throws SecurityException if a security manager is installed and the caller does not have the + * {@code "control" LoggingPermission} * @throws UnsupportedEncodingException if no character set could be found for the encoding name */ @Override public void setEncoding(final String encoding) throws SecurityException, UnsupportedEncodingException { - if (encoding != null) try { - setCharset(Charset.forName(encoding)); - } catch (IllegalArgumentException e) { - final UnsupportedEncodingException e2 = new UnsupportedEncodingException("Unable to set encoding to \"" + encoding + "\""); - e2.initCause(e); - throw e2; - } + if (encoding != null) + try { + setCharset(Charset.forName(encoding)); + } catch (IllegalArgumentException e) { + final UnsupportedEncodingException e2 = new UnsupportedEncodingException( + "Unable to set encoding to \"" + encoding + "\""); + e2.initCause(e); + throw e2; + } } /** @@ -400,11 +410,12 @@ public String getEncoding() { } /** - * Set the handler's character set. If not set, the handler's character set is initialized to the platform default + * Set the handler's character set. If not set, the handler's character set is initialized to the platform default * character set. * * @param charset the character set (must not be {@code null}) - * @throws SecurityException if a security manager is installed and the caller does not have the {@code "control" LoggingPermission} + * @throws SecurityException if a security manager is installed and the caller does not have the + * {@code "control" LoggingPermission} */ public void setCharset(final Charset charset) throws SecurityException { checkAccess(); @@ -412,7 +423,7 @@ public void setCharset(final Charset charset) throws SecurityException { } /** - * Set the handler's character set from within this handler. If not set, the handler's character set is initialized + * Set the handler's character set from within this handler. If not set, the handler's character set is initialized * to the platform default character set. * * @param charset the character set (must not be {@code null}) @@ -493,18 +504,19 @@ public boolean isCallerCalculationRequired() { Formatter formatter = getFormatter(); if (formatterRequiresCallerCalculation(formatter)) { return true; - } else for (Handler handler : getHandlers()) { - if (handler instanceof ExtHandler) { - if (((ExtHandler) handler).isCallerCalculationRequired()) { - return true; - } - } else { - formatter = handler.getFormatter(); - if (formatterRequiresCallerCalculation(formatter)) { - return true; + } else + for (Handler handler : getHandlers()) { + if (handler instanceof ExtHandler) { + if (((ExtHandler) handler).isCallerCalculationRequired()) { + return true; + } + } else { + formatter = handler.getFormatter(); + if (formatterRequiresCallerCalculation(formatter)) { + return true; + } } } - } return false; } @@ -517,24 +529,26 @@ protected void reportError(String msg, Exception ex, int code) { * Report an error using a handler's specific error manager, if any. * * @param handler the handler - * @param msg the error message - * @param ex the exception - * @param code the error code + * @param msg the error message + * @param ex the exception + * @param code the error code */ public static void reportError(Handler handler, String msg, Exception ex, int code) { if (handler != null) { ErrorManager errorManager = handler.getErrorManager(); - if (errorManager != null) try { - errorManager.error(msg, ex, code); - } catch (Exception ex2) { - // use the same message as the JDK - System.err.println("Handler.reportError caught:"); - ex2.printStackTrace(); - } + if (errorManager != null) + try { + errorManager.error(msg, ex, code); + } catch (Exception ex2) { + // use the same message as the JDK + System.err.println("Handler.reportError caught:"); + ex2.printStackTrace(); + } } } private static boolean formatterRequiresCallerCalculation(final Formatter formatter) { - return formatter != null && (!(formatter instanceof ExtFormatter) || ((ExtFormatter) formatter).isCallerCalculationRequired()); + return formatter != null + && (!(formatter instanceof ExtFormatter) || ((ExtFormatter) formatter).isCallerCalculationRequired()); } } diff --git a/src/main/java/org/jboss/logmanager/ExtLogRecord.java b/src/main/java/org/jboss/logmanager/ExtLogRecord.java index 6a3d4520..56f69684 100644 --- a/src/main/java/org/jboss/logmanager/ExtLogRecord.java +++ b/src/main/java/org/jboss/logmanager/ExtLogRecord.java @@ -19,8 +19,6 @@ package org.jboss.logmanager; -import io.smallrye.common.net.HostName; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -28,9 +26,10 @@ import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; - import java.util.logging.LogRecord; +import io.smallrye.common.net.HostName; + /** * An extended log record, which includes additional information including MDC/NDC and correct * caller location (even in the presence of a logging facade). @@ -59,10 +58,10 @@ public enum FormatStyle { } /** - * Construct a new instance. Grabs the current NDC immediately. MDC is deferred. + * Construct a new instance. Grabs the current NDC immediately. MDC is deferred. * - * @param level a logging level value - * @param msg the raw non-localized logging message (may be null) + * @param level a logging level value + * @param msg the raw non-localized logging message (may be null) * @param loggerClassName the name of the logger class */ public ExtLogRecord(final java.util.logging.Level level, final String msg, final String loggerClassName) { @@ -70,14 +69,15 @@ public ExtLogRecord(final java.util.logging.Level level, final String msg, final } /** - * Construct a new instance. Grabs the current NDC immediately. MDC is deferred. + * Construct a new instance. Grabs the current NDC immediately. MDC is deferred. * - * @param level a logging level value - * @param msg the raw non-localized logging message (may be null) - * @param formatStyle the parameter format style to use + * @param level a logging level value + * @param msg the raw non-localized logging message (may be null) + * @param formatStyle the parameter format style to use * @param loggerClassName the name of the logger class */ - public ExtLogRecord(final java.util.logging.Level level, final String msg, final FormatStyle formatStyle, final String loggerClassName) { + public ExtLogRecord(final java.util.logging.Level level, final String msg, final FormatStyle formatStyle, + final String loggerClassName) { super(level, msg); this.formatStyle = formatStyle == null ? FormatStyle.MESSAGE_FORMAT : formatStyle; this.loggerClassName = loggerClassName; @@ -124,7 +124,7 @@ public ExtLogRecord(final ExtLogRecord original) { } /** - * Wrap a JDK log record. If the target record is already an {@code ExtLogRecord}, it is simply returned. Otherwise + * Wrap a JDK log record. If the target record is already an {@code ExtLogRecord}, it is simply returned. Otherwise * a wrapper record is created and returned. * * @param rec the original record @@ -179,7 +179,7 @@ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFound } /** - * Disable caller calculation for this record. If the caller has already been calculated, leave it; otherwise + * Disable caller calculation for this record. If the caller has already been calculated, leave it; otherwise * set the caller to {@code "unknown"}. */ public void disableCallerCalculation() { @@ -189,7 +189,7 @@ public void disableCallerCalculation() { } /** - * Copy all fields and prepare this object to be passed to another thread or to be serialized. Calling this method + * Copy all fields and prepare this object to be passed to another thread or to be serialized. Calling this method * more than once has no additional effect and will not incur extra copies. */ public void copyAll() { @@ -198,7 +198,7 @@ public void copyAll() { } /** - * Copy the MDC. Call this method before passing this log record to another thread. Calling this method + * Copy the MDC. Call this method before passing this log record to another thread. Calling this method * more than once has no additional effect and will not incur extra copies. */ public void copyMdc() { @@ -218,12 +218,12 @@ public String getMdc(String key) { if (mdcCopy == null) { return MDC.get(key); } - final Object value = mdcCopy.get(key); + final Object value = mdcCopy.get(key); return value == null ? null : value.toString(); } /** - * Get a copy of all the MDC properties for this log record. If the MDC has not yet been copied, this method will copy it. + * Get a copy of all the MDC properties for this log record. If the MDC has not yet been copied, this method will copy it. * * @return a copy of the MDC map */ @@ -240,9 +240,9 @@ public Map getMdcCopy() { } /** - * Change an MDC value on this record. If the MDC has not yet been copied, this method will copy it. + * Change an MDC value on this record. If the MDC has not yet been copied, this method will copy it. * - * @param key the key to set + * @param key the key to set * @param value the value to set it to * @return the old value, if any */ @@ -253,7 +253,7 @@ public String putMdc(String key, String value) { } /** - * Remove an MDC value on this record. If the MDC has not yet been copied, this method will copy it. + * Remove an MDC value on this record. If the MDC has not yet been copied, this method will copy it. * * @param key the key to remove * @return the old value, if any @@ -321,7 +321,7 @@ public FormatStyle getFormatStyle() { * Find the first stack frame below the call to the logger, and populate the log record with that information. */ private void calculateCaller() { - if (! calculateCaller) { + if (!calculateCaller) { return; } calculateCaller = false; @@ -487,14 +487,16 @@ public String getFormattedMessage() { } /** - * Get the resource key, if any. If the log message is not localized, then the key is {@code null}. + * Get the resource key, if any. If the log message is not localized, then the key is {@code null}. * * @return the resource key */ public String getResourceKey() { final String msg = getMessage(); - if (msg == null) return null; - if (getResourceBundleName() == null && getResourceBundle() == null) return null; + if (msg == null) + return null; + if (getResourceBundleName() == null && getResourceBundle() == null) + return null; return msg; } @@ -571,7 +573,7 @@ public void setProcessId(final long processId) { } /** - * Set the raw message. Any cached formatted message is discarded. The parameter format is set to be + * Set the raw message. Any cached formatted message is discarded. The parameter format is set to be * {@link java.text.MessageFormat}-style. * * @param message the new raw message @@ -581,10 +583,10 @@ public void setMessage(final String message) { } /** - * Set the raw message. Any cached formatted message is discarded. The parameter format is set according to the + * Set the raw message. Any cached formatted message is discarded. The parameter format is set according to the * given argument. * - * @param message the new raw message + * @param message the new raw message * @param formatStyle the format style to use */ public void setMessage(final String message, final FormatStyle formatStyle) { @@ -593,7 +595,7 @@ public void setMessage(final String message, final FormatStyle formatStyle) { } /** - * Set the parameters to the log message. Any cached formatted message is discarded. + * Set the parameters to the log message. Any cached formatted message is discarded. * * @param parameters the log message parameters. (may be null) */ @@ -602,7 +604,7 @@ public void setParameters(final Object[] parameters) { } /** - * Set the localization resource bundle. Any cached formatted message is discarded. + * Set the localization resource bundle. Any cached formatted message is discarded. * * @param bundle localization bundle (may be null) */ @@ -611,7 +613,7 @@ public void setResourceBundle(final ResourceBundle bundle) { } /** - * Set the localization resource bundle name. Any cached formatted message is discarded. + * Set the localization resource bundle name. Any cached formatted message is discarded. * * @param name localization bundle name (may be null) */ diff --git a/src/main/java/org/jboss/logmanager/FastCopyHashMap.java b/src/main/java/org/jboss/logmanager/FastCopyHashMap.java index f2e3aaf2..6ffb39ac 100644 --- a/src/main/java/org/jboss/logmanager/FastCopyHashMap.java +++ b/src/main/java/org/jboss/logmanager/FastCopyHashMap.java @@ -44,817 +44,715 @@ * * @author Jason T. Greene */ -class FastCopyHashMap extends AbstractMap implements Map, Cloneable, Serializable -{ - /** - * Marks null keys. - */ - private static final Object NULL = new Object(); - - /** - * Serialization ID - */ - private static final long serialVersionUID = 10929568968762L; - - /** - * Same default as HashMap, must be a power of 2 - */ - private static final int DEFAULT_CAPACITY = 8; - - /** - * MAX_INT - 1 - */ - private static final int MAXIMUM_CAPACITY = 1 << 30; - - /** - * 67%, just like IdentityHashMap - */ - private static final float DEFAULT_LOAD_FACTOR = 0.67f; - - /** - * The open-addressed table - */ - private transient Entry[] table; - - /** - * The current number of key-value pairs - */ - private transient int size; - - /** - * The next resize - */ - private transient int threshold; - - /** - * The user defined load factor which defines when to resize - */ - private final float loadFactor; - - /** - * Counter used to detect changes made outside of an iterator - */ - private transient int modCount; - - // Cached views - private transient KeySet keySet; - private transient Values values; - private transient EntrySet entrySet; - - public FastCopyHashMap(int initialCapacity, float loadFactor) - { - if (initialCapacity < 0) - throw new IllegalArgumentException("Can not have a negative size table!"); - - if (initialCapacity > MAXIMUM_CAPACITY) - initialCapacity = MAXIMUM_CAPACITY; - - if (!(loadFactor > 0F && loadFactor <= 1F)) - throw new IllegalArgumentException("Load factor must be greater than 0 and less than or equal to 1"); - - this.loadFactor = loadFactor; - init(initialCapacity, loadFactor); - } - - @SuppressWarnings("unchecked") - public FastCopyHashMap(Map map) - { - if (map instanceof FastCopyHashMap) - { - FastCopyHashMap fast = (FastCopyHashMap) map; - this.table = (Entry[]) fast.table.clone(); - this.loadFactor = fast.loadFactor; - this.size = fast.size; - this.threshold = fast.threshold; - } - else - { - this.loadFactor = DEFAULT_LOAD_FACTOR; - init(map.size(), this.loadFactor); - putAll(map); - } - } - - @SuppressWarnings("unchecked") - private void init(int initialCapacity, float loadFactor) - { - int c = 1; - for (; c < initialCapacity; c <<= 1) ; - threshold = (int) (c * loadFactor); - - // Include the load factor when sizing the table for the first time - if (initialCapacity > threshold && c < MAXIMUM_CAPACITY) - { - c <<= 1; - threshold = (int) (c * loadFactor); - } - - this.table = (Entry[]) new Entry[c]; - } - - public FastCopyHashMap(int initialCapacity) - { - this(initialCapacity, DEFAULT_LOAD_FACTOR); - } - - public FastCopyHashMap() - { - this(DEFAULT_CAPACITY); - } - - // The normal bit spreader... - private static final int hash(Object key) - { - int h = key.hashCode(); - h ^= (h >>> 20) ^ (h >>> 12); - return h ^ (h >>> 7) ^ (h >>> 4); - } - - @SuppressWarnings("unchecked") - private static final K maskNull(K key) - { - return key == null ? (K) NULL : key; - } - - private static final K unmaskNull(K key) - { - return key == NULL ? null : key; - } - - private int nextIndex(int index, int length) - { - index = (index >= length - 1) ? 0 : index + 1; - return index; - } - - private static final boolean eq(Object o1, Object o2) - { - return o1 == o2 || (o1 != null && o1.equals(o2)); - } - - private static final int index(int hashCode, int length) - { - return hashCode & (length - 1); - } - - public int size() - { - return size; - } - - public boolean isEmpty() - { - return size == 0; - } - - public V get(Object key) - { - key = maskNull(key); - - int hash = hash(key); - int length = table.length; - int index = index(hash, length); - - for (int start = index; ;) - { - Entry e = table[index]; - if (e == null) - return null; - - if (e.hash == hash && eq(key, e.key)) - return e.value; - - index = nextIndex(index, length); - if (index == start) // Full table - return null; - } - } - - public boolean containsKey(Object key) - { - key = maskNull(key); - - int hash = hash(key); - int length = table.length; - int index = index(hash, length); - - for (int start = index; ;) - { - Entry e = table[index]; - if (e == null) - return false; +class FastCopyHashMap extends AbstractMap implements Map, Cloneable, Serializable { + /** + * Marks null keys. + */ + private static final Object NULL = new Object(); + + /** + * Serialization ID + */ + private static final long serialVersionUID = 10929568968762L; + + /** + * Same default as HashMap, must be a power of 2 + */ + private static final int DEFAULT_CAPACITY = 8; + + /** + * MAX_INT - 1 + */ + private static final int MAXIMUM_CAPACITY = 1 << 30; + + /** + * 67%, just like IdentityHashMap + */ + private static final float DEFAULT_LOAD_FACTOR = 0.67f; + + /** + * The open-addressed table + */ + private transient Entry[] table; + + /** + * The current number of key-value pairs + */ + private transient int size; + + /** + * The next resize + */ + private transient int threshold; + + /** + * The user defined load factor which defines when to resize + */ + private final float loadFactor; + + /** + * Counter used to detect changes made outside of an iterator + */ + private transient int modCount; + + // Cached views + private transient KeySet keySet; + private transient Values values; + private transient EntrySet entrySet; + + public FastCopyHashMap(int initialCapacity, float loadFactor) { + if (initialCapacity < 0) + throw new IllegalArgumentException("Can not have a negative size table!"); + + if (initialCapacity > MAXIMUM_CAPACITY) + initialCapacity = MAXIMUM_CAPACITY; + + if (!(loadFactor > 0F && loadFactor <= 1F)) + throw new IllegalArgumentException("Load factor must be greater than 0 and less than or equal to 1"); + + this.loadFactor = loadFactor; + init(initialCapacity, loadFactor); + } + + @SuppressWarnings("unchecked") + public FastCopyHashMap(Map map) { + if (map instanceof FastCopyHashMap) { + FastCopyHashMap fast = (FastCopyHashMap) map; + this.table = (Entry[]) fast.table.clone(); + this.loadFactor = fast.loadFactor; + this.size = fast.size; + this.threshold = fast.threshold; + } else { + this.loadFactor = DEFAULT_LOAD_FACTOR; + init(map.size(), this.loadFactor); + putAll(map); + } + } + + @SuppressWarnings("unchecked") + private void init(int initialCapacity, float loadFactor) { + int c = 1; + for (; c < initialCapacity; c <<= 1) + ; + threshold = (int) (c * loadFactor); + + // Include the load factor when sizing the table for the first time + if (initialCapacity > threshold && c < MAXIMUM_CAPACITY) { + c <<= 1; + threshold = (int) (c * loadFactor); + } + + this.table = (Entry[]) new Entry[c]; + } + + public FastCopyHashMap(int initialCapacity) { + this(initialCapacity, DEFAULT_LOAD_FACTOR); + } + + public FastCopyHashMap() { + this(DEFAULT_CAPACITY); + } + + // The normal bit spreader... + private static final int hash(Object key) { + int h = key.hashCode(); + h ^= (h >>> 20) ^ (h >>> 12); + return h ^ (h >>> 7) ^ (h >>> 4); + } + + @SuppressWarnings("unchecked") + private static final K maskNull(K key) { + return key == null ? (K) NULL : key; + } + + private static final K unmaskNull(K key) { + return key == NULL ? null : key; + } + + private int nextIndex(int index, int length) { + index = (index >= length - 1) ? 0 : index + 1; + return index; + } + + private static final boolean eq(Object o1, Object o2) { + return o1 == o2 || (o1 != null && o1.equals(o2)); + } + + private static final int index(int hashCode, int length) { + return hashCode & (length - 1); + } + + public int size() { + return size; + } + + public boolean isEmpty() { + return size == 0; + } + + public V get(Object key) { + key = maskNull(key); + + int hash = hash(key); + int length = table.length; + int index = index(hash, length); + + for (int start = index;;) { + Entry e = table[index]; + if (e == null) + return null; - if (e.hash == hash && eq(key, e.key)) - return true; + if (e.hash == hash && eq(key, e.key)) + return e.value; - index = nextIndex(index, length); - if (index == start) // Full table - return false; - } - } - - public boolean containsValue(Object value) - { - for (Entry e : table) - if (e != null && eq(value, e.value)) - return true; - - return false; - } - - public V put(K key, V value) - { - key = maskNull(key); - - Entry[] table = this.table; - int hash = hash(key); - int length = table.length; - int index = index(hash, length); - - for (int start = index; ;) - { - Entry e = table[index]; - if (e == null) - break; - - if (e.hash == hash && eq(key, e.key)) - { - table[index] = new Entry(e.key, e.hash, value); - return e.value; - } - - index = nextIndex(index, length); - if (index == start) - throw new IllegalStateException("Table is full!"); - } - - modCount++; - table[index] = new Entry(key, hash, value); - if (++size >= threshold) - resize(length); - - return null; - } - - - @SuppressWarnings("unchecked") - private void resize(int from) - { - int newLength = from << 1; - - // Can't get any bigger - if (newLength > MAXIMUM_CAPACITY || newLength <= from) - return; - - Entry[] newTable = new Entry[newLength]; - Entry[] old = table; - - for (Entry e : old) - { - if (e == null) - continue; - - int index = index(e.hash, newLength); - while (newTable[index] != null) - index = nextIndex(index, newLength); - - newTable[index] = e; - } - - threshold = (int) (loadFactor * newLength); - table = newTable; - } - - public void putAll(Map map) - { - int size = map.size(); - if (size == 0) - return; - - if (size > threshold) - { - if (size > MAXIMUM_CAPACITY) - size = MAXIMUM_CAPACITY; - - int length = table.length; - for (; length < size; length <<= 1) ; - - resize(length); - } - - for (Map.Entry e : map.entrySet()) - put(e.getKey(), e.getValue()); - } - - public V remove(Object key) - { - key = maskNull(key); - - Entry[] table = this.table; - int length = table.length; - int hash = hash(key); - int start = index(hash, length); - - for (int index = start; ;) - { - Entry e = table[index]; - if (e == null) - return null; - - if (e.hash == hash && eq(key, e.key)) - { - table[index] = null; - relocate(index); - modCount++; - size--; - return e.value; - } + index = nextIndex(index, length); + if (index == start) // Full table + return null; + } + } - index = nextIndex(index, length); - if (index == start) - return null; - } + public boolean containsKey(Object key) { + key = maskNull(key); + int hash = hash(key); + int length = table.length; + int index = index(hash, length); - } + for (int start = index;;) { + Entry e = table[index]; + if (e == null) + return false; - private void relocate(int start) - { - Entry[] table = this.table; - int length = table.length; - int current = nextIndex(start, length); + if (e.hash == hash && eq(key, e.key)) + return true; - for (; ;) - { - Entry e = table[current]; - if (e == null) - return; + index = nextIndex(index, length); + if (index == start) // Full table + return false; + } + } - // A Doug Lea variant of Knuth's Section 6.4 Algorithm R. - // This provides a non-recursive method of relocating - // entries to their optimal positions once a gap is created. - int prefer = index(e.hash, length); - if ((current < prefer && (prefer <= start || start <= current)) - || (prefer <= start && start <= current)) - { - table[start] = e; - table[current] = null; - start = current; - } - - current = nextIndex(current, length); - } - } - - public void clear() - { - modCount++; - Entry[] table = this.table; - for (int i = 0; i < table.length; i++) - table[i] = null; - - size = 0; - } - - @SuppressWarnings("unchecked") - public FastCopyHashMap clone() - { - try - { - FastCopyHashMap clone = (FastCopyHashMap) super.clone(); - clone.table = table.clone(); - clone.entrySet = null; - clone.values = null; - clone.keySet = null; - return clone; - } - catch (CloneNotSupportedException e) - { - // should never happen - throw new IllegalStateException(e); - } - } - - public void printDebugStats() - { - int optimal = 0; - int total = 0; - int totalSkew = 0; - int maxSkew = 0; - for (int i = 0; i < table.length; i++) - { - Entry e = table[i]; - if (e != null) - { - - total++; - int target = index(e.hash, table.length); - if (i == target) - optimal++; - else - { - int skew = Math.abs(i - target); - if (skew > maxSkew) maxSkew = skew; - totalSkew += skew; - } + public boolean containsValue(Object value) { + for (Entry e : table) + if (e != null && eq(value, e.value)) + return true; - } - } - - System.out.println(" Size: " + size); - System.out.println(" Real Size: " + total); - System.out.println(" Optimal: " + optimal + " (" + (float) optimal * 100 / total + "%)"); - System.out.println(" Average Distance:" + ((float) totalSkew / (total - optimal))); - System.out.println(" Max Distance: " + maxSkew); - } - - public Set> entrySet() - { - if (entrySet == null) - entrySet = new EntrySet(); - - return entrySet; - } - - public Set keySet() - { - if (keySet == null) - keySet = new KeySet(); - - return keySet; - } - - public Collection values() - { - if (values == null) - values = new Values(); - - return values; - } - - public static FastCopyHashMap of(Map map) { - if (map instanceof FastCopyHashMap) { - return (FastCopyHashMap) map; - } else { - return new FastCopyHashMap<>(map); - } - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException - { - s.defaultReadObject(); - - int size = s.readInt(); - - init(size, loadFactor); - - for (int i = 0; i < size; i++) - { - K key = (K) s.readObject(); - V value = (V) s.readObject(); - putForCreate(key, value); - } - - this.size = size; - } - - @SuppressWarnings("unchecked") - private void putForCreate(K key, V value) - { - key = maskNull(key); - - Entry[] table = this.table; - int hash = hash(key); - int length = table.length; - int index = index(hash, length); - - Entry e = table[index]; - while (e != null) - { - index = nextIndex(index, length); - e = table[index]; - } - - table[index] = new Entry(key, hash, value); - } - - private void writeObject(java.io.ObjectOutputStream s) throws IOException - { - s.defaultWriteObject(); - s.writeInt(size); - - for (Entry e : table) - { - if (e != null) - { - s.writeObject(unmaskNull(e.key)); - s.writeObject(e.value); - } - } - } - - private static final class Entry - { - final K key; - final int hash; - final V value; - - Entry(K key, int hash, V value) - { - this.key = key; - this.hash = hash; - this.value = value; - } - } - - private abstract class FastCopyHashMapIterator implements Iterator - { - private int next = 0; - private int expectedCount = modCount; - private int current = -1; - private boolean hasNext; - Entry table[] = FastCopyHashMap.this.table; - - public boolean hasNext() - { - if (hasNext == true) - return true; - - Entry table[] = this.table; - for (int i = next; i < table.length; i++) - { - if (table[i] != null) - { - next = i; - return hasNext = true; + return false; + } + + public V put(K key, V value) { + key = maskNull(key); + + Entry[] table = this.table; + int hash = hash(key); + int length = table.length; + int index = index(hash, length); + + for (int start = index;;) { + Entry e = table[index]; + if (e == null) + break; + + if (e.hash == hash && eq(key, e.key)) { + table[index] = new Entry(e.key, e.hash, value); + return e.value; } - } - next = table.length; - return false; - } + index = nextIndex(index, length); + if (index == start) + throw new IllegalStateException("Table is full!"); + } - protected Entry nextEntry() - { - if (modCount != expectedCount) - throw new ConcurrentModificationException(); + modCount++; + table[index] = new Entry(key, hash, value); + if (++size >= threshold) + resize(length); - if (!hasNext && !hasNext()) - throw new NoSuchElementException(); + return null; + } - current = next++; - hasNext = false; + @SuppressWarnings("unchecked") + private void resize(int from) { + int newLength = from << 1; - return table[current]; - } + // Can't get any bigger + if (newLength > MAXIMUM_CAPACITY || newLength <= from) + return; - @SuppressWarnings("unchecked") - public void remove() - { - if (modCount != expectedCount) - throw new ConcurrentModificationException(); + Entry[] newTable = new Entry[newLength]; + Entry[] old = table; - int current = this.current; - int delete = current; + for (Entry e : old) { + if (e == null) + continue; - if (current == -1) - throw new IllegalStateException(); + int index = index(e.hash, newLength); + while (newTable[index] != null) + index = nextIndex(index, newLength); - // Invalidate current (prevents multiple remove) - this.current = -1; + newTable[index] = e; + } - // Start were we relocate - next = delete; + threshold = (int) (loadFactor * newLength); + table = newTable; + } - Entry[] table = this.table; - if (table != FastCopyHashMap.this.table) - { - FastCopyHashMap.this.remove(table[delete].key); - table[delete] = null; - expectedCount = modCount; + public void putAll(Map map) { + int size = map.size(); + if (size == 0) return; - } + if (size > threshold) { + if (size > MAXIMUM_CAPACITY) + size = MAXIMUM_CAPACITY; - int length = table.length; - int i = delete; + int length = table.length; + for (; length < size; length <<= 1) + ; - table[delete] = null; - size--; + resize(length); + } - for (; ;) - { - i = nextIndex(i, length); - Entry e = table[i]; + for (Map.Entry e : map.entrySet()) + put(e.getKey(), e.getValue()); + } + + public V remove(Object key) { + key = maskNull(key); + + Entry[] table = this.table; + int length = table.length; + int hash = hash(key); + int start = index(hash, length); + + for (int index = start;;) { + Entry e = table[index]; if (e == null) - break; + return null; + + if (e.hash == hash && eq(key, e.key)) { + table[index] = null; + relocate(index); + modCount++; + size--; + return e.value; + } + + index = nextIndex(index, length); + if (index == start) + return null; + } + } + + private void relocate(int start) { + Entry[] table = this.table; + int length = table.length; + int current = nextIndex(start, length); + + for (;;) { + Entry e = table[current]; + if (e == null) + return; + + // A Doug Lea variant of Knuth's Section 6.4 Algorithm R. + // This provides a non-recursive method of relocating + // entries to their optimal positions once a gap is created. int prefer = index(e.hash, length); - if ((i < prefer && (prefer <= delete || delete <= i)) - || (prefer <= delete && delete <= i)) - { - // Snapshot the unseen portion of the table if we have - // to relocate an entry that was already seen by this iterator - if (i < current && current <= delete && table == FastCopyHashMap.this.table) - { - int remaining = length - current; - Entry[] newTable = (Entry[]) new Entry[remaining]; - System.arraycopy(table, current, newTable, 0, remaining); - - // Replace iterator's table. - // Leave table local var pointing to the real table - this.table = newTable; - next = 0; - } - - // Do the swap on the real table - table[delete] = e; - table[i] = null; - delete = i; + if ((current < prefer && (prefer <= start || start <= current)) + || (prefer <= start && start <= current)) { + table[start] = e; + table[current] = null; + start = current; } - } - } - } - - - private class KeyIterator extends FastCopyHashMapIterator - { - public K next() - { - return unmaskNull(nextEntry().key); - } - } - - private class ValueIterator extends FastCopyHashMapIterator - { - public V next() - { - return nextEntry().value; - } - } - - private class EntryIterator extends FastCopyHashMapIterator> - { - private class WriteThroughEntry extends SimpleEntry - { - WriteThroughEntry(K key, V value) - { - super(key, value); - } - - public V setValue(V value) - { - if (table != FastCopyHashMap.this.table) - FastCopyHashMap.this.put(getKey(), value); - - return super.setValue(value); - } - } - - public Map.Entry next() - { - Entry e = nextEntry(); - return new WriteThroughEntry(unmaskNull(e.key), e.value); - } - - } - - private class KeySet extends AbstractSet - { - public Iterator iterator() - { - return new KeyIterator(); - } - - public void clear() - { - FastCopyHashMap.this.clear(); - } - - public boolean contains(Object o) - { - return containsKey(o); - } - - public boolean remove(Object o) - { - int size = size(); - FastCopyHashMap.this.remove(o); - return size() < size; - } - - public int size() - { - return FastCopyHashMap.this.size(); - } - } - - private class Values extends AbstractCollection - { - public Iterator iterator() - { - return new ValueIterator(); - } - - public void clear() - { - FastCopyHashMap.this.clear(); - } - - public int size() - { - return FastCopyHashMap.this.size(); - } - } - - private class EntrySet extends AbstractSet> - { - public Iterator> iterator() - { - return new EntryIterator(); - } - - public boolean contains(Object o) - { - if (!(o instanceof Map.Entry)) - return false; - Map.Entry entry = (Map.Entry) o; - Object value = get(entry.getKey()); - return eq(entry.getValue(), value); - } - - public void clear() - { - FastCopyHashMap.this.clear(); - } - - public boolean isEmpty() - { - return FastCopyHashMap.this.isEmpty(); - } - - public int size() - { - return FastCopyHashMap.this.size(); - } - } - - protected static class SimpleEntry implements Map.Entry - { - private K key; - private V value; - - SimpleEntry(K key, V value) - { - this.key = key; - this.value = value; - } - - SimpleEntry(Map.Entry entry) - { - this.key = entry.getKey(); - this.value = entry.getValue(); - } - - public K getKey() - { - return key; - } - - public V getValue() - { - return value; - } - - public V setValue(V value) - { - V old = this.value; - this.value = value; - return old; - } - - public boolean equals(Object o) - { - if (this == o) - return true; - - if (!(o instanceof Map.Entry)) + current = nextIndex(current, length); + } + } + + public void clear() { + modCount++; + Entry[] table = this.table; + for (int i = 0; i < table.length; i++) + table[i] = null; + + size = 0; + } + + @SuppressWarnings("unchecked") + public FastCopyHashMap clone() { + try { + FastCopyHashMap clone = (FastCopyHashMap) super.clone(); + clone.table = table.clone(); + clone.entrySet = null; + clone.values = null; + clone.keySet = null; + return clone; + } catch (CloneNotSupportedException e) { + // should never happen + throw new IllegalStateException(e); + } + } + + public void printDebugStats() { + int optimal = 0; + int total = 0; + int totalSkew = 0; + int maxSkew = 0; + for (int i = 0; i < table.length; i++) { + Entry e = table[i]; + if (e != null) { + + total++; + int target = index(e.hash, table.length); + if (i == target) + optimal++; + else { + int skew = Math.abs(i - target); + if (skew > maxSkew) + maxSkew = skew; + totalSkew += skew; + } + + } + } + + System.out.println(" Size: " + size); + System.out.println(" Real Size: " + total); + System.out.println(" Optimal: " + optimal + " (" + (float) optimal * 100 / total + "%)"); + System.out.println(" Average Distance:" + ((float) totalSkew / (total - optimal))); + System.out.println(" Max Distance: " + maxSkew); + } + + public Set> entrySet() { + if (entrySet == null) + entrySet = new EntrySet(); + + return entrySet; + } + + public Set keySet() { + if (keySet == null) + keySet = new KeySet(); + + return keySet; + } + + public Collection values() { + if (values == null) + values = new Values(); + + return values; + } + + public static FastCopyHashMap of(Map map) { + if (map instanceof FastCopyHashMap) { + return (FastCopyHashMap) map; + } else { + return new FastCopyHashMap<>(map); + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { + s.defaultReadObject(); + + int size = s.readInt(); + + init(size, loadFactor); + + for (int i = 0; i < size; i++) { + K key = (K) s.readObject(); + V value = (V) s.readObject(); + putForCreate(key, value); + } + + this.size = size; + } + + @SuppressWarnings("unchecked") + private void putForCreate(K key, V value) { + key = maskNull(key); + + Entry[] table = this.table; + int hash = hash(key); + int length = table.length; + int index = index(hash, length); + + Entry e = table[index]; + while (e != null) { + index = nextIndex(index, length); + e = table[index]; + } + + table[index] = new Entry(key, hash, value); + } + + private void writeObject(java.io.ObjectOutputStream s) throws IOException { + s.defaultWriteObject(); + s.writeInt(size); + + for (Entry e : table) { + if (e != null) { + s.writeObject(unmaskNull(e.key)); + s.writeObject(e.value); + } + } + } + + private static final class Entry { + final K key; + final int hash; + final V value; + + Entry(K key, int hash, V value) { + this.key = key; + this.hash = hash; + this.value = value; + } + } + + private abstract class FastCopyHashMapIterator implements Iterator { + private int next = 0; + private int expectedCount = modCount; + private int current = -1; + private boolean hasNext; + Entry table[] = FastCopyHashMap.this.table; + + public boolean hasNext() { + if (hasNext == true) + return true; + + Entry table[] = this.table; + for (int i = next; i < table.length; i++) { + if (table[i] != null) { + next = i; + return hasNext = true; + } + } + + next = table.length; return false; - Map.Entry e = (Map.Entry) o; - return eq(key, e.getKey()) && eq(value, e.getValue()); - } - - public int hashCode() - { - return (key == null ? 0 : hash(key)) ^ - (value == null ? 0 : hash(value)); - } - - public String toString() - { - return getKey() + "=" + getValue(); - } - } + } + + protected Entry nextEntry() { + if (modCount != expectedCount) + throw new ConcurrentModificationException(); + + if (!hasNext && !hasNext()) + throw new NoSuchElementException(); + + current = next++; + hasNext = false; + + return table[current]; + } + + @SuppressWarnings("unchecked") + public void remove() { + if (modCount != expectedCount) + throw new ConcurrentModificationException(); + + int current = this.current; + int delete = current; + + if (current == -1) + throw new IllegalStateException(); + + // Invalidate current (prevents multiple remove) + this.current = -1; + + // Start were we relocate + next = delete; + + Entry[] table = this.table; + if (table != FastCopyHashMap.this.table) { + FastCopyHashMap.this.remove(table[delete].key); + table[delete] = null; + expectedCount = modCount; + return; + } + + int length = table.length; + int i = delete; + + table[delete] = null; + size--; + + for (;;) { + i = nextIndex(i, length); + Entry e = table[i]; + if (e == null) + break; + + int prefer = index(e.hash, length); + if ((i < prefer && (prefer <= delete || delete <= i)) + || (prefer <= delete && delete <= i)) { + // Snapshot the unseen portion of the table if we have + // to relocate an entry that was already seen by this iterator + if (i < current && current <= delete && table == FastCopyHashMap.this.table) { + int remaining = length - current; + Entry[] newTable = (Entry[]) new Entry[remaining]; + System.arraycopy(table, current, newTable, 0, remaining); + + // Replace iterator's table. + // Leave table local var pointing to the real table + this.table = newTable; + next = 0; + } + + // Do the swap on the real table + table[delete] = e; + table[i] = null; + delete = i; + } + } + } + } + + private class KeyIterator extends FastCopyHashMapIterator { + public K next() { + return unmaskNull(nextEntry().key); + } + } + + private class ValueIterator extends FastCopyHashMapIterator { + public V next() { + return nextEntry().value; + } + } + + private class EntryIterator extends FastCopyHashMapIterator> { + private class WriteThroughEntry extends SimpleEntry { + WriteThroughEntry(K key, V value) { + super(key, value); + } + + public V setValue(V value) { + if (table != FastCopyHashMap.this.table) + FastCopyHashMap.this.put(getKey(), value); + + return super.setValue(value); + } + } + + public Map.Entry next() { + Entry e = nextEntry(); + return new WriteThroughEntry(unmaskNull(e.key), e.value); + } + + } + + private class KeySet extends AbstractSet { + public Iterator iterator() { + return new KeyIterator(); + } + + public void clear() { + FastCopyHashMap.this.clear(); + } + + public boolean contains(Object o) { + return containsKey(o); + } + + public boolean remove(Object o) { + int size = size(); + FastCopyHashMap.this.remove(o); + return size() < size; + } + + public int size() { + return FastCopyHashMap.this.size(); + } + } + + private class Values extends AbstractCollection { + public Iterator iterator() { + return new ValueIterator(); + } + + public void clear() { + FastCopyHashMap.this.clear(); + } + + public int size() { + return FastCopyHashMap.this.size(); + } + } + + private class EntrySet extends AbstractSet> { + public Iterator> iterator() { + return new EntryIterator(); + } + + public boolean contains(Object o) { + if (!(o instanceof Map.Entry)) + return false; + + Map.Entry entry = (Map.Entry) o; + Object value = get(entry.getKey()); + return eq(entry.getValue(), value); + } + + public void clear() { + FastCopyHashMap.this.clear(); + } + + public boolean isEmpty() { + return FastCopyHashMap.this.isEmpty(); + } + + public int size() { + return FastCopyHashMap.this.size(); + } + } + + protected static class SimpleEntry implements Map.Entry { + private K key; + private V value; + + SimpleEntry(K key, V value) { + this.key = key; + this.value = value; + } + + SimpleEntry(Map.Entry entry) { + this.key = entry.getKey(); + this.value = entry.getValue(); + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + + public V setValue(V value) { + V old = this.value; + this.value = value; + return old; + } + + public boolean equals(Object o) { + if (this == o) + return true; + + if (!(o instanceof Map.Entry)) + return false; + Map.Entry e = (Map.Entry) o; + return eq(key, e.getKey()) && eq(value, e.getValue()); + } + + public int hashCode() { + return (key == null ? 0 : hash(key)) ^ + (value == null ? 0 : hash(value)); + } + + public String toString() { + return getKey() + "=" + getValue(); + } + } } diff --git a/src/main/java/org/jboss/logmanager/JBossLoggerFinder.java b/src/main/java/org/jboss/logmanager/JBossLoggerFinder.java index 3aafe458..0d769384 100644 --- a/src/main/java/org/jboss/logmanager/JBossLoggerFinder.java +++ b/src/main/java/org/jboss/logmanager/JBossLoggerFinder.java @@ -32,7 +32,7 @@ * * @author James R. Perkins */ -public class JBossLoggerFinder extends System.LoggerFinder { +public class JBossLoggerFinder extends System.LoggerFinder { private static final Map LEVELS = new EnumMap<>(System.Logger.Level.class); private static final AtomicBoolean LOGGED = new AtomicBoolean(false); private static volatile boolean PROPERTY_SET = false; @@ -71,7 +71,8 @@ public System.Logger getLogger(final String name, final Module module) { final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name); if (!logger.getClass().getName().equals("org.jboss.logmanager.Logger")) { if (LOGGED.compareAndSet(false, true)) { - logger.log(Level.ERROR, "The LogManager accessed before the \"java.util.logging.manager\" system property was set to \"org.jboss.logmanager.LogManager\". Results may be unexpected."); + logger.log(Level.ERROR, + "The LogManager accessed before the \"java.util.logging.manager\" system property was set to \"org.jboss.logmanager.LogManager\". Results may be unexpected."); } } return new JBossSystemLogger(logger); @@ -97,7 +98,8 @@ public boolean isLoggable(final Level level) { @Override public void log(final Level level, final ResourceBundle bundle, final String msg, final Throwable thrown) { - final ExtLogRecord record = new ExtLogRecord(LEVELS.getOrDefault(level, java.util.logging.Level.INFO), msg, LOGGER_CLASS_NAME); + final ExtLogRecord record = new ExtLogRecord(LEVELS.getOrDefault(level, java.util.logging.Level.INFO), msg, + LOGGER_CLASS_NAME); record.setThrown(thrown); record.setResourceBundle(bundle); delegate.log(record); @@ -105,7 +107,8 @@ public void log(final Level level, final ResourceBundle bundle, final String msg @Override public void log(final Level level, final ResourceBundle bundle, final String format, final Object... params) { - final ExtLogRecord record = new ExtLogRecord(LEVELS.getOrDefault(level, java.util.logging.Level.INFO), format, ExtLogRecord.FormatStyle.MESSAGE_FORMAT, LOGGER_CLASS_NAME); + final ExtLogRecord record = new ExtLogRecord(LEVELS.getOrDefault(level, java.util.logging.Level.INFO), format, + ExtLogRecord.FormatStyle.MESSAGE_FORMAT, LOGGER_CLASS_NAME); record.setParameters(params); record.setResourceBundle(bundle); delegate.log(record); diff --git a/src/main/java/org/jboss/logmanager/JDKSpecific.java b/src/main/java/org/jboss/logmanager/JDKSpecific.java index cff7d223..0d0b15f1 100644 --- a/src/main/java/org/jboss/logmanager/JDKSpecific.java +++ b/src/main/java/org/jboss/logmanager/JDKSpecific.java @@ -66,7 +66,7 @@ static Class findCallingClass(Set rejectClassLoaders) { } static LogContext logContextFinder(Set rejectClassLoaders, - final Function finder) { + final Function finder) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { return doPrivileged(new FindCallingClassesAction(rejectClassLoaders, finder)); @@ -171,7 +171,7 @@ private static final class FindCallingClassesAction implements PrivilegedAction< private final Function finder; FindCallingClassesAction(final Set rejectClassLoaders, - final Function finder) { + final Function finder) { this.rejectClassLoaders = rejectClassLoaders; this.finder = finder; } diff --git a/src/main/java/org/jboss/logmanager/LogContext.java b/src/main/java/org/jboss/logmanager/LogContext.java index 23942d29..a9a6d5ea 100644 --- a/src/main/java/org/jboss/logmanager/LogContext.java +++ b/src/main/java/org/jboss/logmanager/LogContext.java @@ -19,9 +19,7 @@ package org.jboss.logmanager; -import io.smallrye.common.constraint.Assert; -import io.smallrye.common.ref.Reference; -import io.smallrye.common.ref.References; +import static org.jboss.logmanager.LoggerNode.attachmentsFull; import java.security.AccessController; import java.security.Permission; @@ -40,19 +38,22 @@ import java.util.logging.Level; import java.util.logging.LoggingPermission; -import static org.jboss.logmanager.LoggerNode.attachmentsFull; +import io.smallrye.common.constraint.Assert; +import io.smallrye.common.ref.Reference; +import io.smallrye.common.ref.References; /** * A logging context, for producing isolated logging environments. */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({ "unused", "WeakerAccess" }) public final class LogContext implements AutoCloseable { private static final LogContext SYSTEM_CONTEXT = new LogContext(false, discoverDefaultInitializer()); private static LogContextInitializer discoverDefaultInitializer() { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { - return AccessController.doPrivileged((PrivilegedAction) LogContext::discoverDefaultInitializer0); + return AccessController + .doPrivileged((PrivilegedAction) LogContext::discoverDefaultInitializer0); } else { return discoverDefaultInitializer0(); } @@ -60,7 +61,8 @@ private static LogContextInitializer discoverDefaultInitializer() { private static LogContextInitializer discoverDefaultInitializer0() { // allow exceptions to bubble up, otherwise logging won't work with no indication as to why - final ServiceLoader loader = ServiceLoader.load(LogContextInitializer.class, LogContext.class.getClassLoader()); + final ServiceLoader loader = ServiceLoader.load(LogContextInitializer.class, + LogContext.class.getClassLoader()); final Iterator iterator = loader.iterator(); return iterator.hasNext() ? iterator.next() : LogContextInitializer.DEFAULT; } @@ -148,11 +150,11 @@ private static void addStrong(Map> map, Level lev } /** - * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} + * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} * {@link RuntimePermission RuntimePermission} to invoke this method. * * @param strong {@code true} if the context should use strong references, {@code false} to use (default) weak - * references for automatic logger GC + * references for automatic logger GC * @return a new log context */ public static LogContext create(boolean strong) { @@ -160,11 +162,11 @@ public static LogContext create(boolean strong) { } /** - * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} + * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} * {@link RuntimePermission RuntimePermission} to invoke this method. * - * @param strong {@code true} if the context should use strong references, {@code false} to use (default) weak - * references for automatic logger GC + * @param strong {@code true} if the context should use strong references, {@code false} to use (default) weak + * references for automatic logger GC * @param initializer the log context initializer to use (must not be {@code null}) * @return a new log context */ @@ -178,7 +180,7 @@ public static LogContext create(boolean strong, LogContextInitializer initialize } /** - * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} + * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} * {@link RuntimePermission RuntimePermission} to invoke this method. * * @return a new log context @@ -188,7 +190,7 @@ public static LogContext create() { } /** - * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} + * Create a new log context. If a security manager is installed, the caller must have the {@code "createLogContext"} * {@link RuntimePermission RuntimePermission} to invoke this method. * * @param initializer the log context initializer to use (must not be {@code null}) @@ -212,8 +214,10 @@ public static LogContext create(LogContextInitializer initializer) { public V getAttachment(Logger.AttachmentKey key) { Assert.checkNotNullParam("key", key); synchronized (this) { - if (key == attachmentKey1) return (V) attachmentValue1; - if (key == attachmentKey2) return (V) attachmentValue2; + if (key == attachmentKey1) + return (V) attachmentValue1; + if (key == attachmentKey2) + return (V) attachmentValue2; } return null; } @@ -223,11 +227,12 @@ public V getAttachment(Logger.AttachmentKey key) { * A strong reference is maintained to the key and value for as long as this log context exists. * Log context attachments are placed on the root logger and can also be accessed there. * - * @param key the attachment key + * @param key the attachment key * @param value the attachment value - * @param the attachment value type + * @param the attachment value type * @return the old attachment, if there was one - * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)} + * @throws SecurityException if a security manager exists and if the caller does not have + * {@code LoggingPermission(control)} * @throws IllegalArgumentException if the attachment cannot be added because the maximum has been reached */ @SuppressWarnings("unchecked") @@ -263,11 +268,12 @@ public V attach(Logger.AttachmentKey key, V value) throws SecurityExcepti * A strong reference is maintained to the key and value for as long as this log context exists. * Log context attachments are placed on the root logger and can also be accessed there. * - * @param key the attachment key + * @param key the attachment key * @param value the attachment value - * @param the attachment value type + * @param the attachment value type * @return the current attachment, if there is one, or {@code null} if the value was successfully attached - * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)} + * @throws SecurityException if a security manager exists and if the caller does not have + * {@code LoggingPermission(control)} * @throws IllegalArgumentException if the attachment cannot be added because the maximum has been reached */ @SuppressWarnings("unchecked") @@ -350,13 +356,14 @@ public Logger getLoggerIfExists(String name) { * Get a logger attachment for a logger name, if it exists. * * @param loggerName the logger name - * @param key the attachment key - * @param the attachment value type + * @param key the attachment key + * @param the attachment value type * @return the attachment or {@code null} if the logger or the attachment does not exist */ public V getAttachment(String loggerName, Logger.AttachmentKey key) { final LoggerNode node = rootLogger.getIfExists(loggerName); - if (node == null) return null; + if (node == null) + return null; return node.getAttachment(key); } @@ -382,8 +389,8 @@ public Level getLevelForName(String name) throws IllegalArgumentException { } /** - * Register a level instance with this log context. The level can then be looked up by name. Only a weak - * reference to the level instance will be kept. Any previous level registration for the given level's name + * Register a level instance with this log context. The level can then be looked up by name. Only a weak + * reference to the level instance will be kept. Any previous level registration for the given level's name * will be overwritten. * * @param level the level to register @@ -393,10 +400,10 @@ public void registerLevel(Level level) { } /** - * Register a level instance with this log context. The level can then be looked up by name. Any previous level + * Register a level instance with this log context. The level can then be looked up by name. Any previous level * registration for the given level's name will be overwritten. * - * @param level the level to register + * @param level the level to register * @param strong {@code true} to strongly reference the level, or {@code false} to weakly reference it */ public void registerLevel(Level level, boolean strong) { @@ -414,7 +421,8 @@ public void registerLevel(Level level, boolean strong) { newLevelMap.put(name, levelRef); } } - newLevelMap.put(level.getName(), References.create(strong ? Reference.Type.STRONG : Reference.Type.WEAK, level, null)); + newLevelMap.put(level.getName(), + References.create(strong ? Reference.Type.STRONG : Reference.Type.WEAK, level, null)); if (levelMapReference.compareAndSet(oldLevelMap, newLevelMap)) { return; } @@ -422,7 +430,7 @@ public void registerLevel(Level level, boolean strong) { } /** - * Unregister a previously registered level. Log levels that are not registered may still be used, they just will + * Unregister a previously registered level. Log levels that are not registered may still be used, they just will * not be findable by name. * * @param level the level to unregister @@ -485,7 +493,8 @@ public static LogContext getLogContext() { } /** - * Set a new log context selector. If a security manager is installed, the caller must have the {@code "setLogContextSelector"} + * Set a new log context selector. If a security manager is installed, the caller must have the + * {@code "setLogContextSelector"} * {@link RuntimePermission RuntimePermission} to invoke this method. * * @param newSelector the new selector. diff --git a/src/main/java/org/jboss/logmanager/LogContextConfigurator.java b/src/main/java/org/jboss/logmanager/LogContextConfigurator.java index 317d5480..b076a0fe 100644 --- a/src/main/java/org/jboss/logmanager/LogContextConfigurator.java +++ b/src/main/java/org/jboss/logmanager/LogContextConfigurator.java @@ -21,22 +21,22 @@ import java.io.InputStream; /** - * A configurator for a log context. A log context configurator should set up all the log categories, + * A configurator for a log context. A log context configurator should set up all the log categories, * handlers, formatters, filters, attachments, and other constructs as specified by the configuration. */ public interface LogContextConfigurator { /** - * Configure the given log context according to this configurator's policy. If a configuration stream was - * provided, that is passed in to this method to be used or ignored. The stream should remain open after + * Configure the given log context according to this configurator's policy. If a configuration stream was + * provided, that is passed in to this method to be used or ignored. The stream should remain open after * this method is called. * - * @param logContext the log context to configure (not {@code null}) + * @param logContext the log context to configure (not {@code null}) * @param inputStream the input stream that was requested to be used, or {@code null} if none was provided */ void configure(LogContext logContext, InputStream inputStream); /** - * A constant representing an empty configuration. The configurator does nothing. + * A constant representing an empty configuration. The configurator does nothing. */ LogContextConfigurator EMPTY = new LogContextConfigurator() { @Override diff --git a/src/main/java/org/jboss/logmanager/LogContextInitializer.java b/src/main/java/org/jboss/logmanager/LogContextInitializer.java index 90cc3593..150418ed 100644 --- a/src/main/java/org/jboss/logmanager/LogContextInitializer.java +++ b/src/main/java/org/jboss/logmanager/LogContextInitializer.java @@ -22,12 +22,13 @@ import java.util.logging.Level; /** - * An initializer for log contexts. The initializer provides initial values for log instances within the context + * An initializer for log contexts. The initializer provides initial values for log instances within the context * for properties like levels, handlers, and so on. *

- * The initial log context will be configured using a context initializer that is located via the {@linkplain java.util.ServiceLoader JDK SPI mechanism}. + * The initial log context will be configured using a context initializer that is located via the + * {@linkplain java.util.ServiceLoader JDK SPI mechanism}. *

- * This interface is intended to be forward-extensible. If new methods are added, they will include a default implementation. + * This interface is intended to be forward-extensible. If new methods are added, they will include a default implementation. * Implementations of this interface should accommodate the possibility of new methods being added; as a matter of convention, * such methods should begin with the prefix {@code getInitial}, which will minimize the possibility of conflict. */ @@ -38,14 +39,14 @@ public interface LogContextInitializer { Handler[] NO_HANDLERS = new Handler[0]; /** - * The default log context initializer, which is used when none is specified. This instance uses only + * The default log context initializer, which is used when none is specified. This instance uses only * default implementations for all the given methods. */ LogContextInitializer DEFAULT = new LogContextInitializer() { }; /** - * Get the initial level for the given logger name. If the initializer returns a {@code null} level for the + * Get the initial level for the given logger name. If the initializer returns a {@code null} level for the * root logger, then a level of {@link org.jboss.logmanager.Level#INFO INFO} will be used. *

* The default implementation returns {@code null}. @@ -58,7 +59,7 @@ default Level getInitialLevel(String loggerName) { } /** - * Get the minimum (most verbose) level allowed for the given logger name. If the initializer returns a + * Get the minimum (most verbose) level allowed for the given logger name. If the initializer returns a * {@code null} level for the root logger, then a level of {@link java.util.logging.Level#ALL ALL} will be used. *

* The default implementation returns {@code null}. @@ -73,7 +74,7 @@ default Level getMinimumLevel(String loggerName) { /** * Get the initial set of handlers to configure for the given logger name. *

- * The default implementation returns {@link #NO_HANDLERS}. A value of {@code null} is considered + * The default implementation returns {@link #NO_HANDLERS}. A value of {@code null} is considered * to be the same as {@link #NO_HANDLERS}. * * @param loggerName the logger name (must not be {@code null}) diff --git a/src/main/java/org/jboss/logmanager/LogContextSelector.java b/src/main/java/org/jboss/logmanager/LogContextSelector.java index bdb14eb5..e51e1692 100644 --- a/src/main/java/org/jboss/logmanager/LogContextSelector.java +++ b/src/main/java/org/jboss/logmanager/LogContextSelector.java @@ -20,7 +20,7 @@ package org.jboss.logmanager; /** - * A mechanism for determining what the current log context is. This method is used primarily when constructing + * A mechanism for determining what the current log context is. This method is used primarily when constructing * new loggers to determine what context the constructed logger should be installed into. */ public interface LogContextSelector { diff --git a/src/main/java/org/jboss/logmanager/LogManager.java b/src/main/java/org/jboss/logmanager/LogManager.java index 8ede125b..dcc5a90b 100644 --- a/src/main/java/org/jboss/logmanager/LogManager.java +++ b/src/main/java/org/jboss/logmanager/LogManager.java @@ -19,9 +19,6 @@ package org.jboss.logmanager; -import io.smallrye.common.constraint.Assert; - -import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.InputStream; import java.security.AccessController; @@ -37,8 +34,10 @@ import java.util.function.Function; import java.util.logging.Filter; +import io.smallrye.common.constraint.Assert; + /** - * Simplified log manager. Designed to work around the (many) design flaws of the JDK platform log manager. + * Simplified log manager. Designed to work around the (many) design flaws of the JDK platform log manager. */ public final class LogManager extends java.util.logging.LogManager { @@ -80,7 +79,7 @@ private static class LocalFilterHolder { } /** - * Construct a new logmanager instance. Attempts to plug a known memory leak in {@link java.util.logging.Level} as + * Construct a new logmanager instance. Attempts to plug a known memory leak in {@link java.util.logging.Level} as * well. */ public LogManager() { @@ -119,23 +118,27 @@ private void doConfigure(InputStream inputStream) { final ServiceLoader serviceLoader = ServiceLoader.load(ConfiguratorFactory.class); final Iterator iterator = serviceLoader.iterator(); List problems = null; - for (;;) try { - if (! iterator.hasNext()) break; - final ConfiguratorFactory f = iterator.next(); - if (f.priority() < best || factory == null) { - best = f.priority(); - factory = f; + for (;;) + try { + if (!iterator.hasNext()) + break; + final ConfiguratorFactory f = iterator.next(); + if (f.priority() < best || factory == null) { + best = f.priority(); + factory = f; + } + } catch (Throwable t) { + if (problems == null) + problems = new ArrayList<>(4); + problems.add(t); } - } catch (Throwable t) { - if (problems == null) problems = new ArrayList<>(4); - problems.add(t); - } configurator = factory == null ? null : factory.create(); if (configurator == null) { if (problems == null) { configuratorRef.set(configurator = LogContextConfigurator.EMPTY); } else { - final ServiceConfigurationError e = new ServiceConfigurationError("Failed to configure log configurator service"); + final ServiceConfigurationError e = new ServiceConfigurationError( + "Failed to configure log configurator service"); for (Throwable problem : problems) { e.addSuppressed(problem); } @@ -163,7 +166,8 @@ public void updateConfiguration(final Function> mapper) throws IOException { + public void updateConfiguration(final InputStream ins, final Function> mapper) + throws IOException { // no operation the configuration API should be used } @@ -189,7 +193,7 @@ public void removeConfigurationListener(final Runnable listener) { } /** - * Does nothing. Properties are not supported. + * Does nothing. Properties are not supported. * * @param name ignored * @return {@code null} @@ -200,7 +204,7 @@ public String getProperty(String name) { } /** - * Does nothing. This method only causes trouble. + * Does nothing. This method only causes trouble. */ public void reset() { // no operation! @@ -212,7 +216,7 @@ public Enumeration getLoggerNames() { } /** - * Do nothing. Loggers are only added/acquired via {@link #getLogger(String)}. + * Do nothing. Loggers are only added/acquired via {@link #getLogger(String)}. * * @param logger ignored * @return {@code false} diff --git a/src/main/java/org/jboss/logmanager/Logger.java b/src/main/java/org/jboss/logmanager/Logger.java index 8959bf39..526b6180 100644 --- a/src/main/java/org/jboss/logmanager/Logger.java +++ b/src/main/java/org/jboss/logmanager/Logger.java @@ -19,8 +19,6 @@ package org.jboss.logmanager; -import io.smallrye.common.constraint.Assert; - import java.io.ObjectStreamException; import java.io.Serializable; import java.util.Arrays; @@ -32,8 +30,10 @@ import java.util.logging.Level; import java.util.logging.LogRecord; +import io.smallrye.common.constraint.Assert; + /** - * An actual logger instance. This is the end-user interface into the logging system. + * An actual logger instance. This is the end-user interface into the logging system. */ @SuppressWarnings({ "SerializableClassWithUnconstructableAncestor" }) public final class Logger extends java.util.logging.Logger implements Serializable { @@ -53,7 +53,8 @@ public final class Logger extends java.util.logging.Logger implements Serializab /** * Atomic updater for {@link #resourceBundle}. */ - private static final AtomicReferenceFieldUpdater resourceBundleUpdater = AtomicReferenceFieldUpdater.newUpdater(Logger.class, ResourceBundle.class, "resourceBundle"); + private static final AtomicReferenceFieldUpdater resourceBundleUpdater = AtomicReferenceFieldUpdater + .newUpdater(Logger.class, ResourceBundle.class, "resourceBundle"); private static final String LOGGER_CLASS_NAME = Logger.class.getName(); @@ -70,7 +71,7 @@ public static Logger getLogger(final String name) { /** * Static logger factory method which returns a JBoss LogManager logger. * - * @param name the logger name + * @param name the logger name * @param bundleName the bundle name * @return the logger */ @@ -84,7 +85,7 @@ public static Logger getLogger(final String name, final String bundleName) { * Construct a new instance of an actual logger. * * @param loggerNode the node in the named logger tree - * @param name the fully-qualified name of this node + * @param name the fully-qualified name of this node */ Logger(final LoggerNode loggerNode, final String name) { // Don't set up the bundle in the parent... @@ -116,7 +117,7 @@ public Filter getFilter() { // Level mgmt /** - * {@inheritDoc} This implementation grabs a lock, so that only one thread may update the log level of any + * {@inheritDoc} This implementation grabs a lock, so that only one thread may update the log level of any * logger at a time, in order to allow readers to never block (though there is a window where retrieving the * log level reflects an older effective level than the actual level). */ @@ -128,7 +129,7 @@ public void setLevel(Level newLevel) throws SecurityException { } /** - * Set the log level by name. Uses the parent logging context's name registry; otherwise behaves + * Set the log level by name. Uses the parent logging context's name registry; otherwise behaves * identically to {@link #setLevel(Level)}. * * @param newLevelName the name of the level to set @@ -175,11 +176,12 @@ public V getAttachment(AttachmentKey key) { * Attach an object to this logger under a given key. * A strong reference is maintained to the key and value for as long as this logger exists. * - * @param key the attachment key + * @param key the attachment key * @param value the attachment value - * @param the attachment value type + * @param the attachment value type * @return the old attachment, if there was one - * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)} + * @throws SecurityException if a security manager exists and if the caller does not have + * {@code LoggingPermission(control)} * @throws IllegalArgumentException if the attachment cannot be added because the maximum has been reached */ public V attach(AttachmentKey key, V value) throws SecurityException { @@ -191,11 +193,12 @@ public V attach(AttachmentKey key, V value) throws SecurityException { * Attach an object to this logger under a given key, if such an attachment does not already exist. * A strong reference is maintained to the key and value for as long as this logger exists. * - * @param key the attachment key + * @param key the attachment key * @param value the attachment value - * @param the attachment value type + * @param the attachment value type * @return the current attachment, if there is one, or {@code null} if the value was successfully attached - * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)} + * @throws SecurityException if a security manager exists and if the caller does not have + * {@code LoggingPermission(control)} * @throws IllegalArgumentException if the attachment cannot be added because the maximum has been reached */ @SuppressWarnings({ "unchecked" }) @@ -282,9 +285,10 @@ public Handler[] getAndSetHandlers(final Handler[] handlers) throws SecurityExce /** * Atomically compare and set the handler list for this logger. * - * @param expected the expected list of handlers + * @param expected the expected list of handlers * @param newHandlers the replacement list of handlers - * @return {@code true} if the handler list was updated or {@code false} if the current handlers did not match the expected handlers list + * @return {@code true} if the handler list was updated or {@code false} if the current handlers did not match the expected + * handlers list * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)} */ public boolean compareAndSetHandlers(final Handler[] expected, final Handler[] newHandlers) throws SecurityException { @@ -299,10 +303,10 @@ public boolean compareAndSetHandlers(final Handler[] expected, final Handler[] n Handler[] oldHandlers; do { oldHandlers = loggerNode.getHandlers(); - if (! Arrays.equals(oldHandlers, safeExpectedHandlers)) { + if (!Arrays.equals(oldHandlers, safeExpectedHandlers)) { return false; } - } while (! loggerNode.compareAndSetHandlers(oldHandlers, safeNewHandlers)); + } while (!loggerNode.compareAndSetHandlers(oldHandlers, safeNewHandlers)); return true; } @@ -358,7 +362,8 @@ public Logger getParent() { } /** - * Not allowed. This method may never be called. + * Not allowed. This method may never be called. + * * @throws SecurityException always */ public void setParent(java.util.logging.Logger parent) { @@ -390,7 +395,8 @@ public LogContext getLogContext() { public void log(LogRecord record) { Filter filter = null; final int effectiveLevel = loggerNode.getEffectiveLevel(); - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(record.getLevel().intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(record.getLevel().intValue())) { return; } if (LogManager.PER_THREAD_LOG_FILTER && filter != null && !filter.isLoggable(record)) { @@ -402,7 +408,8 @@ public void log(LogRecord record) { /** {@inheritDoc} */ public void entering(final String sourceClass, final String sourceMethod) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINER_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINER_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINER, "ENTRY", LOGGER_CLASS_NAME); @@ -417,13 +424,14 @@ public void entering(final String sourceClass, final String sourceMethod) { /** {@inheritDoc} */ public void entering(final String sourceClass, final String sourceMethod, final Object param1) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINER_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINER_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINER, "ENTRY {0}", LOGGER_CLASS_NAME); rec.setSourceClassName(sourceClass); rec.setSourceMethodName(sourceMethod); - rec.setParameters(new Object[] {param1}); + rec.setParameters(new Object[] { param1 }); if (LogManager.PER_THREAD_LOG_FILTER && filter != null && !filter.isLoggable(rec)) { return; } @@ -433,17 +441,20 @@ public void entering(final String sourceClass, final String sourceMethod, final /** {@inheritDoc} */ public void entering(final String sourceClass, final String sourceMethod, final Object[] params) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINER_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINER_INT)) { return; } final StringBuilder builder = new StringBuilder("ENTRY"); - if (params != null) for (int i = 0; i < params.length; i++) { - builder.append(" {").append(i).append('}'); - } + if (params != null) + for (int i = 0; i < params.length; i++) { + builder.append(" {").append(i).append('}'); + } final ExtLogRecord rec = new ExtLogRecord(Level.FINER, builder.toString(), LOGGER_CLASS_NAME); rec.setSourceClassName(sourceClass); rec.setSourceMethodName(sourceMethod); - if (params != null) rec.setParameters(params); + if (params != null) + rec.setParameters(params); if (LogManager.PER_THREAD_LOG_FILTER && filter != null && !filter.isLoggable(rec)) { return; } @@ -453,7 +464,8 @@ public void entering(final String sourceClass, final String sourceMethod, final /** {@inheritDoc} */ public void exiting(final String sourceClass, final String sourceMethod) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINER_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINER_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINER, "RETURN", LOGGER_CLASS_NAME); @@ -468,13 +480,14 @@ public void exiting(final String sourceClass, final String sourceMethod) { /** {@inheritDoc} */ public void exiting(final String sourceClass, final String sourceMethod, final Object result) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINER_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINER_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINER, "RETURN {0}", LOGGER_CLASS_NAME); rec.setSourceClassName(sourceClass); rec.setSourceMethodName(sourceMethod); - rec.setParameters(new Object[] {result}); + rec.setParameters(new Object[] { result }); if (LogManager.PER_THREAD_LOG_FILTER && filter != null && !filter.isLoggable(rec)) { return; } @@ -484,7 +497,8 @@ public void exiting(final String sourceClass, final String sourceMethod, final O /** {@inheritDoc} */ public void throwing(final String sourceClass, final String sourceMethod, final Throwable thrown) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINER_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINER_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINER, "THROW", LOGGER_CLASS_NAME); @@ -500,7 +514,8 @@ public void throwing(final String sourceClass, final String sourceMethod, final /** {@inheritDoc} */ public void severe(final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(SEVERE_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(SEVERE_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.SEVERE, msg, LOGGER_CLASS_NAME); @@ -513,7 +528,8 @@ public void severe(final String msg) { /** {@inheritDoc} */ public void warning(final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(WARNING_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(WARNING_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.WARNING, msg, LOGGER_CLASS_NAME); @@ -526,7 +542,8 @@ public void warning(final String msg) { /** {@inheritDoc} */ public void info(final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(INFO_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(INFO_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.INFO, msg, LOGGER_CLASS_NAME); @@ -539,7 +556,8 @@ public void info(final String msg) { /** {@inheritDoc} */ public void config(final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(CONFIG_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(CONFIG_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.CONFIG, msg, LOGGER_CLASS_NAME); @@ -552,7 +570,8 @@ public void config(final String msg) { /** {@inheritDoc} */ public void fine(final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINE_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINE_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINE, msg, LOGGER_CLASS_NAME); @@ -565,7 +584,8 @@ public void fine(final String msg) { /** {@inheritDoc} */ public void finer(final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINER_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINER_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINER, msg, LOGGER_CLASS_NAME); @@ -578,7 +598,8 @@ public void finer(final String msg) { /** {@inheritDoc} */ public void finest(final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(FINEST_INT)) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(FINEST_INT)) { return; } final ExtLogRecord rec = new ExtLogRecord(Level.FINEST, msg, LOGGER_CLASS_NAME); @@ -591,7 +612,8 @@ public void finest(final String msg) { /** {@inheritDoc} */ public void log(final Level level, final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); @@ -604,7 +626,8 @@ public void log(final Level level, final String msg) { /** {@inheritDoc} */ public void log(final Level level, final String msg, final Object param1) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); @@ -618,11 +641,13 @@ public void log(final Level level, final String msg, final Object param1) { /** {@inheritDoc} */ public void log(final Level level, final String msg, final Object[] params) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); - if (params != null) rec.setParameters(params); + if (params != null) + rec.setParameters(params); if (LogManager.PER_THREAD_LOG_FILTER && filter != null && !filter.isLoggable(rec)) { return; } @@ -632,7 +657,8 @@ public void log(final Level level, final String msg, final Object[] params) { /** {@inheritDoc} */ public void log(final Level level, final String msg, final Throwable thrown) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); @@ -646,7 +672,8 @@ public void log(final Level level, final String msg, final Throwable thrown) { /** {@inheritDoc} */ public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); @@ -659,15 +686,17 @@ public void logp(final Level level, final String sourceClass, final String sourc } /** {@inheritDoc} */ - public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Object param1) { + public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, + final Object param1) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); rec.setSourceClassName(sourceClass); rec.setSourceMethodName(sourceMethod); - rec.setParameters(new Object[] {param1}); + rec.setParameters(new Object[] { param1 }); if (LogManager.PER_THREAD_LOG_FILTER && filter != null && !filter.isLoggable(rec)) { return; } @@ -675,15 +704,18 @@ public void logp(final Level level, final String sourceClass, final String sourc } /** {@inheritDoc} */ - public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Object[] params) { + public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, + final Object[] params) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); rec.setSourceClassName(sourceClass); rec.setSourceMethodName(sourceMethod); - if (params != null) rec.setParameters(params); + if (params != null) + rec.setParameters(params); if (LogManager.PER_THREAD_LOG_FILTER && filter != null && !filter.isLoggable(rec)) { return; } @@ -691,9 +723,11 @@ public void logp(final Level level, final String sourceClass, final String sourc } /** {@inheritDoc} */ - public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Throwable thrown) { + public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, + final Throwable thrown) { Filter filter = null; - if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue())) { + if (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } final ExtLogRecord rec = new ExtLogRecord(level, msg, LOGGER_CLASS_NAME); @@ -707,8 +741,10 @@ public void logp(final Level level, final String sourceClass, final String sourc } /** {@inheritDoc} */ - public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, final String msg) { - if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) && !loggerNode.isLoggableLevel(level.intValue())) { + public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, + final String msg) { + if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } // No local check is needed here as this will delegate to log(LogRecord) @@ -716,8 +752,10 @@ public void logrb(final Level level, final String sourceClass, final String sour } /** {@inheritDoc} */ - public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, final String msg, final Object param1) { - if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) && !loggerNode.isLoggableLevel(level.intValue())) { + public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, + final String msg, final Object param1) { + if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } // No local check is needed here as this will delegate to log(LogRecord) @@ -725,8 +763,10 @@ public void logrb(final Level level, final String sourceClass, final String sour } /** {@inheritDoc} */ - public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, final String msg, final Object[] params) { - if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) && !loggerNode.isLoggableLevel(level.intValue())) { + public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, + final String msg, final Object[] params) { + if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } // No local check is needed here as this will delegate to log(LogRecord) @@ -734,8 +774,10 @@ public void logrb(final Level level, final String sourceClass, final String sour } /** {@inheritDoc} */ - public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, final String msg, final Throwable thrown) { - if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) && !loggerNode.isLoggableLevel(level.intValue())) { + public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, + final String msg, final Throwable thrown) { + if (!(LogManager.PER_THREAD_LOG_FILTER && LogManager.getThreadLocalLogFilter() != null) + && !loggerNode.isLoggableLevel(level.intValue())) { return; } // No local check is needed here as this will delegate to log(LogRecord) @@ -747,17 +789,20 @@ public void logrb(final Level level, final String sourceClass, final String sour /** * SPI interface method to log a message at a given level, with a specific resource bundle. * - * @param fqcn the fully qualified class name of the first logger class - * @param level the level to log at - * @param message the message + * @param fqcn the fully qualified class name of the first logger class + * @param level the level to log at + * @param message the message * @param bundleName the resource bundle name - * @param style the message format style - * @param params the log parameters - * @param t the throwable, if any + * @param style the message format style + * @param params the log parameters + * @param t the throwable, if any */ - public void log(final String fqcn, final Level level, final String message, final String bundleName, final ExtLogRecord.FormatStyle style, final Object[] params, final Throwable t) { + public void log(final String fqcn, final Level level, final String message, final String bundleName, + final ExtLogRecord.FormatStyle style, final Object[] params, final Throwable t) { Filter filter = null; - if (level == null || fqcn == null || message == null || (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) || !loggerNode.isLoggableLevel(level.intValue()))) { + if (level == null || fqcn == null || message == null + || (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + || !loggerNode.isLoggableLevel(level.intValue()))) { return; } final ExtLogRecord rec = new ExtLogRecord(level, message, style, fqcn); @@ -773,16 +818,19 @@ public void log(final String fqcn, final Level level, final String message, fina /** * SPI interface method to log a message at a given level. * - * @param fqcn the fully qualified class name of the first logger class - * @param level the level to log at + * @param fqcn the fully qualified class name of the first logger class + * @param level the level to log at * @param message the message - * @param style the message format style - * @param params the log parameters - * @param t the throwable, if any + * @param style the message format style + * @param params the log parameters + * @param t the throwable, if any */ - public void log(final String fqcn, final Level level, final String message, final ExtLogRecord.FormatStyle style, final Object[] params, final Throwable t) { + public void log(final String fqcn, final Level level, final String message, final ExtLogRecord.FormatStyle style, + final Object[] params, final Throwable t) { Filter filter = null; - if (level == null || fqcn == null || message == null || (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) && !loggerNode.isLoggableLevel(level.intValue()))) { + if (level == null || fqcn == null || message == null + || (!(LogManager.PER_THREAD_LOG_FILTER && (filter = LogManager.getThreadLocalLogFilter()) != null) + && !loggerNode.isLoggableLevel(level.intValue()))) { return; } final ExtLogRecord rec = new ExtLogRecord(level, message, style, fqcn); @@ -797,10 +845,10 @@ public void log(final String fqcn, final Level level, final String message, fina /** * SPI interface method to log a message at a given level. * - * @param fqcn the fully qualified class name of the first logger class - * @param level the level to log at + * @param fqcn the fully qualified class name of the first logger class + * @param level the level to log at * @param message the message - * @param t the throwable, if any + * @param t the throwable, if any */ public void log(final String fqcn, final Level level, final String message, final Throwable t) { log(fqcn, level, message, ExtLogRecord.FormatStyle.MESSAGE_FORMAT, null, t); @@ -832,7 +880,7 @@ public void logRaw(final ExtLogRecord record) { } /** - * Set the resource bundle for this logger. Unlike {@link java.util.logging.Logger#setResourceBundle(ResourceBundle)}, + * Set the resource bundle for this logger. Unlike {@link java.util.logging.Logger#setResourceBundle(ResourceBundle)}, * there is no parent search performed for resource bundles by this implementation. * * @param resourceBundle the resource bundle (must not be {@code null}) @@ -844,14 +892,14 @@ public void setResourceBundle(ResourceBundle resourceBundle) { ResourceBundle old; do { old = this.resourceBundle; - if (old != null && ! old.getBaseBundleName().equals(resourceBundle.getBaseBundleName())) { + if (old != null && !old.getBaseBundleName().equals(resourceBundle.getBaseBundleName())) { throw new IllegalArgumentException("Bundle base name does not match existing bundle"); } - } while (! resourceBundleUpdater.compareAndSet(this, old, resourceBundle)); + } while (!resourceBundleUpdater.compareAndSet(this, old, resourceBundle)); } /** - * Get the resource bundle for this logger. Unlike {@link java.util.logging.Logger#getResourceBundle()}, + * Get the resource bundle for this logger. Unlike {@link java.util.logging.Logger#getResourceBundle()}, * there is no parent search performed for resource bundles by this implementation. * * @return the resource bundle, or {@code null} if none is configured for this logger @@ -862,7 +910,7 @@ public ResourceBundle getResourceBundle() { } /** - * Get the resource bundle name for this logger. Unlike {@link java.util.logging.Logger#getResourceBundleName()}, + * Get the resource bundle name for this logger. Unlike {@link java.util.logging.Logger#getResourceBundleName()}, * there is no parent search performed for resource bundles by this implementation. * * @return the resource bundle, or {@code null} if none is configured for this logger @@ -874,7 +922,7 @@ public String getResourceBundleName() { } /** - * Do the logging with no level checks (they've already been done). Creates an extended log record if the + * Do the logging with no level checks (they've already been done). Creates an extended log record if the * provided record is not one. * * @param record the log record diff --git a/src/main/java/org/jboss/logmanager/LoggerNode.java b/src/main/java/org/jboss/logmanager/LoggerNode.java index b9d29f27..932dc422 100644 --- a/src/main/java/org/jboss/logmanager/LoggerNode.java +++ b/src/main/java/org/jboss/logmanager/LoggerNode.java @@ -19,11 +19,6 @@ package org.jboss.logmanager; -import io.smallrye.common.constraint.Assert; -import io.smallrye.common.ref.PhantomReference; -import io.smallrye.common.ref.Reaper; -import io.smallrye.common.ref.Reference; - import java.lang.reflect.UndeclaredThrowableException; import java.security.AccessController; import java.security.PrivilegedAction; @@ -41,8 +36,13 @@ import java.util.logging.Handler; import java.util.logging.Level; +import io.smallrye.common.constraint.Assert; +import io.smallrye.common.ref.PhantomReference; +import io.smallrye.common.ref.Reaper; +import io.smallrye.common.ref.Reference; + /** - * A node in the tree of logger names. Maintains weak references to children and a strong reference to its parent. + * A node in the tree of logger names. Maintains weak references to children and a strong reference to its parent. */ final class LoggerNode implements AutoCloseable { @@ -68,12 +68,12 @@ public void reap(Reference reference) { private final String fullName; /** - * The map of names to child nodes. The child node references are weak. + * The map of names to child nodes. The child node references are weak. */ private final ConcurrentMap children; /** - * The handlers for this logger. May only be updated using the {@link #handlersUpdater} atomic updater. The array + * The handlers for this logger. May only be updated using the {@link #handlersUpdater} atomic updater. The array * instance should not be modified (treat as immutable). */ @SuppressWarnings({ "UnusedDeclaration" }) @@ -122,15 +122,16 @@ public void reap(Reference reference) { /** * The atomic updater for the {@link #handlers} field. */ - private static final AtomicArray handlersUpdater = AtomicArray.create(AtomicReferenceFieldUpdater.newUpdater(LoggerNode.class, Handler[].class, "handlers"), Handler.class); + private static final AtomicArray handlersUpdater = AtomicArray + .create(AtomicReferenceFieldUpdater.newUpdater(LoggerNode.class, Handler[].class, "handlers"), Handler.class); /** - * The actual level. May only be modified when the context's level change lock is held; in addition, changing + * The actual level. May only be modified when the context's level change lock is held; in addition, changing * this field must be followed immediately by recursively updating the effective loglevel of the child tree. */ private volatile java.util.logging.Level level; /** - * The effective level. May only be modified when the context's level change lock is held; in addition, changing + * The effective level. May only be modified when the context's level change lock is held; in addition, changing * this field must be followed immediately by recursively updating the effective loglevel of the child tree. */ private volatile int effectiveLevel; @@ -166,8 +167,8 @@ public void reap(Reference reference) { /** * Construct a child instance. * - * @param context the logmanager - * @param parent the parent node + * @param context the logmanager + * @param parent the parent node * @param nodeName the name of this subnode */ private LoggerNode(LogContext context, LoggerNode parent, String nodeName) { @@ -210,16 +211,18 @@ static Handler[] safeCloneHandlers(Handler... initialHandlers) { if (clone[i] == null) { // our clone contains nulls; we have to clone again to be safe int cnt; - for (cnt = 1, i ++; i < length; i ++) { - if (clone[i] == null) cnt ++; + for (cnt = 1, i++; i < length; i++) { + if (clone[i] == null) + cnt++; } final int newLen = length - cnt; if (newLen == 0) { return LogContextInitializer.NO_HANDLERS; } final Handler[] newClone = new Handler[newLen]; - for (int j = 0, k = 0; j < length; j ++) { - if (clone[j] != null) newClone[k++] = clone[j]; + for (int j = 0, k = 0; j < length; j++) { + if (clone[j] != null) + newClone[k++] = clone[j]; } return newClone; } @@ -256,7 +259,7 @@ public void close() { } /** - * Get or create a relative logger node. The name is relatively qualified to this node. + * Get or create a relative logger node. The name is relatively qualified to this node. * * @param name the name * @return the corresponding logger node @@ -332,7 +335,7 @@ LogContext getContext() { } /** - * Update the effective level if it is inherited from a parent. Must only be called while the logmanager's level + * Update the effective level if it is inherited from a parent. Must only be called while the logmanager's level * change lock is held. * * @param newLevel the new effective level @@ -409,35 +412,37 @@ void setUseParentHandlers(final boolean useParentHandlers) { } void publish(final ExtLogRecord record) { - for (Handler handler : handlers) try { - handler.publish(record); - } catch (VirtualMachineError e) { - throw e; - } catch (Throwable t) { - ErrorManager errorManager = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ErrorManager run() { - return handler.getErrorManager(); - } - }); - if (errorManager != null) { - Exception e; - if (t instanceof Exception) { - e = (Exception) t; - } else { - e = new UndeclaredThrowableException(t); - e.setStackTrace(EMPTY_STACK); - } - try { - errorManager.error("Handler publication threw an exception", e, ErrorManager.WRITE_FAILURE); - } catch (Throwable t2) { - StandardOutputStreams.printError(t2, "Handler.reportError caught an exception"); + for (Handler handler : handlers) + try { + handler.publish(record); + } catch (VirtualMachineError e) { + throw e; + } catch (Throwable t) { + ErrorManager errorManager = AccessController.doPrivileged(new PrivilegedAction() { + @Override + public ErrorManager run() { + return handler.getErrorManager(); + } + }); + if (errorManager != null) { + Exception e; + if (t instanceof Exception) { + e = (Exception) t; + } else { + e = new UndeclaredThrowableException(t); + e.setStackTrace(EMPTY_STACK); + } + try { + errorManager.error("Handler publication threw an exception", e, ErrorManager.WRITE_FAILURE); + } catch (Throwable t2) { + StandardOutputStreams.printError(t2, "Handler.reportError caught an exception"); + } } } - } if (useParentHandlers) { final LoggerNode parent = this.parent; - if (parent != null) parent.publish(record); + if (parent != null) + parent.publish(record); } } @@ -482,8 +487,10 @@ Level getLevel() { V getAttachment(final Logger.AttachmentKey key) { Assert.checkNotNullParam("key", key); synchronized (this) { - if (key == attachmentKey1) return (V) attachmentValue1; - if (key == attachmentKey2) return (V) attachmentValue2; + if (key == attachmentKey1) + return (V) attachmentValue1; + if (key == attachmentKey2) + return (V) attachmentValue2; } return null; } @@ -593,7 +600,8 @@ private static boolean isLoggable(final LoggerNode loggerNode, final ExtLogRecor return true; } final Filter filter = loggerNode.filter; - return !(filter != null && !filter.isLoggable(record)) && (!loggerNode.useParentFilter || isLoggable(loggerNode.getParent(), record)); + return !(filter != null && !filter.isLoggable(record)) + && (!loggerNode.useParentFilter || isLoggable(loggerNode.getParent(), record)); } Enumeration getLoggerNames() { diff --git a/src/main/java/org/jboss/logmanager/MDC.java b/src/main/java/org/jboss/logmanager/MDC.java index 1dfbdbf4..01cabf4e 100644 --- a/src/main/java/org/jboss/logmanager/MDC.java +++ b/src/main/java/org/jboss/logmanager/MDC.java @@ -27,33 +27,36 @@ import java.util.ServiceLoader; /** - * Mapped diagnostic context. This is a thread-local map used to hold loggable information. + * Mapped diagnostic context. This is a thread-local map used to hold loggable information. */ public final class MDC { private static final MDCProvider mdcProvider = getDefaultMDCProvider(); - private MDC() {} + private MDC() { + } static MDCProvider getMDCProvider() { return mdcProvider; } private static MDCProvider getDefaultMDCProvider() { - return System.getSecurityManager() == null ? doGetDefaultMDCProvider() : AccessController.doPrivileged((PrivilegedAction) MDC::doGetDefaultMDCProvider); + return System.getSecurityManager() == null ? doGetDefaultMDCProvider() + : AccessController.doPrivileged((PrivilegedAction) MDC::doGetDefaultMDCProvider); } private static MDCProvider doGetDefaultMDCProvider() { final ServiceLoader configLoader = ServiceLoader.load(MDCProvider.class, MDC.class.getClassLoader()); final Iterator iterator = configLoader.iterator(); - for (;;) try { - if (! iterator.hasNext()) { - return new ThreadLocalMDC(); + for (;;) + try { + if (!iterator.hasNext()) { + return new ThreadLocalMDC(); + } + return iterator.next(); + } catch (ServiceConfigurationError | RuntimeException e) { + System.err.print("Warning: failed to load MDC Provider: "); + e.printStackTrace(System.err); } - return iterator.next(); - } catch (ServiceConfigurationError | RuntimeException e) { - System.err.print("Warning: failed to load MDC Provider: "); - e.printStackTrace(System.err); - } } /** @@ -79,7 +82,7 @@ public static Object getObject(String key) { /** * Set the value of a key, returning the old value (if any) or {@code null} if there was none. * - * @param key the key + * @param key the key * @param value the new value * @return the old value or {@code null} if there was none */ @@ -90,7 +93,7 @@ public static String put(String key, String value) { /** * Set the value of a key, returning the old value (if any) or {@code null} if there was none. * - * @param key the key + * @param key the key * @param value the new value * @return the old value or {@code null} if there was none */ @@ -119,7 +122,7 @@ public static Object removeObject(String key) { } /** - * Get a copy of the MDC map. This is a relatively expensive operation. + * Get a copy of the MDC map. This is a relatively expensive operation. * * @return a copy of the map */ @@ -128,7 +131,7 @@ public static Map copy() { } /** - * Get a copy of the MDC map. This is a relatively expensive operation. + * Get a copy of the MDC map. This is a relatively expensive operation. * * @return a copy of the map */ diff --git a/src/main/java/org/jboss/logmanager/MDCProvider.java b/src/main/java/org/jboss/logmanager/MDCProvider.java index 1c2723fe..bf644735 100644 --- a/src/main/java/org/jboss/logmanager/MDCProvider.java +++ b/src/main/java/org/jboss/logmanager/MDCProvider.java @@ -55,14 +55,14 @@ public interface MDCProvider { Object removeObject(String key); /** - * Get a copy of the MDC map. This is a relatively expensive operation. + * Get a copy of the MDC map. This is a relatively expensive operation. * * @return a copy of the map */ Map copy(); /** - * Get a copy of the MDC map. This is a relatively expensive operation. + * Get a copy of the MDC map. This is a relatively expensive operation. * * @return a copy of the map */ diff --git a/src/main/java/org/jboss/logmanager/NDC.java b/src/main/java/org/jboss/logmanager/NDC.java index 2e8b330c..337759f8 100644 --- a/src/main/java/org/jboss/logmanager/NDC.java +++ b/src/main/java/org/jboss/logmanager/NDC.java @@ -26,34 +26,37 @@ import java.util.ServiceLoader; /** - * Nested diagnostic context. This is basically a thread-local stack that holds a string which can be included + * Nested diagnostic context. This is basically a thread-local stack that holds a string which can be included * in a log message. */ public final class NDC { private static final NDCProvider ndcProvider = getDefaultNDCProvider(); - private NDC() {} + private NDC() { + } static NDCProvider getNDCProvider() { return ndcProvider; } static NDCProvider getDefaultNDCProvider() { - return System.getSecurityManager() == null ? doGetDefaultNDCProvider() : AccessController.doPrivileged((PrivilegedAction) NDC::doGetDefaultNDCProvider); + return System.getSecurityManager() == null ? doGetDefaultNDCProvider() + : AccessController.doPrivileged((PrivilegedAction) NDC::doGetDefaultNDCProvider); } static NDCProvider doGetDefaultNDCProvider() { final ServiceLoader configLoader = ServiceLoader.load(NDCProvider.class, NDC.class.getClassLoader()); final Iterator iterator = configLoader.iterator(); - for (;;) try { - if (! iterator.hasNext()) { - return new ThreadLocalNDC(); + for (;;) + try { + if (!iterator.hasNext()) { + return new ThreadLocalNDC(); + } + return iterator.next(); + } catch (ServiceConfigurationError | RuntimeException e) { + System.err.print("Warning: failed to load NDC Provider: "); + e.printStackTrace(System.err); } - return iterator.next(); - } catch (ServiceConfigurationError | RuntimeException e) { - System.err.print("Warning: failed to load NDC Provider: "); - e.printStackTrace(System.err); - } } /** @@ -83,7 +86,7 @@ public static void clear() { } /** - * Trim the thread NDC stack down to no larger than the given size. Used to restore the stack to the depth returned + * Trim the thread NDC stack down to no larger than the given size. Used to restore the stack to the depth returned * by a {@code push()}. * * @param size the new size @@ -111,7 +114,7 @@ public static String get() { } /** - * Provided for compatibility with log4j. Get the NDC value that is {@code n} entries from the bottom. + * Provided for compatibility with log4j. Get the NDC value that is {@code n} entries from the bottom. * * @param n the index * @return the value or {@code null} if there is none diff --git a/src/main/java/org/jboss/logmanager/NDCProvider.java b/src/main/java/org/jboss/logmanager/NDCProvider.java index f1d9b5d4..9e83b407 100644 --- a/src/main/java/org/jboss/logmanager/NDCProvider.java +++ b/src/main/java/org/jboss/logmanager/NDCProvider.java @@ -23,7 +23,7 @@ public interface NDCProvider { void clear(); /** - * Trim the thread NDC stack down to no larger than the given size. Used to restore the stack to the depth returned + * Trim the thread NDC stack down to no larger than the given size. Used to restore the stack to the depth returned * by a {@code push()}. * * @param size the new size @@ -45,7 +45,7 @@ public interface NDCProvider { String get(); /** - * Provided for compatibility with log4j. Get the NDC value that is {@code n} entries from the bottom. + * Provided for compatibility with log4j. Get the NDC value that is {@code n} entries from the bottom. * * @param n the index * @return the value or {@code null} if there is none diff --git a/src/main/java/org/jboss/logmanager/PropertyValues.java b/src/main/java/org/jboss/logmanager/PropertyValues.java index 367730a0..131c1de1 100644 --- a/src/main/java/org/jboss/logmanager/PropertyValues.java +++ b/src/main/java/org/jboss/logmanager/PropertyValues.java @@ -60,7 +60,8 @@ public class PropertyValues { * @return a map of the key value pairs or an empty map if the string is {@code null} or empty */ public static Map stringToMap(final String s) { - if (s == null || s.isEmpty()) return Collections.emptyMap(); + if (s == null || s.isEmpty()) + return Collections.emptyMap(); final Map map = new LinkedHashMap<>(); @@ -82,7 +83,8 @@ public static Map stringToMap(final String s) { continue; } } - throw new IllegalStateException("Escape character found at invalid position " + i + ". Only characters '=' and '\\' need to be escaped for a key."); + throw new IllegalStateException("Escape character found at invalid position " + i + + ". Only characters '=' and '\\' need to be escaped for a key."); } case '=': { state = VALUE; @@ -105,7 +107,8 @@ public static Map stringToMap(final String s) { continue; } } - throw new IllegalStateException("Escape character found at invalid position " + i + ". Only characters ',' and '\\' need to be escaped for a value."); + throw new IllegalStateException("Escape character found at invalid position " + i + + ". Only characters ',' and '\\' need to be escaped for a value."); } case ',': { // Only add if the key isn't empty @@ -173,7 +176,6 @@ public static > EnumMap stringToEnumMap(final Class return stringToEnumMap(enumType, s, true); } - /** * Parses a string of key/value pairs into an {@linkplain EnumMap enum map}. *

@@ -199,9 +201,11 @@ public static > EnumMap stringToEnumMap(final Class * @return a map of the key value pairs or an empty map if the string is {@code null} or empty */ @SuppressWarnings("SameParameterValue") - public static > EnumMap stringToEnumMap(final Class enumType, final String s, final boolean convertKeyCase) { + public static > EnumMap stringToEnumMap(final Class enumType, final String s, + final boolean convertKeyCase) { final EnumMap result = new EnumMap<>(enumType); - if (s == null || s.isEmpty()) return result; + if (s == null || s.isEmpty()) + return result; final StringBuilder key = new StringBuilder(); final StringBuilder value = new StringBuilder(); @@ -241,7 +245,8 @@ public static > EnumMap stringToEnumMap(final Class continue; } } - throw new IllegalStateException("Escape character found at invalid position " + i + ". Only characters ',' and '\\' need to be escaped for a value."); + throw new IllegalStateException("Escape character found at invalid position " + i + + ". Only characters ',' and '\\' need to be escaped for a value."); } case ',': { // Only add if the key isn't empty diff --git a/src/main/java/org/jboss/logmanager/SerializedLogger.java b/src/main/java/org/jboss/logmanager/SerializedLogger.java index aa040bf3..f67a5bd0 100644 --- a/src/main/java/org/jboss/logmanager/SerializedLogger.java +++ b/src/main/java/org/jboss/logmanager/SerializedLogger.java @@ -22,7 +22,7 @@ import java.io.Serializable; /** - * A marker class for loggers. After read, the {@link #readResolve()} method will return a logger with the given name. + * A marker class for loggers. After read, the {@link #readResolve()} method will return a logger with the given name. */ public final class SerializedLogger implements Serializable { diff --git a/src/main/java/org/jboss/logmanager/StandardOutputStreams.java b/src/main/java/org/jboss/logmanager/StandardOutputStreams.java index e7ceaab5..40057be1 100644 --- a/src/main/java/org/jboss/logmanager/StandardOutputStreams.java +++ b/src/main/java/org/jboss/logmanager/StandardOutputStreams.java @@ -26,7 +26,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"WeakerAccess", "unused"}) +@SuppressWarnings({ "WeakerAccess", "unused" }) public class StandardOutputStreams { public static final PrintStream stdout = System.out; public static final PrintStream stderr = System.err; diff --git a/src/main/java/org/jboss/logmanager/ThreadLocalLogContextSelector.java b/src/main/java/org/jboss/logmanager/ThreadLocalLogContextSelector.java index 4dbe8a0a..8e5d5272 100644 --- a/src/main/java/org/jboss/logmanager/ThreadLocalLogContextSelector.java +++ b/src/main/java/org/jboss/logmanager/ThreadLocalLogContextSelector.java @@ -43,7 +43,7 @@ public ThreadLocalLogContextSelector(final LogContextSelector delegate) { * Construct a new instance. * * @param securityKey the security key required to push or pop a log context. - * @param delegate the selector to delegate to if no context is chosen + * @param delegate the selector to delegate to if no context is chosen */ public ThreadLocalLogContextSelector(final Object securityKey, final LogContextSelector delegate) { this.securityKey = securityKey; @@ -59,7 +59,7 @@ public LogContext getLogContext() { * Get and set the log context. * * @param securityKey the security key to check (ignored if none was set on construction) - * @param newValue the new log context value, or {@code null} to clear + * @param newValue the new log context value, or {@code null} to clear * @return the previous log context value, or {@code null} if none was set */ public LogContext getAndSet(Object securityKey, LogContext newValue) { @@ -69,7 +69,10 @@ public LogContext getAndSet(Object securityKey, LogContext newValue) { try { return context.get(); } finally { - if (newValue == null) context.remove(); else context.set(newValue); + if (newValue == null) + context.remove(); + else + context.set(newValue); } } } diff --git a/src/main/java/org/jboss/logmanager/WrappedExtLogRecord.java b/src/main/java/org/jboss/logmanager/WrappedExtLogRecord.java index 5e79b18b..7bf00b23 100644 --- a/src/main/java/org/jboss/logmanager/WrappedExtLogRecord.java +++ b/src/main/java/org/jboss/logmanager/WrappedExtLogRecord.java @@ -21,7 +21,6 @@ import java.time.Instant; import java.util.ResourceBundle; - import java.util.logging.Level; import java.util.logging.LogRecord; @@ -84,7 +83,7 @@ public void setSequenceNumber(final long seq) { } public String getSourceClassName() { - if (! resolved) { + if (!resolved) { resolve(); } return super.getSourceClassName(); @@ -97,7 +96,7 @@ public void setSourceClassName(final String sourceClassName) { } public String getSourceMethodName() { - if (! resolved) { + if (!resolved) { resolve(); } return super.getSourceMethodName(); @@ -126,7 +125,7 @@ private void resolve() { } public int getSourceLineNumber() { - if (! resolved) { + if (!resolved) { resolve(); } return super.getSourceLineNumber(); @@ -138,7 +137,7 @@ public void setSourceLineNumber(final int sourceLineNumber) { } public String getSourceFileName() { - if (! resolved) { + if (!resolved) { resolve(); } return super.getSourceFileName(); diff --git a/src/main/java/org/jboss/logmanager/configuration/ContextConfiguration.java b/src/main/java/org/jboss/logmanager/configuration/ContextConfiguration.java index 3ada8256..3fd831cc 100644 --- a/src/main/java/org/jboss/logmanager/configuration/ContextConfiguration.java +++ b/src/main/java/org/jboss/logmanager/configuration/ContextConfiguration.java @@ -46,7 +46,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"UnusedReturnValue", "unused"}) +@SuppressWarnings({ "UnusedReturnValue", "unused" }) public class ContextConfiguration { public static final Logger.AttachmentKey CONTEXT_CONFIGURATION_KEY = new Logger.AttachmentKey<>(); private final Map> errorManagers; diff --git a/src/main/java/org/jboss/logmanager/configuration/DefaultLogContextConfigurator.java b/src/main/java/org/jboss/logmanager/configuration/DefaultLogContextConfigurator.java index 8fed9f01..de004fdc 100644 --- a/src/main/java/org/jboss/logmanager/configuration/DefaultLogContextConfigurator.java +++ b/src/main/java/org/jboss/logmanager/configuration/DefaultLogContextConfigurator.java @@ -50,7 +50,8 @@ * Locating the {@code logging.properties} happens in the following order: *

    *
  • The {@code logging.configuration} system property is checked
  • - *
  • The current threads {@linkplain ClassLoader#getResourceAsStream(String)} class loader} for a {@code logging.properties}
  • + *
  • The current threads {@linkplain ClassLoader#getResourceAsStream(String)} class loader} for a + * {@code logging.properties}
  • *
  • Finally {@link Class#getResourceAsStream(String)} is used to locate a {@code logging.properties}
  • *
*

@@ -79,7 +80,8 @@ public void configure(final LogContext logContext, final InputStream inputStream serviceLoader.next().configure(logContext, inputStream); } else { // Configure a default console handler, pattern formatter and associated with the root logger - final ConsoleHandler handler = new ConsoleHandler(new PatternFormatter("%d{yyyy-MM-dd'T'HH:mm:ssXXX} %-5p [%c] (%t) %s%e%n")); + final ConsoleHandler handler = new ConsoleHandler( + new PatternFormatter("%d{yyyy-MM-dd'T'HH:mm:ssXXX} %-5p [%c] (%t) %s%e%n")); handler.setLevel(Level.INFO); handler.setAutoFlush(true); final Logger rootLogger = logContext.getLogger(""); @@ -91,17 +93,20 @@ public void configure(final LogContext logContext, final InputStream inputStream private static InputStream findConfiguration() { final String propLoc = System.getProperty("logging.configuration"); - if (propLoc != null) try { - return new URL(propLoc).openStream(); - } catch (IOException e) { - StandardOutputStreams.printError("Unable to read the logging configuration from '%s' (%s)%n", propLoc, e); - } + if (propLoc != null) + try { + return new URL(propLoc).openStream(); + } catch (IOException e) { + StandardOutputStreams.printError("Unable to read the logging configuration from '%s' (%s)%n", propLoc, e); + } final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - if (tccl != null) try { - final InputStream stream = tccl.getResourceAsStream("logging.properties"); - if (stream != null) return stream; - } catch (Exception ignore) { - } + if (tccl != null) + try { + final InputStream stream = tccl.getResourceAsStream("logging.properties"); + if (stream != null) + return stream; + } catch (Exception ignore) { + } return DefaultLogContextConfigurator.class.getResourceAsStream("logging.properties"); } } diff --git a/src/main/java/org/jboss/logmanager/configuration/ObjectBuilder.java b/src/main/java/org/jboss/logmanager/configuration/ObjectBuilder.java index 1b96a236..70b55d02 100644 --- a/src/main/java/org/jboss/logmanager/configuration/ObjectBuilder.java +++ b/src/main/java/org/jboss/logmanager/configuration/ObjectBuilder.java @@ -42,7 +42,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"UnusedReturnValue"}) +@SuppressWarnings({ "UnusedReturnValue" }) class ObjectBuilder { private final LogContext logContext; @@ -56,7 +56,7 @@ class ObjectBuilder { private String moduleName; private ObjectBuilder(final LogContext logContext, final ContextConfiguration contextConfiguration, - final Class baseClass, final String className) { + final Class baseClass, final String className) { this.logContext = logContext; this.contextConfiguration = contextConfiguration; this.baseClass = baseClass; @@ -78,7 +78,7 @@ private ObjectBuilder(final LogContext logContext, final ContextConfiguration co * @return a new {@link ObjectBuilder} */ static ObjectBuilder of(final LogContext logContext, final ContextConfiguration contextConfiguration, - final Class baseClass, final String className) { + final Class baseClass, final String className) { return new ObjectBuilder<>(logContext, contextConfiguration, baseClass, className); } @@ -190,7 +190,8 @@ Supplier build() { final String property = entry.getKey(); final Class type = getConstructorPropertyType(actualClass, property); if (type == null) { - throw new IllegalArgumentException(String.format("No property named \"%s\" in \"%s\"", property, className)); + throw new IllegalArgumentException( + String.format("No property named \"%s\" in \"%s\"", property, className)); } paramTypes[i] = type; params[i] = getValue(actualClass, property, type, entry.getValue()); @@ -208,12 +209,14 @@ Supplier build() { for (Map.Entry entry : properties.entrySet()) { final Method method = getPropertySetter(actualClass, entry.getKey()); if (method == null) { - throw new IllegalArgumentException(String.format("Failed to locate setter for property \"%s\" on type \"%s\"", entry.getKey(), className)); + throw new IllegalArgumentException(String + .format("Failed to locate setter for property \"%s\" on type \"%s\"", entry.getKey(), className)); } // Get the value type for the setter Class type = getPropertyType(method); if (type == null) { - throw new IllegalArgumentException(String.format("Failed to determine type for setter \"%s\" on type \"%s\"", method.getName(), className)); + throw new IllegalArgumentException(String + .format("Failed to determine type for setter \"%s\" on type \"%s\"", method.getName(), className)); } setters.put(method, getValue(actualClass, entry.getKey(), type, entry.getValue())); } @@ -225,7 +228,8 @@ Supplier build() { final Method method = actualClass.getMethod(methodName, value.type); setters.put(method, value.value.get()); } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(String.format("Failed to find setter method for property \"%s\" on type \"%s\"", value.name, className), e); + throw new IllegalArgumentException(String.format( + "Failed to find setter method for property \"%s\" on type \"%s\"", value.name, className), e); } } @@ -235,7 +239,9 @@ Supplier build() { try { postConstruct.add(actualClass.getMethod(methodName)); } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(String.format("Failed to find post construct method \"%s\" on type \"%s\"", methodName, className), e); + throw new IllegalArgumentException( + String.format("Failed to find post construct method \"%s\" on type \"%s\"", methodName, className), + e); } } try { @@ -261,7 +267,8 @@ Supplier build() { private Object getValue(final Class objClass, final String propertyName, final Class paramType, final String value) { if (value == null) { if (paramType.isPrimitive()) { - throw new IllegalArgumentException(String.format("Cannot assign null value to primitive property \"%s\" of %s", propertyName, objClass)); + throw new IllegalArgumentException( + String.format("Cannot assign null value to primitive property \"%s\" of %s", propertyName, objClass)); } return null; } @@ -338,7 +345,8 @@ private static Class getConstructorPropertyType(Class clazz, String proper private static Method getPropertySetter(Class clazz, String propertyName) { final String set = getPropertySetterName(propertyName); for (Method method : clazz.getMethods()) { - if ((method.getName().equals(set) && Modifier.isPublic(method.getModifiers())) && method.getParameterTypes().length == 1) { + if ((method.getName().equals(set) && Modifier.isPublic(method.getModifiers())) + && method.getParameterTypes().length == 1) { return method; } } @@ -349,7 +357,8 @@ private static Method getPropertyGetter(Class clazz, String propertyName) { final String upperPropertyName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); final Pattern pattern = Pattern.compile("(get|has|is)(" + Pattern.quote(upperPropertyName) + ")"); for (Method method : clazz.getMethods()) { - if ((pattern.matcher(method.getName()).matches() && Modifier.isPublic(method.getModifiers())) && method.getParameterTypes().length == 0) { + if ((pattern.matcher(method.getName()).matches() && Modifier.isPublic(method.getModifiers())) + && method.getParameterTypes().length == 0) { return method; } } diff --git a/src/main/java/org/jboss/logmanager/configuration/PropertyConfigurator.java b/src/main/java/org/jboss/logmanager/configuration/PropertyConfigurator.java index f46e5df8..f0483431 100644 --- a/src/main/java/org/jboss/logmanager/configuration/PropertyConfigurator.java +++ b/src/main/java/org/jboss/logmanager/configuration/PropertyConfigurator.java @@ -32,14 +32,15 @@ import java.util.logging.Level; import java.util.logging.Logger; -import io.smallrye.common.constraint.Assert; -import io.smallrye.common.expression.Expression; import org.jboss.logmanager.LogContext; import org.jboss.logmanager.StandardOutputStreams; import org.jboss.logmanager.configuration.filters.FilterExpressions; import org.jboss.logmanager.filters.AcceptAllFilter; import org.jboss.logmanager.filters.DenyAllFilter; +import io.smallrye.common.constraint.Assert; +import io.smallrye.common.expression.Expression; + /** * A utility to parse a {@code logging.properties} file and configure a {@link LogContext}. * @@ -71,8 +72,7 @@ private PropertyConfigurator(final LogContext logContext, final Properties prope public static void configure(final LogContext logContext, final Properties properties) { final PropertyConfigurator config = new PropertyConfigurator( Assert.checkNotNullParam("logContext", logContext), - Assert.checkNotNullParam("properties", properties) - ); + Assert.checkNotNullParam("properties", properties)); config.doConfigure(); } @@ -105,12 +105,14 @@ private void doConfigure() { } } - @SuppressWarnings({"ConstantConditions", "CastCanBeRemovedNarrowingVariableType"}) + @SuppressWarnings({ "ConstantConditions", "CastCanBeRemovedNarrowingVariableType" }) private void configureLogger(final String loggerName) { - /*if (logContext.getLoggerIfExists(loggerName) != null) { - // duplicate - return; - } */ + /* + * if (logContext.getLoggerIfExists(loggerName) != null) { + * // duplicate + * return; + * } + */ final Logger logger = logContext.getLogger(loggerName); // Get logger level @@ -159,7 +161,8 @@ private boolean configureHandler(final String handlerName) { return false; } - final ObjectBuilder handlerBuilder = ObjectBuilder.of(logContext, contextConfiguration, Handler.class, className) + final ObjectBuilder handlerBuilder = ObjectBuilder + .of(logContext, contextConfiguration, Handler.class, className) .setModuleName(getStringProperty(getKey("handler", handlerName, "module"))) .addPostConstructMethods(getStringCsvArray(getKey("handler", handlerName, "postConfiguration"))); @@ -233,7 +236,8 @@ private boolean configureFormatter(final String formatterName) { StandardOutputStreams.printError("Formatter %s is not defined%n", formatterName); return false; } - final ObjectBuilder formatterBuilder = ObjectBuilder.of(logContext, contextConfiguration, Formatter.class, className) + final ObjectBuilder formatterBuilder = ObjectBuilder + .of(logContext, contextConfiguration, Formatter.class, className) .setModuleName(getStringProperty(getKey("formatter", formatterName, "module"))) .addPostConstructMethods(getStringCsvArray(getKey("formatter", formatterName, "postConfiguration"))); configureProperties(formatterBuilder, "formatter", formatterName); @@ -251,7 +255,8 @@ private boolean configureErrorManager(final String errorManagerName) { StandardOutputStreams.printError("Error manager %s is not defined%n", errorManagerName); return false; } - final ObjectBuilder errorManagerBuilder = ObjectBuilder.of(logContext, contextConfiguration, ErrorManager.class, className) + final ObjectBuilder errorManagerBuilder = ObjectBuilder + .of(logContext, contextConfiguration, ErrorManager.class, className) .setModuleName(getStringProperty(getKey("errorManager", errorManagerName, "module"))) .addPostConstructMethods(getStringCsvArray(getKey("errorManager", errorManagerName, "postConfiguration"))); configureProperties(errorManagerBuilder, "errorManager", errorManagerName); @@ -277,7 +282,8 @@ private boolean configureFilter(final String filterName) { contextConfiguration.addFilter(filterName, DenyAllFilter::getInstance); } else { // We assume we're a defined filter - final ObjectBuilder filterBuilder = ObjectBuilder.of(logContext, contextConfiguration, Filter.class, filterValue) + final ObjectBuilder filterBuilder = ObjectBuilder + .of(logContext, contextConfiguration, Filter.class, filterValue) .setModuleName(getStringProperty(getKey("filter", filterName, "module"))) .addPostConstructMethods(getStringCsvArray(getKey("filter", filterName, "postConfiguration"))); configureProperties(filterBuilder, "errorManager", filterName); @@ -335,14 +341,16 @@ private void configureProperties(final ObjectBuilder builder, final String pr final String[] constructorPropertyNames = getStringCsvArray(getKey(prefix, name, "constructorProperties")); for (String propertyName : constructorPropertyNames) { final String valueString = getStringProperty(getKey(prefix, name, propertyName), false, true); - if (valueString != null) builder.addConstructorProperty(propertyName, valueString); + if (valueString != null) + builder.addConstructorProperty(propertyName, valueString); } // Next configure setter properties final String[] propertyNames = getStringCsvArray(getKey(prefix, name, "properties")); for (String propertyName : propertyNames) { final String valueString = getStringProperty(getKey(prefix, name, propertyName), false, true); - if (valueString != null) builder.addProperty(propertyName, valueString); + if (valueString != null) + builder.addProperty(propertyName, valueString); } } diff --git a/src/main/java/org/jboss/logmanager/configuration/filters/FilterExpressions.java b/src/main/java/org/jboss/logmanager/configuration/filters/FilterExpressions.java index 7cd54b05..ce8361ee 100644 --- a/src/main/java/org/jboss/logmanager/configuration/filters/FilterExpressions.java +++ b/src/main/java/org/jboss/logmanager/configuration/filters/FilterExpressions.java @@ -75,7 +75,8 @@ public static Filter parse(final LogContext logContext, final String expression) return parseFilterExpression(logContext, iterator, true); } - private static Filter parseFilterExpression(final LogContext logContext, final Iterator iterator, final boolean outermost) { + private static Filter parseFilterExpression(final LogContext logContext, final Iterator iterator, + final boolean outermost) { if (!iterator.hasNext()) { if (outermost) { return null; @@ -175,7 +176,8 @@ private static boolean expect(final String trueToken, final String falseToken, f final String next = hasNext ? iterator.next() : null; final boolean result; if (!hasNext || !((result = trueToken.equals(next)) || falseToken.equals(next))) { - throw new IllegalArgumentException("Expected '" + trueToken + "' or '" + falseToken + "' next in filter expression"); + throw new IllegalArgumentException( + "Expected '" + trueToken + "' or '" + falseToken + "' next in filter expression"); } return result; } @@ -190,7 +192,6 @@ private static IllegalArgumentException endOfExpression() { return new IllegalArgumentException("Unexpected end of filter expression"); } - @SuppressWarnings("UnusedAssignment") private static List tokens(final String source) { final List tokens = new ArrayList<>(); diff --git a/src/main/java/org/jboss/logmanager/errormanager/HandlerErrorManager.java b/src/main/java/org/jboss/logmanager/errormanager/HandlerErrorManager.java index e13406a9..3ce25643 100644 --- a/src/main/java/org/jboss/logmanager/errormanager/HandlerErrorManager.java +++ b/src/main/java/org/jboss/logmanager/errormanager/HandlerErrorManager.java @@ -2,9 +2,10 @@ import java.util.logging.Handler; -import io.smallrye.common.constraint.Assert; import org.jboss.logmanager.ExtErrorManager; +import io.smallrye.common.constraint.Assert; + /** * An error manager which publishes errors to a handler. */ diff --git a/src/main/java/org/jboss/logmanager/filters/AcceptAllFilter.java b/src/main/java/org/jboss/logmanager/filters/AcceptAllFilter.java index 45a3f285..b0ea7c0a 100644 --- a/src/main/java/org/jboss/logmanager/filters/AcceptAllFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/AcceptAllFilter.java @@ -26,7 +26,8 @@ * An accept-all filter. */ public final class AcceptAllFilter implements Filter { - private AcceptAllFilter() {} + private AcceptAllFilter() { + } private static final AcceptAllFilter INSTANCE = new AcceptAllFilter(); diff --git a/src/main/java/org/jboss/logmanager/filters/AllFilter.java b/src/main/java/org/jboss/logmanager/filters/AllFilter.java index 61a7a71b..bbcb458b 100644 --- a/src/main/java/org/jboss/logmanager/filters/AllFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/AllFilter.java @@ -20,13 +20,12 @@ package org.jboss.logmanager.filters; import java.util.Iterator; - import java.util.logging.Filter; import java.util.logging.LogRecord; /** - * A filter consisting of several filters in a chain. If any filter finds the log message to be unloggable, - * the message will not be logged and subsequent filters will not be checked. If there are no nested filters, + * A filter consisting of several filters in a chain. If any filter finds the log message to be unloggable, + * the message will not be logged and subsequent filters will not be checked. If there are no nested filters, * this instance always returns {@code true}. */ public final class AllFilter implements Filter { @@ -81,7 +80,7 @@ private static Filter[] unroll(Iterator iter, int cnt) { */ public boolean isLoggable(final LogRecord record) { for (Filter filter : filters) { - if (! filter.isLoggable(record)) { + if (!filter.isLoggable(record)) { return false; } } diff --git a/src/main/java/org/jboss/logmanager/filters/AnyFilter.java b/src/main/java/org/jboss/logmanager/filters/AnyFilter.java index 92ffffd1..176a7ee7 100644 --- a/src/main/java/org/jboss/logmanager/filters/AnyFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/AnyFilter.java @@ -20,13 +20,12 @@ package org.jboss.logmanager.filters; import java.util.Iterator; - import java.util.logging.Filter; import java.util.logging.LogRecord; /** - * A filter consisting of several filters in a chain. If any filter finds the log message to be loggable, - * the message will be logged and subsequent filters will not be checked. If there are no nested filters, this + * A filter consisting of several filters in a chain. If any filter finds the log message to be loggable, + * the message will be logged and subsequent filters will not be checked. If there are no nested filters, this * instance always returns {@code false}. */ public final class AnyFilter implements Filter { @@ -87,4 +86,4 @@ public boolean isLoggable(final LogRecord record) { } return false; } -} \ No newline at end of file +} diff --git a/src/main/java/org/jboss/logmanager/filters/DenyAllFilter.java b/src/main/java/org/jboss/logmanager/filters/DenyAllFilter.java index 7dd6b983..700f5681 100644 --- a/src/main/java/org/jboss/logmanager/filters/DenyAllFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/DenyAllFilter.java @@ -26,7 +26,8 @@ * A deny-all filter. */ public final class DenyAllFilter implements Filter { - private DenyAllFilter() {} + private DenyAllFilter() { + } private static final DenyAllFilter INSTANCE = new DenyAllFilter(); diff --git a/src/main/java/org/jboss/logmanager/filters/InvertFilter.java b/src/main/java/org/jboss/logmanager/filters/InvertFilter.java index 15a94987..22b92490 100644 --- a/src/main/java/org/jboss/logmanager/filters/InvertFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/InvertFilter.java @@ -44,6 +44,6 @@ public InvertFilter(final Filter target) { * @return {@code true} if the target filter returns {@code false}, {@code false} otherwise */ public boolean isLoggable(final LogRecord record) { - return ! target.isLoggable(record); + return !target.isLoggable(record); } } diff --git a/src/main/java/org/jboss/logmanager/filters/LevelFilter.java b/src/main/java/org/jboss/logmanager/filters/LevelFilter.java index 80f502f0..6d07c2e8 100644 --- a/src/main/java/org/jboss/logmanager/filters/LevelFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/LevelFilter.java @@ -23,7 +23,6 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; - import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; @@ -61,4 +60,4 @@ public LevelFilter(final Collection includedLevels) { public boolean isLoggable(final LogRecord record) { return includedLevels.contains(record.getLevel()); } -} \ No newline at end of file +} diff --git a/src/main/java/org/jboss/logmanager/filters/LevelRangeFilter.java b/src/main/java/org/jboss/logmanager/filters/LevelRangeFilter.java index c55890b5..71829a5e 100644 --- a/src/main/java/org/jboss/logmanager/filters/LevelRangeFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/LevelRangeFilter.java @@ -35,9 +35,9 @@ public final class LevelRangeFilter implements Filter { /** * Create a new instance. * - * @param min the minimum (least severe) level, inclusive + * @param min the minimum (least severe) level, inclusive * @param minInclusive {@code true} if the {@code min} value is inclusive, {@code false} if it is exclusive - * @param max the maximum (most severe) level, inclusive + * @param max the maximum (most severe) level, inclusive * @param maxInclusive {@code true} if the {@code max} value is inclusive, {@code false} if it is exclusive */ public LevelRangeFilter(final Level min, final boolean minInclusive, final Level max, final boolean maxInclusive) { diff --git a/src/main/java/org/jboss/logmanager/filters/RegexFilter.java b/src/main/java/org/jboss/logmanager/filters/RegexFilter.java index 407e72f0..98f12d1c 100644 --- a/src/main/java/org/jboss/logmanager/filters/RegexFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/RegexFilter.java @@ -20,15 +20,14 @@ package org.jboss.logmanager.filters; import java.text.MessageFormat; +import java.util.logging.Filter; import java.util.logging.LogRecord; import java.util.regex.Pattern; -import java.util.logging.Filter; - import org.jboss.logmanager.ExtLogRecord; /** - * A regular-expression-based filter. Used to exclude log records which match or don't match the expression. The + * A regular-expression-based filter. Used to exclude log records which match or don't match the expression. The * regular expression is checked against the raw (unformatted) message. */ public final class RegexFilter implements Filter { diff --git a/src/main/java/org/jboss/logmanager/filters/SubstituteFilter.java b/src/main/java/org/jboss/logmanager/filters/SubstituteFilter.java index f7ac43f6..2760dff8 100644 --- a/src/main/java/org/jboss/logmanager/filters/SubstituteFilter.java +++ b/src/main/java/org/jboss/logmanager/filters/SubstituteFilter.java @@ -20,12 +20,11 @@ package org.jboss.logmanager.filters; import java.text.MessageFormat; +import java.util.logging.Filter; import java.util.logging.LogRecord; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.logging.Filter; - import org.jboss.logmanager.ExtLogRecord; import org.jboss.logmanager.ExtLogRecord.FormatStyle; @@ -41,9 +40,9 @@ public final class SubstituteFilter implements Filter { /** * Construct a new instance. * - * @param pattern the pattern to match + * @param pattern the pattern to match * @param replacement the string replacement - * @param replaceAll {@code true} if all occurrences should be replaced; {@code false} if only the first occurrence + * @param replaceAll {@code true} if all occurrences should be replaced; {@code false} if only the first occurrence */ public SubstituteFilter(final Pattern pattern, final String replacement, final boolean replaceAll) { this.pattern = pattern; @@ -55,8 +54,8 @@ public SubstituteFilter(final Pattern pattern, final String replacement, final b * Construct a new instance. * * @param patternString the pattern to match - * @param replacement the string replacement - * @param replaceAll {@code true} if all occurrences should be replaced; {@code false} if only the first occurrence + * @param replacement the string replacement + * @param replaceAll {@code true} if all occurrences should be replaced; {@code false} if only the first occurrence */ public SubstituteFilter(final String patternString, final String replacement, final boolean replaceAll) { this(Pattern.compile(patternString), replacement, replaceAll); diff --git a/src/main/java/org/jboss/logmanager/formatters/ColorMap.java b/src/main/java/org/jboss/logmanager/formatters/ColorMap.java index 87d0634d..fc9fd1b1 100644 --- a/src/main/java/org/jboss/logmanager/formatters/ColorMap.java +++ b/src/main/java/org/jboss/logmanager/formatters/ColorMap.java @@ -18,6 +18,7 @@ */ package org.jboss.logmanager.formatters; + import java.util.Collections; import java.util.HashMap; import java.util.Locale; @@ -51,7 +52,6 @@ public class ColorMap { private static final String CLEAR = "\033[0m"; - static final boolean SUPPORTS_COLOR; private static final Map codes; @@ -65,7 +65,7 @@ public class ColorMap { private final NavigableMap levelMap; - private ColorMap(NavigableMap levelMap) { + private ColorMap(NavigableMap levelMap) { this.levelMap = levelMap; } @@ -214,7 +214,6 @@ static ColorMap create(String expression) { continue; } - try { int i = Integer.parseInt(parts[0]); levelMap.put(i, color); @@ -241,7 +240,7 @@ String getCode(String name, java.util.logging.Level level) { String lower = name.toLowerCase(Locale.ROOT); if (lower.equals(LEVEL_NAME)) { - Map.Entry entry = levelMap.floorEntry(level.intValue()); + Map.Entry entry = levelMap.floorEntry(level.intValue()); return entry != null ? entry.getValue() : null; } diff --git a/src/main/java/org/jboss/logmanager/formatters/ColorPatternFormatter.java b/src/main/java/org/jboss/logmanager/formatters/ColorPatternFormatter.java index acf69188..a6b65b59 100644 --- a/src/main/java/org/jboss/logmanager/formatters/ColorPatternFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/ColorPatternFormatter.java @@ -19,14 +19,14 @@ package org.jboss.logmanager.formatters; -import org.jboss.logmanager.ExtLogRecord; -import org.jboss.logmanager.Level; -import org.jboss.logmanager.handlers.ConsoleHandler; +import static java.lang.Math.abs; import java.util.logging.Formatter; import java.util.logging.LogRecord; -import static java.lang.Math.abs; +import org.jboss.logmanager.ExtLogRecord; +import org.jboss.logmanager.Level; +import org.jboss.logmanager.handlers.ConsoleHandler; /** * A pattern formatter that colorizes the pattern in a fixed manner. @@ -124,7 +124,8 @@ private String colorizePlain(final String str) { public String formatMessage(final LogRecord logRecord) { if (logRecord instanceof ExtLogRecord) { final ExtLogRecord record = (ExtLogRecord) logRecord; - if (record.getFormatStyle() != ExtLogRecord.FormatStyle.PRINTF || record.getParameters() == null || record.getParameters().length == 0) { + if (record.getFormatStyle() != ExtLogRecord.FormatStyle.PRINTF || record.getParameters() == null + || record.getParameters().length == 0) { return colorizePlain(super.formatMessage(record)); } return printf.format(record.getMessage(), record.getParameters()); diff --git a/src/main/java/org/jboss/logmanager/formatters/ColorPrintf.java b/src/main/java/org/jboss/logmanager/formatters/ColorPrintf.java index 71ec0e5c..a274e424 100644 --- a/src/main/java/org/jboss/logmanager/formatters/ColorPrintf.java +++ b/src/main/java/org/jboss/logmanager/formatters/ColorPrintf.java @@ -44,23 +44,26 @@ public StringBuilder formatDirect(final StringBuilder destination, final String return destination; } - protected void formatTimeTextField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, final String[] symbols, final GeneralFlags genFlags, final int width) { + protected void formatTimeTextField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, + final String[] symbols, final GeneralFlags genFlags, final int width) { super.formatTimeTextField(target, ta, field, symbols, genFlags, width); } - protected void formatTimeZoneId(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, final int width) { + protected void formatTimeZoneId(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, + final int width) { super.formatTimeZoneId(target, ta, genFlags, width); } - protected void formatTimeZoneOffset(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, final int width) { + protected void formatTimeZoneOffset(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, + final int width) { super.formatTimeZoneOffset(target, ta, genFlags, width); } - protected void formatTimeField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, final GeneralFlags genFlags, final int width, final int zeroPad) { + protected void formatTimeField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, + final GeneralFlags genFlags, final int width, final int zeroPad) { super.formatTimeField(target, ta, field, genFlags, width, zeroPad); } - protected void formatPercent(final StringBuilder target) { super.formatPercent(target); } @@ -69,11 +72,13 @@ protected void formatLineSeparator(final StringBuilder target) { super.formatLineSeparator(target); } - protected void formatFormattableString(final StringBuilder target, final Formattable formattable, final GeneralFlags genFlags, final int width, final int precision) { + protected void formatFormattableString(final StringBuilder target, final Formattable formattable, + final GeneralFlags genFlags, final int width, final int precision) { super.formatFormattableString(target, formattable, genFlags, width, precision); } - protected void formatPlainString(final StringBuilder target, final Object item, final GeneralFlags genFlags, final int width, final int precision) { + protected void formatPlainString(final StringBuilder target, final Object item, final GeneralFlags genFlags, + final int width, final int precision) { if (item instanceof Class || item instanceof Executable || item instanceof Field) { ColorUtil.startFgColor(target, trueColor, 0xff >>> darken, 0xff >>> darken, 0xdd >>> darken); } else if (item instanceof UUID) { @@ -85,39 +90,48 @@ protected void formatPlainString(final StringBuilder target, final Object item, ColorUtil.endFgColor(target); } - protected void formatBoolean(final StringBuilder target, final Object item, final GeneralFlags genFlags, final int width, final int precision) { + protected void formatBoolean(final StringBuilder target, final Object item, final GeneralFlags genFlags, final int width, + final int precision) { super.formatBoolean(target, item, genFlags, width, precision); } - protected void formatHashCode(final StringBuilder target, final Object item, final GeneralFlags genFlags, final int width, final int precision) { + protected void formatHashCode(final StringBuilder target, final Object item, final GeneralFlags genFlags, final int width, + final int precision) { super.formatHashCode(target, item, genFlags, width, precision); } - protected void formatCharacter(final StringBuilder target, final int codePoint, final GeneralFlags genFlags, final int width, final int precision) { + protected void formatCharacter(final StringBuilder target, final int codePoint, final GeneralFlags genFlags, + final int width, final int precision) { super.formatCharacter(target, codePoint, genFlags, width, precision); } - protected void formatDecimalInteger(final StringBuilder target, final Number item, final GeneralFlags genFlags, final NumericFlags numFlags, final int width) { + protected void formatDecimalInteger(final StringBuilder target, final Number item, final GeneralFlags genFlags, + final NumericFlags numFlags, final int width) { super.formatDecimalInteger(target, item, genFlags, numFlags, width); } - protected void formatOctalInteger(final StringBuilder target, final Number item, final GeneralFlags genFlags, final NumericFlags numFlags, final int width) { + protected void formatOctalInteger(final StringBuilder target, final Number item, final GeneralFlags genFlags, + final NumericFlags numFlags, final int width) { super.formatOctalInteger(target, item, genFlags, numFlags, width); } - protected void formatHexInteger(final StringBuilder target, final Number item, final GeneralFlags genFlags, final NumericFlags numFlags, final int width) { + protected void formatHexInteger(final StringBuilder target, final Number item, final GeneralFlags genFlags, + final NumericFlags numFlags, final int width) { super.formatHexInteger(target, item, genFlags, numFlags, width); } - protected void formatFloatingPointSci(final StringBuilder target, final Number item, final GeneralFlags genFlags, final NumericFlags numFlags, final int width, final int precision) { + protected void formatFloatingPointSci(final StringBuilder target, final Number item, final GeneralFlags genFlags, + final NumericFlags numFlags, final int width, final int precision) { super.formatFloatingPointSci(target, item, genFlags, numFlags, width, precision); } - protected void formatFloatingPointDecimal(final StringBuilder target, final Number item, final GeneralFlags genFlags, final NumericFlags numFlags, final int width, final int precision) { + protected void formatFloatingPointDecimal(final StringBuilder target, final Number item, final GeneralFlags genFlags, + final NumericFlags numFlags, final int width, final int precision) { super.formatFloatingPointDecimal(target, item, genFlags, numFlags, width, precision); } - protected void formatFloatingPointGeneral(final StringBuilder target, final Number item, final GeneralFlags genFlags, final NumericFlags numFlags, final int width, final int precision) { + protected void formatFloatingPointGeneral(final StringBuilder target, final Number item, final GeneralFlags genFlags, + final NumericFlags numFlags, final int width, final int precision) { super.formatFloatingPointGeneral(target, item, genFlags, numFlags, width, precision); } } diff --git a/src/main/java/org/jboss/logmanager/formatters/ColorUtil.java b/src/main/java/org/jboss/logmanager/formatters/ColorUtil.java index ebc4449a..faa80d6e 100644 --- a/src/main/java/org/jboss/logmanager/formatters/ColorUtil.java +++ b/src/main/java/org/jboss/logmanager/formatters/ColorUtil.java @@ -23,7 +23,8 @@ * This is a throwaway temp class. */ final class ColorUtil { - private ColorUtil() {} + private ColorUtil() { + } static StringBuilder startFgColor(StringBuilder target, boolean trueColor, int r, int g, int b) { return startColor(target, 38, trueColor, r, g, b); @@ -35,13 +36,15 @@ static StringBuilder startBgColor(StringBuilder target, boolean trueColor, int r static StringBuilder startColor(StringBuilder target, int mode, boolean trueColor, int r, int g, int b) { if (trueColor) { - return target.appendCodePoint(27).append('[').append(mode).append(';').append(2).append(';').append(clip(r)).append(';').append(clip(g)).append(';').append(clip(b)).append('m'); + return target.appendCodePoint(27).append('[').append(mode).append(';').append(2).append(';').append(clip(r)) + .append(';').append(clip(g)).append(';').append(clip(b)).append('m'); } else { int ar = (5 * clip(r)) / 255; int ag = (5 * clip(g)) / 255; int ab = (5 * clip(b)) / 255; int col = 16 + 36 * ar + 6 * ag + ab; - return target.appendCodePoint(27).append('[').append(mode).append(';').append('5').append(';').append(col).append('m'); + return target.appendCodePoint(27).append('[').append(mode).append(';').append('5').append(';').append(col) + .append('m'); } } diff --git a/src/main/java/org/jboss/logmanager/formatters/FlagSet.java b/src/main/java/org/jboss/logmanager/formatters/FlagSet.java index 578524fd..6e7725b3 100644 --- a/src/main/java/org/jboss/logmanager/formatters/FlagSet.java +++ b/src/main/java/org/jboss/logmanager/formatters/FlagSet.java @@ -43,7 +43,8 @@ public boolean hasNext() { } public E next() { - if (! hasNext()) throw new NoSuchElementException(); + if (!hasNext()) + throw new NoSuchElementException(); int lob = Integer.lowestOneBit(bits); bits &= ~lob; return values()[Integer.numberOfTrailingZeros(lob)]; @@ -99,7 +100,7 @@ public int hashCode() { } public boolean equals(final Object o) { - return o.getClass() == getClass() && ((FlagSet)o).value == value || super.equals(o); + return o.getClass() == getClass() && ((FlagSet) o).value == value || super.equals(o); } public void forbid(final E flag) { @@ -109,7 +110,7 @@ public void forbid(final E flag) { } public void forbidAll() { - if (! isEmpty()) { + if (!isEmpty()) { throw notAllowed(this); } } diff --git a/src/main/java/org/jboss/logmanager/formatters/FormatStep.java b/src/main/java/org/jboss/logmanager/formatters/FormatStep.java index f1a01f85..cecf6b15 100644 --- a/src/main/java/org/jboss/logmanager/formatters/FormatStep.java +++ b/src/main/java/org/jboss/logmanager/formatters/FormatStep.java @@ -1,9 +1,9 @@ package org.jboss.logmanager.formatters; -import org.jboss.logmanager.ExtLogRecord; - import java.util.logging.Formatter; +import org.jboss.logmanager.ExtLogRecord; + /** * A single format step which handles some part of rendering a log record. */ @@ -13,7 +13,7 @@ public interface FormatStep { * Render a part of the log record. * * @param builder the string builder to append to - * @param record the record being rendered + * @param record the record being rendered */ void render(StringBuilder builder, ExtLogRecord record); @@ -21,15 +21,15 @@ public interface FormatStep { * Render a part of the log record to the given formatter. * * @param formatter the formatter to render to - * @param builder the string builder to append to - * @param record the record being rendered + * @param builder the string builder to append to + * @param record the record being rendered */ default void render(Formatter formatter, StringBuilder builder, ExtLogRecord record) { render(builder, record); } /** - * Emit an estimate of the length of data which this step will produce. The more accurate the estimate, the + * Emit an estimate of the length of data which this step will produce. The more accurate the estimate, the * more likely the format operation will be performant. * * @return an estimate @@ -55,7 +55,7 @@ default ItemType getItemType() { } /** - * An enumeration of the types of items that can be rendered. Note that this enumeration may be expanded + * An enumeration of the types of items that can be rendered. Note that this enumeration may be expanded * in the future, so unknown values should be handled gracefully as if {@link #GENERIC} were used. */ enum ItemType { diff --git a/src/main/java/org/jboss/logmanager/formatters/FormatStringParser.java b/src/main/java/org/jboss/logmanager/formatters/FormatStringParser.java index 7e53ef95..92616ba9 100644 --- a/src/main/java/org/jboss/logmanager/formatters/FormatStringParser.java +++ b/src/main/java/org/jboss/logmanager/formatters/FormatStringParser.java @@ -19,10 +19,10 @@ package org.jboss.logmanager.formatters; -import java.util.regex.Pattern; -import java.util.regex.Matcher; import java.util.ArrayList; import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * A parser which can translate a log4j-style format string into a series of {@code FormatStep} instances. @@ -30,13 +30,13 @@ public final class FormatStringParser { /** - * The regular expression for format strings. Ain't regex grand? + * The regular expression for format strings. Ain't regex grand? */ private static final Pattern pattern = Pattern.compile( - // greedily match all non-format characters - "([^%]++)" + - // match a format string... - "|(?:%" + + // greedily match all non-format characters + "([^%]++)" + + // match a format string... + "|(?:%" + // optional minimum width plus justify flag "(?:(-)?(\\d+))?" + // optional maximum width @@ -45,9 +45,8 @@ public final class FormatStringParser { "(.)" + // an optional argument string "(?:\\{([^}]*)\\})?" + - // end format string - ")" - ); + // end format string + ")"); private FormatStringParser() { } @@ -83,27 +82,33 @@ public static FormatStep[] getSteps(final String formatString, ColorMap colors) final char formatChar = formatCharString.charAt(0); switch (formatChar) { case 'c': { - stepList.add(Formatters.loggerNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, argument)); + stepList.add(Formatters.loggerNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, + argument)); break; } case 'C': { - stepList.add(Formatters.classNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, argument)); + stepList.add(Formatters.classNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, + argument)); break; } case 'd': { - stepList.add(Formatters.dateFormatStep(timeZone, argument, leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add(Formatters.dateFormatStep(timeZone, argument, leftJustify, minimumWidth, truncateBeginning, + maximumWidth)); break; } case 'D': { - stepList.add(Formatters.moduleNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, argument)); + stepList.add(Formatters.moduleNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, + argument)); break; } case 'e': { - stepList.add(Formatters.exceptionFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, argument, false)); + stepList.add(Formatters.exceptionFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, + argument, false)); break; } case 'E': { - stepList.add(Formatters.exceptionFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, argument, true)); + stepList.add(Formatters.exceptionFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, + argument, true)); break; } case 'F': { @@ -111,19 +116,23 @@ public static FormatStep[] getSteps(final String formatString, ColorMap colors) break; } case 'h': { - stepList.add(Formatters.hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, false)); + stepList.add(Formatters.hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, + false)); break; } case 'H': { - stepList.add(Formatters.hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, argument)); + stepList.add(Formatters.hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, + argument)); break; } case 'i': { - stepList.add(Formatters.processIdFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.processIdFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 'k': { - stepList.add(Formatters.resourceKeyFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.resourceKeyFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 'K': { @@ -134,11 +143,13 @@ public static FormatStep[] getSteps(final String formatString, ColorMap colors) break; } case 'l': { - stepList.add(Formatters.locationInformationFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add(Formatters.locationInformationFormatStep(leftJustify, minimumWidth, truncateBeginning, + maximumWidth)); break; } case 'L': { - stepList.add(Formatters.lineNumberFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.lineNumberFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 'm': { @@ -146,15 +157,18 @@ public static FormatStep[] getSteps(final String formatString, ColorMap colors) break; } case 'M': { - stepList.add(Formatters.methodNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.methodNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 'n': { - stepList.add(Formatters.lineSeparatorFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.lineSeparatorFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 'N': { - stepList.add(Formatters.processNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.processNameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 'p': { @@ -162,19 +176,23 @@ public static FormatStep[] getSteps(final String formatString, ColorMap colors) break; } case 'P': { - stepList.add(Formatters.localizedLevelFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add(Formatters.localizedLevelFormatStep(leftJustify, minimumWidth, truncateBeginning, + maximumWidth)); break; } case 'r': { - stepList.add(Formatters.relativeTimeFormatStep(time, leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add(Formatters.relativeTimeFormatStep(time, leftJustify, minimumWidth, truncateBeginning, + maximumWidth)); break; } case 's': { - stepList.add(Formatters.simpleMessageFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.simpleMessageFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 't': { - stepList.add(Formatters.threadFormatStep(argument, leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add(Formatters.threadFormatStep(argument, leftJustify, minimumWidth, truncateBeginning, + maximumWidth)); break; } case 'v': { @@ -183,11 +201,13 @@ public static FormatStep[] getSteps(final String formatString, ColorMap colors) } case 'x': { final int count = argument == null ? 0 : Integer.parseInt(argument); - stepList.add(Formatters.ndcFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, count)); + stepList.add( + Formatters.ndcFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, count)); break; } case 'X': { - stepList.add(Formatters.mdcFormatStep(argument, leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add( + Formatters.mdcFormatStep(argument, leftJustify, minimumWidth, truncateBeginning, maximumWidth)); break; } case 'z': { @@ -196,7 +216,8 @@ public static FormatStep[] getSteps(final String formatString, ColorMap colors) } case '#': case '$': { - stepList.add(Formatters.systemPropertyFormatStep(argument, leftJustify, minimumWidth, truncateBeginning, maximumWidth)); + stepList.add(Formatters.systemPropertyFormatStep(argument, leftJustify, minimumWidth, truncateBeginning, + maximumWidth)); break; } case '%': { diff --git a/src/main/java/org/jboss/logmanager/formatters/Formatters.java b/src/main/java/org/jboss/logmanager/formatters/Formatters.java index 422e8265..a27c17a4 100644 --- a/src/main/java/org/jboss/logmanager/formatters/Formatters.java +++ b/src/main/java/org/jboss/logmanager/formatters/Formatters.java @@ -47,7 +47,7 @@ /** * Formatter utility methods. */ -@SuppressWarnings({"WeakerAccess", "unused"}) +@SuppressWarnings({ "WeakerAccess", "unused" }) public final class Formatters { public static final String THREAD_ID = "id"; @@ -56,7 +56,6 @@ public final class Formatters { private static final String NEW_LINE = String.format("%n"); private static final Pattern PRECISION_INT_PATTERN = Pattern.compile("\\d+"); - private Formatters() { } @@ -100,7 +99,7 @@ public ItemType getItemType() { /** * Apply up to {@code count} trailing segments of the given string to the given {@code builder}. * - * @param count the maximum number of segments to include + * @param count the maximum number of segments to include * @param subject the subject string * @return the substring */ @@ -109,7 +108,7 @@ private static String applySegments(final int count, final String subject) { return subject; } int idx = subject.length() + 1; - for (int i = 0; i < count; i ++) { + for (int i = 0; i < count; i++) { idx = subject.lastIndexOf('.', idx - 1); if (idx == -1) { return subject; @@ -180,9 +179,11 @@ private abstract static class JustifyingFormatStep implements FormatStep { private final int minimumWidth; private final int maximumWidth; - protected JustifyingFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + protected JustifyingFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, + final int maximumWidth) { if (maximumWidth != 0 && minimumWidth > maximumWidth) { - throw new IllegalArgumentException("Specified minimum width may not be greater than the specified maximum width"); + throw new IllegalArgumentException( + "Specified minimum width may not be greater than the specified maximum width"); } if (maximumWidth < 0 || minimumWidth < 0) { throw new IllegalArgumentException("Minimum and maximum widths must not be less than zero"); @@ -216,7 +217,7 @@ public void render(Formatter formatter, StringBuilder builder, ExtLogRecord reco builder.setLength(newLen - overflow); } else { final int spaces = minimumWidth - writtenLen; - for (int i = 0; i < spaces; i ++) { + for (int i = 0; i < spaces; i++) { builder.append(' '); } } @@ -234,7 +235,7 @@ public void render(Formatter formatter, StringBuilder builder, ExtLogRecord reco } else if (len < minimumWidth) { // right justify int spaces = minimumWidth - len; - for (int i = 0; i < spaces; i ++) { + for (int i = 0; i < spaces; i++) { builder.append(' '); } } @@ -259,13 +260,15 @@ private abstract static class SegmentedFormatStep extends JustifyingFormatStep { private final int count; private final String precision; - protected SegmentedFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final int count) { + protected SegmentedFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, + final int maximumWidth, final int count) { super(leftJustify, minimumWidth, truncateBeginning, maximumWidth); this.count = count; precision = null; } - protected SegmentedFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String precision) { + protected SegmentedFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, + final int maximumWidth, final String precision) { super(leftJustify, minimumWidth, truncateBeginning, maximumWidth); this.count = 0; this.precision = precision; @@ -285,13 +288,14 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex /** * Create a format step which emits the logger name with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @param precision the argument used for the logger name, may be {@code null} or contain dots to format the logger name * @return the format */ - public static FormatStep loggerNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final String precision) { + public static FormatStep loggerNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, + final String precision) { return loggerNameFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth, precision); } @@ -307,7 +311,8 @@ public static FormatStep loggerNameFormatStep(final boolean leftJustify, final i * * @return the format */ - public static FormatStep loggerNameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String precision) { + public static FormatStep loggerNameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth, final String precision) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, precision) { public ItemType getItemType() { return ItemType.CATEGORY; @@ -323,13 +328,14 @@ public String getSegmentedSubject(final ExtLogRecord record) { * Create a format step which emits the source class name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @param precision the argument used for the class name, may be {@code null} or contain dots to format the class name * @return the format step */ - public static FormatStep classNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final String precision) { + public static FormatStep classNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, + final String precision) { return classNameFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth, precision); } @@ -346,7 +352,8 @@ public static FormatStep classNameFormatStep(final boolean leftJustify, final in * * @return the format step */ - public static FormatStep classNameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String precision) { + public static FormatStep classNameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth, final String precision) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, precision) { public String getSegmentedSubject(final ExtLogRecord record) { return record.getSourceClassName(); @@ -367,13 +374,14 @@ public ItemType getItemType() { * Create a format step which emits the source module name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @param precision the argument used for the class name, may be {@code null} or contain dots to format the class name * @return the format step */ - public static FormatStep moduleNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final String precision) { + public static FormatStep moduleNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, + final String precision) { return moduleNameFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth, precision); } @@ -390,7 +398,8 @@ public static FormatStep moduleNameFormatStep(final boolean leftJustify, final i * * @return the format step */ - public static FormatStep moduleNameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String precision) { + public static FormatStep moduleNameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth, final String precision) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, precision) { public String getSegmentedSubject(final ExtLogRecord record) { return record.getSourceModuleName(); @@ -411,15 +420,16 @@ public ItemType getItemType() { * Create a format step which emits the source module version with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none - * @param precision the argument used for the class name, may be {@code null} or contain dots to format the - * class name + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param precision the argument used for the class name, may be {@code null} or contain dots to format the + * class name * * @return the format step */ - public static FormatStep moduleVersionFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final String precision) { + public static FormatStep moduleVersionFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, + final String precision) { return new SegmentedFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth, precision) { public String getSegmentedSubject(final ExtLogRecord record) { return record.getSourceModuleVersion(); @@ -439,14 +449,15 @@ public ItemType getItemType() { /** * Create a format step which emits the date of the log record with the given justification rules. * - * @param timeZone the time zone to format to + * @param timeZone the time zone to format to * @param formatString the date format string - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep dateFormatStep(final TimeZone timeZone, final String formatString, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep dateFormatStep(final TimeZone timeZone, final String formatString, final boolean leftJustify, + final int minimumWidth, final int maximumWidth) { return dateFormatStep(timeZone, formatString, leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } @@ -462,10 +473,12 @@ public static FormatStep dateFormatStep(final TimeZone timeZone, final String fo * * @return the format step */ - public static FormatStep dateFormatStep(final TimeZone timeZone, final String formatString, final boolean leftJustify, final int minimumWidth, - final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep dateFormatStep(final TimeZone timeZone, final String formatString, final boolean leftJustify, + final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { - final DateTimeFormatter dtf = DateTimeFormatter.ofPattern(formatString == null ? "yyyy-MM-DD HH:mm:ss,SSS" : formatString); + final DateTimeFormatter dtf = DateTimeFormatter + .ofPattern(formatString == null ? "yyyy-MM-DD HH:mm:ss,SSS" : formatString); public ItemType getItemType() { return ItemType.DATE; @@ -481,12 +494,13 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex * Create a format step which emits the date of the log record with the given justification rules. * * @param formatString the date format string - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep dateFormatStep(final String formatString, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep dateFormatStep(final String formatString, final boolean leftJustify, final int minimumWidth, + final int maximumWidth) { return dateFormatStep(TimeZone.getDefault(), formatString, leftJustify, minimumWidth, maximumWidth); } @@ -494,7 +508,7 @@ public static FormatStep dateFormatStep(final String formatString, final boolean * Create a format step which emits the source file name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -507,13 +521,14 @@ public static FormatStep fileNameFormatStep(final boolean leftJustify, final int * Create a format step which emits the source file name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep fileNameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep fileNameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { builder.append(record.getSourceFileName()); @@ -533,13 +548,14 @@ public ItemType getItemType() { /** * Create a format step which emits the source process name with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep processNameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep processNameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.PROCESS_NAME; @@ -555,13 +571,14 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex * Create a format step which emits the source file line number with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep processIdFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep processIdFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.PROCESS_ID; @@ -576,38 +593,42 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex /** * Create a format step which emits the hostname. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none - * @param qualified {@code true} to use the fully qualified host name, {@code false} to only use the + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param qualified {@code true} to use the fully qualified host name, {@code false} to only use the * @return the format step */ - public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final boolean qualified) { - return qualified ? hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) : new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) { - public ItemType getItemType() { - return ItemType.HOST_NAME; - } + public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth, final boolean qualified) { + return qualified ? hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) + : new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) { + public ItemType getItemType() { + return ItemType.HOST_NAME; + } - public String getSegmentedSubject(final ExtLogRecord record) { - final String hostName = record.getHostName(); - final int idx = hostName.indexOf('.'); - return idx == -1 ? hostName :hostName.substring(0, idx); - } - }; + public String getSegmentedSubject(final ExtLogRecord record) { + final String hostName = record.getHostName(); + final int idx = hostName.indexOf('.'); + return idx == -1 ? hostName : hostName.substring(0, idx); + } + }; } /** * Create a format step which emits the hostname. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none - * @param precision the argument used for the class name, may be {@code null} or contain dots to format the class name + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param precision the argument used for the class name, may be {@code null} or contain dots to format the class + * name * @return the format step */ - public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String precision) { + public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth, final String precision) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) { public ItemType getItemType() { return ItemType.HOST_NAME; @@ -644,12 +665,13 @@ public String getSegmentedSubject(final ExtLogRecord record) { * Create a format step which emits the complete source location information with the given justification rules * (NOTE: call stack introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep locationInformationFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep locationInformationFormatStep(final boolean leftJustify, final int minimumWidth, + final int maximumWidth) { return locationInformationFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } @@ -657,13 +679,14 @@ public static FormatStep locationInformationFormatStep(final boolean leftJustify * Create a format step which emits the complete source location information with the given justification rules * (NOTE: call stack introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep locationInformationFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep locationInformationFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { final String fileName = record.getSourceFileName(); @@ -689,7 +712,7 @@ public boolean isCallerInformationRequired() { * Create a format step which emits the source file line number with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -702,13 +725,14 @@ public static FormatStep lineNumberFormatStep(final boolean leftJustify, final i * Create a format step which emits the source file line number with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep lineNumberFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep lineNumberFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { builder.append(record.getSourceLineNumber()); @@ -728,7 +752,7 @@ public ItemType getItemType() { /** * Create a format step which emits the formatted log message text with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -740,17 +764,19 @@ public static FormatStep messageFormatStep(final boolean leftJustify, final int /** * Create a format step which emits the formatted log message text with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep messageFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep messageFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { String formatted; - if (formatter == null || record.getFormatStyle() == ExtLogRecord.FormatStyle.PRINTF && ! (formatter instanceof ExtFormatter)) { + if (formatter == null + || record.getFormatStyle() == ExtLogRecord.FormatStyle.PRINTF && !(formatter instanceof ExtFormatter)) { formatted = record.getFormattedMessage(); } else { formatted = formatter.formatMessage(record); @@ -771,31 +797,36 @@ public ItemType getItemType() { } /** - * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given justification rules. + * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given + * justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep simpleMessageFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep simpleMessageFormatStep(final boolean leftJustify, final int minimumWidth, + final int maximumWidth) { return simpleMessageFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } /** - * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given justification rules. + * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given + * justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep simpleMessageFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep simpleMessageFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { String formatted; - if (formatter == null || record.getFormatStyle() == ExtLogRecord.FormatStyle.PRINTF && ! (formatter instanceof ExtFormatter)) { + if (formatter == null + || record.getFormatStyle() == ExtLogRecord.FormatStyle.PRINTF && !(formatter instanceof ExtFormatter)) { formatted = record.getFormattedMessage(); } else { formatted = formatter.formatMessage(record); @@ -806,27 +837,31 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex } /** - * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given justification rules. + * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given + * justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep simpleMessageFormatStep(final ExtFormatter formatter, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep simpleMessageFormatStep(final ExtFormatter formatter, final boolean leftJustify, + final int minimumWidth, final int maximumWidth) { return simpleMessageFormatStep(formatter, leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } /** - * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given justification rules. + * Create a format step which emits the formatted log message text (simple version, no exception traces) with the given + * justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep simpleMessageFormatStep(final ExtFormatter formatter, final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep simpleMessageFormatStep(final ExtFormatter formatter, final boolean leftJustify, + final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { builder.append(formatter.formatMessage(record)); @@ -841,27 +876,29 @@ public ItemType getItemType() { /** * Create a format step which emits the stack trace of an exception with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none - * @param extended {@code true} if the stack trace should attempt to include extended JAR version information + * @param extended {@code true} if the stack trace should attempt to include extended JAR version information * @return the format step */ - public static FormatStep exceptionFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final boolean extended) { + public static FormatStep exceptionFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, + final boolean extended) { return exceptionFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth, null, extended); } /** * Create a format step which emits the stack trace of an exception with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none - * @param extended {@code true} if the stack trace should attempt to include extended JAR version information + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param extended {@code true} if the stack trace should attempt to include extended JAR version information * @return the format step */ - public static FormatStep exceptionFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String argument, final boolean extended) { + public static FormatStep exceptionFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth, final String argument, final boolean extended) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { // not really correct but doesn't matter for now public ItemType getItemType() { @@ -882,7 +919,8 @@ public Void run() { }; } - private static void doExceptionFormatStep(final StringBuilder builder, final ExtLogRecord record, final String argument, final boolean extended) { + private static void doExceptionFormatStep(final StringBuilder builder, final ExtLogRecord record, final String argument, + final boolean extended) { final Throwable t = record.getThrown(); if (t != null) { int depth = -1; @@ -899,7 +937,7 @@ private static void doExceptionFormatStep(final StringBuilder builder, final Ext /** * Create a format step which emits the log message resource key (if any) with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -911,13 +949,14 @@ public static FormatStep resourceKeyFormatStep(final boolean leftJustify, final /** * Create a format step which emits the log message resource key (if any) with the given justification rules. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep resourceKeyFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep resourceKeyFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.RESOURCE_KEY; @@ -925,7 +964,8 @@ public ItemType getItemType() { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { final String key = record.getResourceKey(); - if (key != null) builder.append(key); + if (key != null) + builder.append(key); } }; } @@ -934,7 +974,7 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex * Create a format step which emits the source method name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -947,13 +987,14 @@ public static FormatStep methodNameFormatStep(final boolean leftJustify, final i * Create a format step which emits the source method name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep methodNameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep methodNameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { builder.append(record.getSourceMethodName()); @@ -983,25 +1024,27 @@ public String run() { /** * Create a format step which emits the platform line separator. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth, + final int maximumWidth) { return lineSeparatorFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } /** * Create a format step which emits the platform line separator. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.SOURCE_LINE_NUMBER; @@ -1016,7 +1059,7 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex /** * Create a format step which emits the log level name. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -1028,13 +1071,14 @@ public static FormatStep levelFormatStep(final boolean leftJustify, final int mi /** * Create a format step which emits the log level name. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep levelFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep levelFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, + final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.LEVEL; @@ -1050,25 +1094,27 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex /** * Create a format step which emits the localized log level name. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep localizedLevelFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep localizedLevelFormatStep(final boolean leftJustify, final int minimumWidth, + final int maximumWidth) { return localizedLevelFormatStep(leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } /** * Create a format step which emits the localized log level name. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep localizedLevelFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep localizedLevelFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.LEVEL; @@ -1084,27 +1130,29 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex /** * Create a format step which emits the number of milliseconds since the given base time. * - * @param baseTime the base time as milliseconds as per {@link System#currentTimeMillis()} - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param baseTime the base time as milliseconds as per {@link System#currentTimeMillis()} + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep relativeTimeFormatStep(final long baseTime, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep relativeTimeFormatStep(final long baseTime, final boolean leftJustify, final int minimumWidth, + final int maximumWidth) { return relativeTimeFormatStep(baseTime, leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } /** * Create a format step which emits the number of milliseconds since the given base time. * - * @param baseTime the base time as milliseconds as per {@link System#currentTimeMillis()} - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param baseTime the base time as milliseconds as per {@link System#currentTimeMillis()} + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep relativeTimeFormatStep(final long baseTime, final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep relativeTimeFormatStep(final long baseTime, final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.RELATIVE_TIME; @@ -1129,7 +1177,8 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex * * @return the format step */ - public static FormatStep threadFormatStep(final String argument, final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep threadFormatStep(final String argument, final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { if (argument != null && THREAD_ID.equals(argument.toLowerCase(Locale.ROOT))) { return threadIdFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth); } @@ -1139,13 +1188,14 @@ public static FormatStep threadFormatStep(final String argument, final boolean l /** * Create a format step which emits the id of the thread which originated the log record. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep threadIdFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep threadIdFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.THREAD_ID; @@ -1160,7 +1210,7 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex /** * Create a format step which emits the name of the thread which originated the log record. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -1172,13 +1222,14 @@ public static FormatStep threadNameFormatStep(final boolean leftJustify, final i /** * Create a format step which emits the name of the thread which originated the log record. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep threadNameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep threadNameFormatStep(final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.THREAD_NAME; @@ -1193,7 +1244,7 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex /** * Create a format step which emits the NDC value of the log record. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step @@ -1205,14 +1256,15 @@ public static FormatStep ndcFormatStep(final boolean leftJustify, final int mini /** * Create a format step which emits the NDC value of the log record. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none - * @param count the limit to the number of segments to format + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param count the limit to the number of segments to format * @return the format step */ - public static FormatStep ndcFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final int count) { + public static FormatStep ndcFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, + final int maximumWidth, final int count) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, count) { public ItemType getItemType() { return ItemType.NDC; @@ -1227,25 +1279,27 @@ public String getSegmentedSubject(final ExtLogRecord record) { /** * Create a format step which emits the MDC value associated with the given key of the log record. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { + public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth, + final int maximumWidth) { return mdcFormatStep(key, leftJustify, minimumWidth, DEFAULT_TRUNCATE_BEGINNING, maximumWidth); } /** * Create a format step which emits the MDC value associated with the given key of the log record. * - * @param leftJustify {@code true} to left justify, {@code false} to right justify - * @param minimumWidth the minimum field width, or 0 for none + * @param leftJustify {@code true} to left justify, {@code false} to right justify + * @param minimumWidth the minimum field width, or 0 for none * @param truncateBeginning {@code true} to truncate the beginning, otherwise {@code false} to truncate the end - * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none + * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ - public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { + public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth, + final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public ItemType getItemType() { return ItemType.MDC; @@ -1265,7 +1319,7 @@ public void renderRaw(Formatter formatter, final StringBuilder builder, final Ex } public static FormatStep formatColor(final ColorMap colors, final String color) { - return new FormatStep() { + return new FormatStep() { public void render(final StringBuilder builder, final ExtLogRecord record) { String code = colors.getCode(color, record.getLevel()); if (code != null) { @@ -1297,7 +1351,7 @@ public int estimateLength() { * allow access to the specified system property */ public static FormatStep systemPropertyFormatStep(final String argument, final boolean leftJustify, final int minimumWidth, - final boolean truncateBeginning, final int maximumWidth) { + final boolean truncateBeginning, final int maximumWidth) { if (argument == null) { throw new IllegalArgumentException("System property requires a key for the lookup"); } diff --git a/src/main/java/org/jboss/logmanager/formatters/GeneralFlags.java b/src/main/java/org/jboss/logmanager/formatters/GeneralFlags.java index deed6736..48d0fd98 100644 --- a/src/main/java/org/jboss/logmanager/formatters/GeneralFlags.java +++ b/src/main/java/org/jboss/logmanager/formatters/GeneralFlags.java @@ -67,7 +67,7 @@ private static GeneralFlags getOrCreateSet(final int bits) { GeneralFlags set = ALL_SETS.get(bits); if (set == null) { set = new GeneralFlags(bits); - if (! ALL_SETS.compareAndSet(bits, null, set)) { + if (!ALL_SETS.compareAndSet(bits, null, set)) { GeneralFlags appearing = ALL_SETS.get(bits); if (appearing != null) { set = appearing; diff --git a/src/main/java/org/jboss/logmanager/formatters/IndentingXmlWriter.java b/src/main/java/org/jboss/logmanager/formatters/IndentingXmlWriter.java index 179745d7..89e67666 100644 --- a/src/main/java/org/jboss/logmanager/formatters/IndentingXmlWriter.java +++ b/src/main/java/org/jboss/logmanager/formatters/IndentingXmlWriter.java @@ -21,6 +21,7 @@ import java.util.Iterator; import java.util.NoSuchElementException; + import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; @@ -81,7 +82,8 @@ public void writeStartElement(final String namespaceURI, final String localName) } @Override - public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException { + public void writeStartElement(final String prefix, final String localName, final String namespaceURI) + throws XMLStreamException { newline(); indent(); delegate.writeStartElement(prefix, localName, namespaceURI); @@ -99,7 +101,8 @@ public void writeEmptyElement(final String namespaceURI, final String localName) } @Override - public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException { + public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) + throws XMLStreamException { newline(); indent(); delegate.writeEmptyElement(prefix, localName, namespaceURI); @@ -148,12 +151,14 @@ public void writeAttribute(final String localName, final String value) throws XM } @Override - public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException { + public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) + throws XMLStreamException { delegate.writeAttribute(prefix, namespaceURI, localName, value); } @Override - public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException { + public void writeAttribute(final String namespaceURI, final String localName, final String value) + throws XMLStreamException { delegate.writeAttribute(namespaceURI, localName, value); } diff --git a/src/main/java/org/jboss/logmanager/formatters/JsonFormatter.java b/src/main/java/org/jboss/logmanager/formatters/JsonFormatter.java index 020b0fb1..a65605b8 100644 --- a/src/main/java/org/jboss/logmanager/formatters/JsonFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/JsonFormatter.java @@ -24,6 +24,7 @@ import java.math.BigInteger; import java.util.HashMap; import java.util.Map; + import jakarta.json.Json; import jakarta.json.JsonValue; import jakarta.json.stream.JsonGenerator; @@ -36,7 +37,9 @@ *

* Note that including details can be expensive in terms of calculating the caller. *

- *

The details include;

+ *

+ * The details include; + *

*
    *
  • {@link org.jboss.logmanager.ExtLogRecord#getSourceClassName() source class name}
  • *
  • {@link org.jboss.logmanager.ExtLogRecord#getSourceFileName() source file name}
  • @@ -48,7 +51,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({ "unused", "WeakerAccess" }) public class JsonFormatter extends StructuredFormatter { private final Map config; @@ -94,7 +97,9 @@ public JsonFormatter(final Map keyOverrides) { */ public boolean isPrettyPrint() { synchronized (config) { - return (config.containsKey(jakarta.json.stream.JsonGenerator.PRETTY_PRINTING) ? (Boolean) config.get(jakarta.json.stream.JsonGenerator.PRETTY_PRINTING) : false); + return (config.containsKey(jakarta.json.stream.JsonGenerator.PRETTY_PRINTING) + ? (Boolean) config.get(jakarta.json.stream.JsonGenerator.PRETTY_PRINTING) + : false); } } diff --git a/src/main/java/org/jboss/logmanager/formatters/MultistepFormatter.java b/src/main/java/org/jboss/logmanager/formatters/MultistepFormatter.java index 8180b278..60c87f88 100644 --- a/src/main/java/org/jboss/logmanager/formatters/MultistepFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/MultistepFormatter.java @@ -19,10 +19,11 @@ package org.jboss.logmanager.formatters; -import org.jboss.logmanager.ExtLogRecord; -import org.jboss.logmanager.ExtFormatter; import static java.lang.Math.max; +import org.jboss.logmanager.ExtFormatter; +import org.jboss.logmanager.ExtLogRecord; + /** * A formatter which formats a record in a series of steps. */ diff --git a/src/main/java/org/jboss/logmanager/formatters/NumericFlags.java b/src/main/java/org/jboss/logmanager/formatters/NumericFlags.java index 01889bcd..68d373c1 100644 --- a/src/main/java/org/jboss/logmanager/formatters/NumericFlags.java +++ b/src/main/java/org/jboss/logmanager/formatters/NumericFlags.java @@ -67,7 +67,7 @@ private static NumericFlags getOrCreateSet(final int bits) { NumericFlags set = ALL_SETS.get(bits); if (set == null) { set = new NumericFlags(bits); - if (! ALL_SETS.compareAndSet(bits, null, set)) { + if (!ALL_SETS.compareAndSet(bits, null, set)) { NumericFlags appearing = ALL_SETS.get(bits); if (appearing != null) { set = appearing; diff --git a/src/main/java/org/jboss/logmanager/formatters/PatternFormatter.java b/src/main/java/org/jboss/logmanager/formatters/PatternFormatter.java index c61a8933..1136253f 100644 --- a/src/main/java/org/jboss/logmanager/formatters/PatternFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/PatternFormatter.java @@ -27,6 +27,7 @@ public class PatternFormatter extends MultistepFormatter { private volatile String pattern; private volatile ColorMap colors; + /** * Construct a new instance. */ @@ -49,7 +50,7 @@ public PatternFormatter(String pattern) { * Construct a new instance. * * @param pattern the initial pattern - * @param colors the color map to use + * @param colors the color map to use */ public PatternFormatter(String pattern, String colors) { ColorMap colorMap = ColorMap.create(colors); @@ -84,45 +85,108 @@ public void setPattern(final String pattern) { /** * Set the color map to use for log levels when %K{level} is used. * - *

    The format is level:color,level:color,... + *

    + * The format is level:color,level:color,... * - *

    Where level is either a numerical value or one of the following constants:

    + *

    + * Where level is either a numerical value or one of the following constants: + *

    * * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * *
    fatal
    error
    severe
    warn
    warning
    info
    config
    debug
    trace
    fine
    finer
    finest
    fatal
    error
    severe
    warn
    warning
    info
    config
    debug
    trace
    fine
    finer
    finest
    * - *

    Color is one of the following constants:

    + *

    + * Color is one of the following constants: + *

    * * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * *
    clear
    black
    red
    green
    yellow
    blue
    magenta
    cyan
    white
    brightblack
    brightred
    brightgreen
    brightyellow
    brightblue
    brightmagenta
    brightcyan
    brightwhite
    clear
    black
    red
    green
    yellow
    blue
    magenta
    cyan
    white
    brightblack
    brightred
    brightgreen
    brightyellow
    brightblue
    brightmagenta
    brightcyan
    brightwhite
    * * @param colors a colormap expression string described above diff --git a/src/main/java/org/jboss/logmanager/formatters/Printf.java b/src/main/java/org/jboss/logmanager/formatters/Printf.java index 0b92ec33..1c9c52e7 100644 --- a/src/main/java/org/jboss/logmanager/formatters/Printf.java +++ b/src/main/java/org/jboss/logmanager/formatters/Printf.java @@ -19,7 +19,7 @@ package org.jboss.logmanager.formatters; -import io.smallrye.common.constraint.Assert; +import static java.lang.Math.max; import java.io.IOException; import java.math.BigDecimal; @@ -55,7 +55,7 @@ import java.util.TimeZone; import java.util.UnknownFormatConversionException; -import static java.lang.Math.max; +import io.smallrye.common.constraint.Assert; /** * A string formatter which can be customized. @@ -131,7 +131,8 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje } } else if (state == ST_PCT || state == ST_DOLLAR) { if (state == ST_PCT && cp == '<') { - if (lastArgIdx == -1) throw new IllegalFormatFlagsException("<"); + if (lastArgIdx == -1) + throw new IllegalFormatFlagsException("<"); argIdx = lastArgIdx; continue; } @@ -144,25 +145,29 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje case ' ': { numFlags.forbid(NumericFlag.SPACE_POSITIVE); numFlags = numFlags.with(NumericFlag.SPACE_POSITIVE); - if (numFlags.contains(NumericFlag.SIGN)) numFlags.forbid(NumericFlag.SPACE_POSITIVE); + if (numFlags.contains(NumericFlag.SIGN)) + numFlags.forbid(NumericFlag.SPACE_POSITIVE); continue; } case '+': { numFlags.forbid(NumericFlag.SIGN); numFlags = numFlags.with(NumericFlag.SIGN); - if (numFlags.contains(NumericFlag.SPACE_POSITIVE)) numFlags.forbid(NumericFlag.SIGN); + if (numFlags.contains(NumericFlag.SPACE_POSITIVE)) + numFlags.forbid(NumericFlag.SIGN); continue; } case '0': { numFlags.forbid(NumericFlag.ZERO_PAD); numFlags = numFlags.with(NumericFlag.ZERO_PAD); - if (genFlags.contains(GeneralFlag.LEFT_JUSTIFY)) numFlags.forbid(NumericFlag.ZERO_PAD); + if (genFlags.contains(GeneralFlag.LEFT_JUSTIFY)) + numFlags.forbid(NumericFlag.ZERO_PAD); continue; } case '-': { genFlags.forbid(GeneralFlag.LEFT_JUSTIFY); genFlags = genFlags.with(GeneralFlag.LEFT_JUSTIFY); - if (numFlags.contains(NumericFlag.ZERO_PAD)) genFlags.forbid(GeneralFlag.LEFT_JUSTIFY); + if (numFlags.contains(NumericFlag.ZERO_PAD)) + genFlags.forbid(GeneralFlag.LEFT_JUSTIFY); continue; } case '(': { @@ -186,7 +191,8 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje // time-specific format specifiers numFlags.forbidAll(); genFlags.forbid(GeneralFlag.ALTERNATE); - if (precision != -1) throw precisionException(precision); + if (precision != -1) + throw precisionException(precision); if (argVal == null) { formatPlainString(destination, null, genFlags, width, -1); continue; @@ -209,24 +215,29 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje switch (cp) { // locale-based names case 'A': { - formatTimeTextField(destination, ta, ChronoField.DAY_OF_WEEK, getDateFormatSymbols().getWeekdays(), genFlags, width); + formatTimeTextField(destination, ta, ChronoField.DAY_OF_WEEK, getDateFormatSymbols().getWeekdays(), + genFlags, width); break; } case 'a': { - formatTimeTextField(destination, ta, ChronoField.DAY_OF_WEEK, getDateFormatSymbols().getShortWeekdays(), genFlags, width); + formatTimeTextField(destination, ta, ChronoField.DAY_OF_WEEK, getDateFormatSymbols().getShortWeekdays(), + genFlags, width); break; } case 'B': { - formatTimeTextField(destination, ta, ChronoField.MONTH_OF_YEAR, getDateFormatSymbols().getMonths(), genFlags, width); + formatTimeTextField(destination, ta, ChronoField.MONTH_OF_YEAR, getDateFormatSymbols().getMonths(), + genFlags, width); break; } case 'h': // synonym for 'b' case 'b': { - formatTimeTextField(destination, ta, ChronoField.MONTH_OF_YEAR, getDateFormatSymbols().getShortMonths(), genFlags, width); + formatTimeTextField(destination, ta, ChronoField.MONTH_OF_YEAR, getDateFormatSymbols().getShortMonths(), + genFlags, width); break; } case 'p': { - formatTimeTextField(destination, ta, ChronoField.AMPM_OF_DAY, getDateFormatSymbols().getAmPmStrings(), genFlags, width); + formatTimeTextField(destination, ta, ChronoField.AMPM_OF_DAY, getDateFormatSymbols().getAmPmStrings(), + genFlags, width); break; } @@ -313,9 +324,11 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje // compositions case 'c': { final StringBuilder b = new StringBuilder(); - formatTimeTextField(b, ta, ChronoField.DAY_OF_WEEK, getDateFormatSymbols().getShortWeekdays(), genFlags, -1); + formatTimeTextField(b, ta, ChronoField.DAY_OF_WEEK, getDateFormatSymbols().getShortWeekdays(), genFlags, + -1); b.append(' '); - formatTimeTextField(b, ta, ChronoField.MONTH_OF_YEAR, getDateFormatSymbols().getShortMonths(), genFlags, -1); + formatTimeTextField(b, ta, ChronoField.MONTH_OF_YEAR, getDateFormatSymbols().getShortMonths(), genFlags, + -1); b.append(' '); formatTimeField(b, ta, ChronoField.DAY_OF_MONTH, genFlags, -1, 2); b.append(' '); @@ -369,7 +382,8 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje b.append(':'); formatTimeField(b, ta, ChronoField.SECOND_OF_MINUTE, genFlags, -1, 2); b.append(' '); - formatTimeTextField(b, ta, ChronoField.AMPM_OF_DAY, getDateFormatSymbols().getAmPmStrings(), genFlags.with(GeneralFlag.UPPERCASE), width); + formatTimeTextField(b, ta, ChronoField.AMPM_OF_DAY, getDateFormatSymbols().getAmPmStrings(), + genFlags.with(GeneralFlag.UPPERCASE), width); appendStr(destination, genFlags, width, -1, b.toString()); break; } @@ -441,12 +455,14 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje // capture argument if (argIdx != -1) { if (argIdx - 1 >= params.length) { - throw new MissingFormatArgumentException(format.substring(start, cp == 't' || cp == 'T' ? i + 2 : i + 1)); + throw new MissingFormatArgumentException( + format.substring(start, cp == 't' || cp == 'T' ? i + 2 : i + 1)); } argVal = params[argIdx - 1]; } else { if (crs >= params.length) { - throw new MissingFormatArgumentException(format.substring(start, cp == 't' || cp == 'T' ? i + 2 : i + 1)); + throw new MissingFormatArgumentException( + format.substring(start, cp == 't' || cp == 'T' ? i + 2 : i + 1)); } argVal = params[crs++]; argIdx = crs; // crs is 0-based, argIdx & lastArgIdx are 1-based @@ -456,7 +472,8 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje case '%': { genFlags.forbidAllBut(GeneralFlag.LEFT_JUSTIFY); // but it's ignored anyway numFlags.forbidAll(); - if (precision != -1 || state == ST_PREC) throw precisionException(precision); + if (precision != -1 || state == ST_PREC) + throw precisionException(precision); formatPercent(destination); break; } @@ -469,8 +486,10 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje case 'b': { numFlags.forbidAll(); genFlags.forbid(GeneralFlag.ALTERNATE); - if (Character.isUpperCase(cp)) genFlags = genFlags.with(GeneralFlag.UPPERCASE); - if (argVal != null && ! (argVal instanceof Boolean)) throw new IllegalFormatConversionException((char)cp, argVal.getClass()); + if (Character.isUpperCase(cp)) + genFlags = genFlags.with(GeneralFlag.UPPERCASE); + if (argVal != null && !(argVal instanceof Boolean)) + throw new IllegalFormatConversionException((char) cp, argVal.getClass()); formatBoolean(destination, checkType(cp, argVal, Boolean.class), genFlags, width, precision); break; } @@ -478,8 +497,10 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje case 'c': { numFlags.forbidAll(); genFlags.forbidAllBut(GeneralFlag.LEFT_JUSTIFY); - if (Character.isUpperCase(cp)) genFlags = genFlags.with(GeneralFlag.UPPERCASE); - if (precision != -1 || state == ST_PREC) throw precisionException(precision); + if (Character.isUpperCase(cp)) + genFlags = genFlags.with(GeneralFlag.UPPERCASE); + if (precision != -1 || state == ST_PREC) + throw precisionException(precision); int cpa; if (argVal == null) { appendStr(destination, genFlags, width, precision, "null"); @@ -496,8 +517,10 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje } case 'd': { genFlags.forbid(GeneralFlag.ALTERNATE); - if (precision != -1 || state == ST_PREC) throw precisionException(precision); - formatDecimalInteger(destination, checkType(cp, argVal, Number.class, Byte.class, Short.class, Integer.class, Long.class, BigInteger.class), genFlags, numFlags, width); + if (precision != -1 || state == ST_PREC) + throw precisionException(precision); + formatDecimalInteger(destination, checkType(cp, argVal, Number.class, Byte.class, Short.class, + Integer.class, Long.class, BigInteger.class), genFlags, numFlags, width); break; } case 'E': @@ -505,8 +528,10 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje case 'f': case 'G': case 'g': { - if (Character.isUpperCase(cp)) genFlags = genFlags.with(GeneralFlag.UPPERCASE); - if (argVal != null && ! (argVal instanceof Float) && ! (argVal instanceof Double) && ! (argVal instanceof BigDecimal)) { + if (Character.isUpperCase(cp)) + genFlags = genFlags.with(GeneralFlag.UPPERCASE); + if (argVal != null && !(argVal instanceof Float) && !(argVal instanceof Double) + && !(argVal instanceof BigDecimal)) { throw new IllegalFormatConversionException((char) cp, argVal.getClass()); } Number item = checkType(cp, argVal, Number.class, Float.class, Double.class, BigDecimal.class); @@ -537,14 +562,17 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje } case 'o': { numFlags.forbidAllBut(NumericFlag.ZERO_PAD); - if (precision != -1 || state == ST_PREC) throw precisionException(precision); - formatOctalInteger(destination, checkType(cp, argVal, Number.class, Byte.class, Short.class, Integer.class, Long.class, BigInteger.class), genFlags, numFlags, width); + if (precision != -1 || state == ST_PREC) + throw precisionException(precision); + formatOctalInteger(destination, checkType(cp, argVal, Number.class, Byte.class, Short.class, Integer.class, + Long.class, BigInteger.class), genFlags, numFlags, width); break; } case 's': case 'S': { numFlags.forbidAll(); - if (Character.isUpperCase(cp)) genFlags = genFlags.with(GeneralFlag.UPPERCASE); + if (Character.isUpperCase(cp)) + genFlags = genFlags.with(GeneralFlag.UPPERCASE); if (argVal instanceof Formattable) { formatFormattableString(destination, (Formattable) argVal, genFlags, width, precision); } else { @@ -554,16 +582,20 @@ public StringBuilder formatDirect(StringBuilder destination, String format, Obje } case 'T': case 't': { - if (Character.isUpperCase(cp)) genFlags = genFlags.with(GeneralFlag.UPPERCASE); + if (Character.isUpperCase(cp)) + genFlags = genFlags.with(GeneralFlag.UPPERCASE); state = ST_TIME; continue; } case 'X': case 'x': { numFlags.forbidAllBut(NumericFlag.ZERO_PAD); - if (Character.isUpperCase(cp)) genFlags = genFlags.with(GeneralFlag.UPPERCASE); - if (precision != -1 || state == ST_PREC) throw precisionException(precision); - formatHexInteger(destination, checkType(cp, argVal, Number.class, Byte.class, Short.class, Integer.class, Long.class, BigInteger.class), genFlags, numFlags, width); + if (Character.isUpperCase(cp)) + genFlags = genFlags.with(GeneralFlag.UPPERCASE); + if (precision != -1 || state == ST_PREC) + throw precisionException(precision); + formatHexInteger(destination, checkType(cp, argVal, Number.class, Byte.class, Short.class, Integer.class, + Long.class, BigInteger.class), genFlags, numFlags, width); break; } default: { @@ -597,14 +629,17 @@ protected DateFormatSymbols getDateFormatSymbols() { return dfs; } - protected void formatTimeTextField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, final String[] symbols, final GeneralFlags genFlags, final int width) { + protected void formatTimeTextField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, + final String[] symbols, final GeneralFlags genFlags, final int width) { final int baseIdx = ta.get(field); // fix offset fields - final int idx = field == ChronoField.MONTH_OF_YEAR ? baseIdx - 1 : field == ChronoField.DAY_OF_WEEK ? (baseIdx + 1) % 7 : baseIdx; + final int idx = field == ChronoField.MONTH_OF_YEAR ? baseIdx - 1 + : field == ChronoField.DAY_OF_WEEK ? (baseIdx + 1) % 7 : baseIdx; appendStr(target, genFlags, width, -1, symbols[idx]); } - protected void formatTimeZoneId(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, final int width) { + protected void formatTimeZoneId(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, + final int width) { final boolean upper = genFlags.contains(GeneralFlag.UPPERCASE); final ZoneId zoneId = ta.query(TemporalQueries.zone()); if (zoneId == null) { @@ -620,32 +655,36 @@ protected void formatTimeZoneId(final StringBuilder target, final TemporalAccess appendStr(target, genFlags, width, -1, output); } - protected void formatTimeZoneOffset(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, final int width) { + protected void formatTimeZoneOffset(final StringBuilder target, final TemporalAccessor ta, final GeneralFlags genFlags, + final int width) { final int offset = ta.get(ChronoField.OFFSET_SECONDS); final int absOffset = Math.abs(offset); final int minutes = (absOffset / 60) % 60; final int hours = (absOffset / 3600); final boolean lj = genFlags.contains(GeneralFlag.LEFT_JUSTIFY); - if (width > 5 && ! lj) { + if (width > 5 && !lj) { appendSpaces(target, width - 5); } target.append(offset > 0 ? '+' : '-'); - if (hours < 10) target.append('0'); + if (hours < 10) + target.append('0'); target.append(hours); - if (minutes < 10) target.append('0'); + if (minutes < 10) + target.append('0'); target.append(minutes); if (width > 5 && lj) { appendSpaces(target, width - 5); } } - protected void formatTimeField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, final GeneralFlags genFlags, final int width, final int zeroPad) { + protected void formatTimeField(final StringBuilder target, final TemporalAccessor ta, final TemporalField field, + final GeneralFlags genFlags, final int width, final int zeroPad) { final long val = ta.getLong(field); final String valStr = Long.toString(val); final int length = valStr.length(); final int extLen = max(zeroPad, length); final boolean lj = genFlags.contains(GeneralFlag.LEFT_JUSTIFY); - if (width > extLen && ! lj) { + if (width > extLen && !lj) { appendSpaces(target, width - extLen); } if (zeroPad > length) { @@ -665,11 +704,15 @@ protected void formatLineSeparator(StringBuilder target) { target.append(System.lineSeparator()); } - protected void formatFormattableString(StringBuilder target, Formattable formattable, GeneralFlags genFlags, int width, int precision) { + protected void formatFormattableString(StringBuilder target, Formattable formattable, GeneralFlags genFlags, int width, + int precision) { int fmtFlags = 0; - if (genFlags.contains(GeneralFlag.LEFT_JUSTIFY)) fmtFlags |= FormattableFlags.LEFT_JUSTIFY; - if (genFlags.contains(GeneralFlag.UPPERCASE)) fmtFlags |= FormattableFlags.UPPERCASE; - if (genFlags.contains(GeneralFlag.ALTERNATE)) fmtFlags |= FormattableFlags.ALTERNATE; + if (genFlags.contains(GeneralFlag.LEFT_JUSTIFY)) + fmtFlags |= FormattableFlags.LEFT_JUSTIFY; + if (genFlags.contains(GeneralFlag.UPPERCASE)) + fmtFlags |= FormattableFlags.UPPERCASE; + if (genFlags.contains(GeneralFlag.ALTERNATE)) + fmtFlags |= FormattableFlags.ALTERNATE; // make a dummy Formatter to appease the constraints of the API formattable.formatTo(new Formatter(target), fmtFlags, width, precision); } @@ -679,7 +722,8 @@ protected void formatPlainString(StringBuilder target, Object item, GeneralFlags } protected void formatBoolean(StringBuilder target, Object item, GeneralFlags genFlags, int width, int precision) { - appendStr(target, genFlags, width, precision, item instanceof Boolean ? item.toString() : Boolean.toString(item != null)); + appendStr(target, genFlags, width, precision, + item instanceof Boolean ? item.toString() : Boolean.toString(item != null)); } protected void formatHashCode(StringBuilder target, Object item, GeneralFlags genFlags, int width, int precision) { @@ -694,7 +738,8 @@ protected void formatCharacter(StringBuilder target, int codePoint, GeneralFlags } } - protected void formatDecimalInteger(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, int width) { + protected void formatDecimalInteger(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, + int width) { if (item == null) { appendStr(target, genFlags, width, -1, "null"); } else { @@ -723,7 +768,8 @@ protected void formatDecimalInteger(StringBuilder target, Number item, GeneralFl } } - protected void formatOctalInteger(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, int width) { + protected void formatOctalInteger(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, + int width) { if (item == null) { appendStr(target, genFlags, width, -1, "null"); } else { @@ -732,15 +778,18 @@ protected void formatOctalInteger(StringBuilder target, Number item, GeneralFlag final boolean lj = genFlags.contains(GeneralFlag.LEFT_JUSTIFY); if (numFlags.contains(NumericFlag.ZERO_PAD)) { // write zeros first - if (addRadix) target.append('0'); + if (addRadix) + target.append('0'); appendZeros(target, fillCount); } else if (lj) { - if (addRadix) target.append('0'); + if (addRadix) + target.append('0'); } else { // ! LEFT_JUSTIFY // write spaces first appendSpaces(target, fillCount); - if (addRadix) target.append('0'); + if (addRadix) + target.append('0'); } appendOctal(target, item); if (lj) { @@ -749,7 +798,8 @@ protected void formatOctalInteger(StringBuilder target, Number item, GeneralFlag } } - protected void formatHexInteger(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, int width) { + protected void formatHexInteger(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, + int width) { if (item == null) { appendStr(target, genFlags, width, -1, "null"); } else { @@ -759,15 +809,18 @@ protected void formatHexInteger(StringBuilder target, Number item, GeneralFlags final boolean lj = genFlags.contains(GeneralFlag.LEFT_JUSTIFY); if (numFlags.contains(NumericFlag.ZERO_PAD)) { // write zeros first - if (addRadix) target.append(upper ? "0X" : "0x"); + if (addRadix) + target.append(upper ? "0X" : "0x"); appendZeros(target, fillCount); } else if (lj) { - if (addRadix) target.append(upper ? "0X" : "0x"); + if (addRadix) + target.append(upper ? "0X" : "0x"); } else { // ! LEFT_JUSTIFY // write spaces first appendSpaces(target, fillCount); - if (addRadix) target.append(upper ? "0X" : "0x"); + if (addRadix) + target.append(upper ? "0X" : "0x"); } appendHex(target, item, upper); if (lj) { @@ -776,7 +829,8 @@ protected void formatHexInteger(StringBuilder target, Number item, GeneralFlags } } - protected void formatFloatingPointSci(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, int width, int precision) { + protected void formatFloatingPointSci(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, + int width, int precision) { if (item == null) { appendStr(target, genFlags, width, precision, "null"); } else { @@ -787,19 +841,23 @@ protected void formatFloatingPointSci(StringBuilder target, Number item, General } else { sym.setExponentSeparator(upper ? "E+" : "e+"); } - formatDFP(target, item, genFlags, numFlags, width, precision == -1 ? 6 : precision == 0 ? 1 : precision, true, sym, "0.#E00"); + formatDFP(target, item, genFlags, numFlags, width, precision == -1 ? 6 : precision == 0 ? 1 : precision, true, sym, + "0.#E00"); } } - protected void formatFloatingPointDecimal(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, int width, int precision) { + protected void formatFloatingPointDecimal(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, + int width, int precision) { if (item == null) { appendStr(target, genFlags, width, precision, "null"); } else { - formatDFP(target, item, genFlags, numFlags, width, precision == 0 ? 1 : precision, false, DecimalFormatSymbols.getInstance(locale), "0.#"); + formatDFP(target, item, genFlags, numFlags, width, precision == 0 ? 1 : precision, false, + DecimalFormatSymbols.getInstance(locale), "0.#"); } } - protected void formatFloatingPointGeneral(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, int width, int precision) { + protected void formatFloatingPointGeneral(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags, + int width, int precision) { if (item == null) { appendStr(target, genFlags, width, precision, "null"); } else { @@ -823,10 +881,12 @@ protected void formatFloatingPointGeneral(StringBuilder target, Number item, Gen } } - private void formatDFP(final StringBuilder target, final Number item, final GeneralFlags genFlags, final NumericFlags numFlags, final int width, final int precision, final boolean oneIntDigit, final DecimalFormatSymbols sym, final String s) { - if (! (item instanceof BigDecimal)) { + private void formatDFP(final StringBuilder target, final Number item, final GeneralFlags genFlags, + final NumericFlags numFlags, final int width, final int precision, final boolean oneIntDigit, + final DecimalFormatSymbols sym, final String s) { + if (!(item instanceof BigDecimal)) { final double dv = item.doubleValue(); - if (! Double.isFinite(dv)) { + if (!Double.isFinite(dv)) { appendStr(target, genFlags, width, -1, Double.toString(dv)); return; } @@ -848,8 +908,8 @@ private void formatDFP(final StringBuilder target, final Number item, final Gene fmt.setNegativeSuffix(""); } fmt.setGroupingUsed(numFlags.contains(NumericFlag.LOCALE_GROUPING_SEPARATORS)); - fmt.setMinimumFractionDigits(precision == - 1 ? 1 : precision); - fmt.setMaximumFractionDigits(precision == - 1 ? Integer.MAX_VALUE : precision); + fmt.setMinimumFractionDigits(precision == -1 ? 1 : precision); + fmt.setMaximumFractionDigits(precision == -1 ? Integer.MAX_VALUE : precision); fmt.setMinimumIntegerDigits(1); if (oneIntDigit) { fmt.setMaximumIntegerDigits(1); @@ -859,7 +919,7 @@ private void formatDFP(final StringBuilder target, final Number item, final Gene final int end = iterator.getEndIndex(); final boolean lj = genFlags.contains(GeneralFlag.LEFT_JUSTIFY); final boolean zp = numFlags.contains(NumericFlag.ZERO_PAD); - if (! lj && ! zp && width > end) { + if (!lj && !zp && width > end) { appendSpaces(target, width - end); } while (iterator.getAttribute(NumberFormat.Field.SIGN) != null) { @@ -926,9 +986,12 @@ private static void appendOctal(StringBuilder target, final Number item) { int max = ((bl + 2) / 3) * 3; for (int i = 0; i < max; i += 3) { int val = 0; - if (bi.testBit(max - i )) val |= 0b100; - if (bi.testBit(max - i - 1)) val |= 0b010; - if (bi.testBit(max - i - 2)) val |= 0b001; + if (bi.testBit(max - i)) + val |= 0b100; + if (bi.testBit(max - i - 1)) + val |= 0b010; + if (bi.testBit(max - i - 2)) + val |= 0b001; target.append(val); } } @@ -957,18 +1020,24 @@ private static void appendHex(final StringBuilder target, final Number item, fin int max = ((bl + 3) / 4) * 4; for (int i = 0; i < max; i += 4) { int val = 0; - if (bi.testBit(max - i )) val |= 0b1000; - if (bi.testBit(max - i - 1)) val |= 0b0100; - if (bi.testBit(max - i - 2)) val |= 0b0010; - if (bi.testBit(max - i - 3)) val |= 0b0001; - if (val > 9) val += upper ? 'A' : 'a' - 10; + if (bi.testBit(max - i)) + val |= 0b1000; + if (bi.testBit(max - i - 1)) + val |= 0b0100; + if (bi.testBit(max - i - 2)) + val |= 0b0010; + if (bi.testBit(max - i - 3)) + val |= 0b0001; + if (val > 9) + val += upper ? 'A' : 'a' - 10; target.append((char) (val > 9 ? val - 10 + (upper ? 'A' : 'a') : val + '0')); } } } } - private void appendChar(final StringBuilder target, GeneralFlags genFlags, final int width, final int precision, final char c) { + private void appendChar(final StringBuilder target, GeneralFlags genFlags, final int width, final int precision, + final char c) { if (genFlags.contains(GeneralFlag.UPPERCASE) && Character.isLowerCase(c)) { appendStr(target, genFlags, width, precision, Character.toString(c)); } else if (width <= 1) { @@ -982,7 +1051,8 @@ private void appendChar(final StringBuilder target, GeneralFlags genFlags, final } } - private void appendStr(final StringBuilder target, GeneralFlags genFlags, final int width, final int precision, final String itemStr) { + private void appendStr(final StringBuilder target, GeneralFlags genFlags, final int width, final int precision, + final String itemStr) { String str = genFlags.contains(GeneralFlag.UPPERCASE) ? itemStr.toUpperCase(locale) : itemStr; if (width == -1 && precision == -1) { target.append(str); @@ -1008,11 +1078,14 @@ private void appendStr(final StringBuilder target, GeneralFlags genFlags, final @SafeVarargs private static T checkType(int convCp, Object arg, Class commonType, Class... allowedSubTypes) { - if (arg == null) return null; + if (arg == null) + return null; if (commonType.isInstance(arg)) { - if (allowedSubTypes.length == 0) return commonType.cast(arg); + if (allowedSubTypes.length == 0) + return commonType.cast(arg); for (Class subType : allowedSubTypes) { - if (subType.isInstance(arg)) return commonType.cast(arg); + if (subType.isInstance(arg)) + return commonType.cast(arg); } } throw new IllegalFormatConversionException((char) convCp, arg.getClass()); @@ -1156,4 +1229,4 @@ public R adjustInto(final R temporal, final long newValue) return (R) temporal.with(ChronoField.YEAR, (temporal.get(ChronoField.YEAR) % 100) + 100 * newValue); } }; -} \ No newline at end of file +} diff --git a/src/main/java/org/jboss/logmanager/formatters/StackTraceFormatter.java b/src/main/java/org/jboss/logmanager/formatters/StackTraceFormatter.java index 2fd4e43e..1ad838a0 100644 --- a/src/main/java/org/jboss/logmanager/formatters/StackTraceFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/StackTraceFormatter.java @@ -62,7 +62,7 @@ public static void renderStackTrace(final StringBuilder builder, final Throwable * @param suppressedDepth the number of suppressed messages to include */ static void renderStackTrace(final StringBuilder builder, final Throwable t, - @SuppressWarnings("unused") final boolean extended, final int suppressedDepth) { + @SuppressWarnings("unused") final boolean extended, final int suppressedDepth) { new StackTraceFormatter(builder, suppressedDepth).renderStackTrace(t); } @@ -96,7 +96,7 @@ private void renderStackTrace(final Throwable t) { } private void renderStackTrace(final StackTraceElement[] parentStack, final Throwable child, final String caption, - final String prefix) { + final String prefix) { if (seen.contains(child)) { builder.append(prefix) .append(caption) diff --git a/src/main/java/org/jboss/logmanager/formatters/StructuredFormatter.java b/src/main/java/org/jboss/logmanager/formatters/StructuredFormatter.java index 946cfa5e..67e8ebf3 100644 --- a/src/main/java/org/jboss/logmanager/formatters/StructuredFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/StructuredFormatter.java @@ -30,8 +30,6 @@ import org.jboss.logmanager.ExtFormatter; import org.jboss.logmanager.ExtLogRecord; import org.jboss.logmanager.PropertyValues; -import org.jboss.logmanager.formatters.StackTraceFormatter; -import org.jboss.logmanager.formatters.StringBuilderWriter; /** * An abstract class that uses a generator to help generate structured data from a {@link @@ -45,7 +43,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({ "unused", "WeakerAccess" }) public abstract class StructuredFormatter extends ExtFormatter { /** @@ -203,7 +201,6 @@ protected final String getKey(final Key defaultKey) { return defaultKey.getKey(); } - @Override public final synchronized String format(final ExtLogRecord record) { final boolean details = printDetails; @@ -474,7 +471,8 @@ protected boolean isFormattedExceptionOutputType() { exceptionOutputType == ExceptionOutputType.DETAILED_AND_FORMATTED; } - private void addException(final Generator generator, final Throwable throwable, final Map seen) throws Exception { + private void addException(final Generator generator, final Throwable throwable, final Map seen) + throws Exception { if (throwable == null) { return; } diff --git a/src/main/java/org/jboss/logmanager/formatters/TextBannerFormatter.java b/src/main/java/org/jboss/logmanager/formatters/TextBannerFormatter.java index 3fb9756e..641f9dd8 100644 --- a/src/main/java/org/jboss/logmanager/formatters/TextBannerFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/TextBannerFormatter.java @@ -26,7 +26,7 @@ public final class TextBannerFormatter extends ExtFormatter.Delegating { * Construct a new instance. * * @param bannerSupplier the supplier for the banner (must not be {@code null}) - * @param delegate the delegate formatter (must not be {@code null}) + * @param delegate the delegate formatter (must not be {@code null}) */ public TextBannerFormatter(final Supplier bannerSupplier, final ExtFormatter delegate) { super(delegate); @@ -64,7 +64,7 @@ public static Supplier createStringSupplier(String string) { * Create a supplier which loads the banner from the given file path, * falling back to the given fallback supplier on error. * - * @param path the path to load from (must not be {@code null}) + * @param path the path to load from (must not be {@code null}) * @param fallback the fallback supplier (must not be {@code null}) * @return the supplier (not {@code null}) */ @@ -84,7 +84,7 @@ public static Supplier createFileSupplier(Path path, Supplier fa * Create a supplier which loads the banner from the given URL, * falling back to the given fallback supplier on error. * - * @param url the URL to load from (must not be {@code null}) + * @param url the URL to load from (must not be {@code null}) * @param fallback the fallback supplier (must not be {@code null}) * @return the supplier (not {@code null}) */ @@ -105,9 +105,9 @@ public static Supplier createUrlSupplier(URL url, Supplier fallb * Create a supplier which loads the banner from a resource in the given class loader, * falling back to the given fallback supplier on error. * - * @param resource the resource name (must not be {@code null}) + * @param resource the resource name (must not be {@code null}) * @param classLoader the class loader to load from (must not be {@code null}) - * @param fallback the fallback supplier (must not be {@code null}) + * @param fallback the fallback supplier (must not be {@code null}) * @return the supplier (not {@code null}) */ public static Supplier createResourceSupplier(String resource, ClassLoader classLoader, Supplier fallback) { @@ -139,7 +139,8 @@ public static Supplier createResourceSupplier(String resource, Supplier< // private stuff private static final Supplier EMPTY = createStringSupplier(""); - private static final StackWalker STACK_WALKER = AccessController.doPrivileged((PrivilegedAction) () -> StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)); + private static final StackWalker STACK_WALKER = AccessController.doPrivileged( + (PrivilegedAction) () -> StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)); private static ClassLoader getClassLoader(Class clazz) { return AccessController.doPrivileged((PrivilegedAction) clazz::getClassLoader); diff --git a/src/main/java/org/jboss/logmanager/formatters/XmlFormatter.java b/src/main/java/org/jboss/logmanager/formatters/XmlFormatter.java index 08f37661..c3e39f9d 100644 --- a/src/main/java/org/jboss/logmanager/formatters/XmlFormatter.java +++ b/src/main/java/org/jboss/logmanager/formatters/XmlFormatter.java @@ -21,6 +21,7 @@ import java.io.Writer; import java.util.Map; + import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; @@ -41,7 +42,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"}) +@SuppressWarnings({ "WeakerAccess", "unused", "SameParameterValue" }) public class XmlFormatter extends StructuredFormatter { public static final String DEFAULT_NAMESPACE = "urn:jboss:logmanager:formatter:1.0"; @@ -89,7 +90,7 @@ public XmlFormatter(final String keyOverrides) { public XmlFormatter(final Map keyOverrides) { super(keyOverrides); if (keyOverrides == null || keyOverrides.isEmpty()) { - namespaceUri = DEFAULT_NAMESPACE; + namespaceUri = DEFAULT_NAMESPACE; } else { namespaceUri = null; } @@ -272,17 +273,19 @@ private void writeEnd() throws XMLStreamException { } private void safeFlush(final XMLStreamWriter flushable) { - if (flushable != null) try { - flushable.flush(); - } catch (Throwable ignore) { - } + if (flushable != null) + try { + flushable.flush(); + } catch (Throwable ignore) { + } } private void safeClose(final XMLStreamWriter closeable) { - if (closeable != null) try { - closeable.close(); - } catch (Throwable ignore) { - } + if (closeable != null) + try { + closeable.close(); + } catch (Throwable ignore) { + } } } } diff --git a/src/main/java/org/jboss/logmanager/handlers/AsyncHandler.java b/src/main/java/org/jboss/logmanager/handlers/AsyncHandler.java index a73ef858..7f366db8 100644 --- a/src/main/java/org/jboss/logmanager/handlers/AsyncHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/AsyncHandler.java @@ -24,7 +24,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -import java.util.logging.ErrorManager; import java.util.logging.Handler; import org.jboss.logmanager.ExtHandler; @@ -44,14 +43,15 @@ public class AsyncHandler extends ExtHandler { @SuppressWarnings("unused") private volatile int state; - private static final AtomicIntegerFieldUpdater stateUpdater = AtomicIntegerFieldUpdater.newUpdater(AsyncHandler.class, "state"); + private static final AtomicIntegerFieldUpdater stateUpdater = AtomicIntegerFieldUpdater + .newUpdater(AsyncHandler.class, "state"); private static final int DEFAULT_QUEUE_LENGTH = 512; /** * Construct a new instance. * - * @param queueLength the queue length + * @param queueLength the queue length * @param threadFactory the thread factory to use to construct the handler thread */ public AsyncHandler(final int queueLength, final ThreadFactory threadFactory) { diff --git a/src/main/java/org/jboss/logmanager/handlers/ByteStringBuilder.java b/src/main/java/org/jboss/logmanager/handlers/ByteStringBuilder.java index 6f999bb7..e720ae9a 100644 --- a/src/main/java/org/jboss/logmanager/handlers/ByteStringBuilder.java +++ b/src/main/java/org/jboss/logmanager/handlers/ByteStringBuilder.java @@ -27,7 +27,7 @@ * @author David M. Lloyd * @author James R. Perkins */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({ "unused", "WeakerAccess" }) final class ByteStringBuilder implements Appendable { private static final int INVALID_US_ASCII_CODE_POINT = 0x3f; @@ -235,7 +235,8 @@ public byte[] toArray() { } public byte byteAt(final int index) { - if (index < 0 || index > length) throw new IndexOutOfBoundsException(); + if (index < 0 || index > length) + throw new IndexOutOfBoundsException(); return content[index]; } @@ -260,7 +261,8 @@ public boolean contentEquals(final byte[] other) { } public boolean contentEquals(final byte[] other, final int offs, final int length) { - if (length != this.length) return false; + if (length != this.length) + return false; for (int i = 0; i < length; i++) { if (content[i] != other[offs + i]) { return false; @@ -273,7 +275,8 @@ private ByteStringBuilder appendASCII(final int asciiLen, final String s, final return appendASCII(0, asciiLen, s, offs, len, maxLen); } - private ByteStringBuilder appendASCII(final int minChar, final int maxChar, final String s, final int offs, final int len, final int maxLen) { + private ByteStringBuilder appendASCII(final int minChar, final int maxChar, final String s, final int offs, final int len, + final int maxLen) { reserve(len, false); char c; for (int i = 0; i < len; i++) { @@ -295,15 +298,18 @@ private void reserve(final int count, final boolean clear) { final byte[] content = this.content; int cl = content.length; if (cl - length >= count) { - if (clear) Arrays.fill(content, length, length + count, (byte) 0); + if (clear) + Arrays.fill(content, length, length + count, (byte) 0); return; } // clear remainder - if (clear) Arrays.fill(content, length, cl, (byte) 0); + if (clear) + Arrays.fill(content, length, cl, (byte) 0); do { // not enough space... grow by 1.5x cl = cl + (cl + 1 >> 1); - if (cl < 0) throw new IllegalStateException("Too large"); + if (cl < 0) + throw new IllegalStateException("Too large"); } while (cl - length < count); this.content = Arrays.copyOf(content, cl); } diff --git a/src/main/java/org/jboss/logmanager/handlers/ClientSocketFactory.java b/src/main/java/org/jboss/logmanager/handlers/ClientSocketFactory.java index 7e8d1503..e75129a7 100644 --- a/src/main/java/org/jboss/logmanager/handlers/ClientSocketFactory.java +++ b/src/main/java/org/jboss/logmanager/handlers/ClientSocketFactory.java @@ -26,6 +26,7 @@ import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; + import javax.net.SocketFactory; /** @@ -106,7 +107,8 @@ static ClientSocketFactory of(final InetAddress address, final int port) { */ static ClientSocketFactory of(final SocketFactory socketFactory, final InetAddress address, final int port) { if (address == null || port < 0) { - throw new IllegalArgumentException(String.format("The address cannot be null (%s) and the port must be a positive integer (%d)", address, port)); + throw new IllegalArgumentException(String + .format("The address cannot be null (%s) and the port must be a positive integer (%d)", address, port)); } final SocketFactory factory = (socketFactory == null ? SocketFactory.getDefault() : socketFactory); return new ClientSocketFactory() { diff --git a/src/main/java/org/jboss/logmanager/handlers/ConsoleHandler.java b/src/main/java/org/jboss/logmanager/handlers/ConsoleHandler.java index c968a7f2..5bed9a84 100644 --- a/src/main/java/org/jboss/logmanager/handlers/ConsoleHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/ConsoleHandler.java @@ -25,7 +25,6 @@ import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; - import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Objects; @@ -98,16 +97,23 @@ public ConsoleHandler(final Target target) { /** * Construct a new instance. * - * @param target the target to write to, or {@code null} to start with an uninitialized target + * @param target the target to write to, or {@code null} to start with an uninitialized target * @param formatter the formatter to use */ public ConsoleHandler(final Target target, final Formatter formatter) { super(formatter); switch (target) { - case SYSTEM_OUT: setOutputStream(wrap(out)); break; - case SYSTEM_ERR: setOutputStream(wrap(err)); break; - case CONSOLE: setWriter(wrap(console)); break; - default: throw new IllegalArgumentException(); + case SYSTEM_OUT: + setOutputStream(wrap(out)); + break; + case SYSTEM_ERR: + setOutputStream(wrap(err)); + break; + case CONSOLE: + setWriter(wrap(console)); + break; + default: + throw new IllegalArgumentException(); } } @@ -119,10 +125,17 @@ public ConsoleHandler(final Target target, final Formatter formatter) { public void setTarget(Target target) { final Target t = (target == null ? console == null ? Target.SYSTEM_OUT : Target.CONSOLE : target); switch (t) { - case SYSTEM_OUT: setOutputStream(wrap(out)); break; - case SYSTEM_ERR: setOutputStream(wrap(err)); break; - case CONSOLE: setWriter(wrap(console)); break; - default: throw new IllegalArgumentException(); + case SYSTEM_OUT: + setOutputStream(wrap(out)); + break; + case SYSTEM_ERR: + setOutputStream(wrap(err)); + break; + case CONSOLE: + setWriter(wrap(console)); + break; + default: + throw new IllegalArgumentException(); } } @@ -142,8 +155,8 @@ public void setErrorManager(final ErrorManager em) { * The image data stream must be closed by the caller. * * @param imageData the PNG image data stream to write (must not be {@code null}) - * @param columns the number of text columns to occupy (0 for automatic) - * @param rows the number of text rows to occupy (0 for automatic) + * @param columns the number of text columns to occupy (0 for automatic) + * @param rows the number of text rows to occupy (0 for automatic) * @return {@code true} if the image was written, or {@code false} if image support isn't found * @throws IOException if the stream failed while writing the image */ @@ -151,7 +164,7 @@ public boolean writeImagePng(InputStream imageData, int columns, int rows) throw Objects.requireNonNull(imageData, "imageData"); columns = Math.max(0, columns); rows = Math.max(0, rows); - if (! isGraphicsSupportPassivelyDetected()) { + if (!isGraphicsSupportPassivelyDetected()) { // no graphics return false; } @@ -159,14 +172,16 @@ public boolean writeImagePng(InputStream imageData, int columns, int rows) throw try { // clear out any pending stuff final Writer writer = getWriter(); - if (writer == null) return false; + if (writer == null) + return false; // start with the header try (OutputStream os = Base64.getEncoder().wrap(new OutputStream() { final byte[] buffer = new byte[2048]; int pos = 0; public void write(final int b) throws IOException { - if (pos == buffer.length) more(); + if (pos == buffer.length) + more(); buffer[pos++] = (byte) b; } @@ -213,7 +228,7 @@ public void close() throws IOException { } /** - * Get the local error manager. This is an error manager that will publish errors to this console handler. + * Get the local error manager. This is an error manager that will publish errors to this console handler. * The console handler itself should not use this error manager. * * @return the local error manager @@ -223,19 +238,12 @@ public ErrorManager getLocalErrorManager() { } private static OutputStream wrap(final OutputStream outputStream) { - return outputStream == null ? - null : - outputStream instanceof UncloseableOutputStream ? - outputStream : - new UncloseableOutputStream(outputStream); + return outputStream == null ? null + : outputStream instanceof UncloseableOutputStream ? outputStream : new UncloseableOutputStream(outputStream); } private static Writer wrap(final Writer writer) { - return writer == null ? - null : - writer instanceof UncloseableWriter ? - writer : - new UncloseableWriter(writer); + return writer == null ? null : writer instanceof UncloseableWriter ? writer : new UncloseableWriter(writer); } /** {@inheritDoc} */ @@ -262,7 +270,7 @@ public static boolean hasConsole() { * @return {@code true} if the console exists and supports truecolor output; {@code false} otherwise */ public static boolean isTrueColor() { - if (! hasConsole()) { + if (!hasConsole()) { return false; } final String colorterm = System.getenv("COLORTERM"); @@ -275,10 +283,10 @@ public static boolean isTrueColor() { * this information. * * @return {@code true} if the console exists and supports graphical output; {@code false} otherwise or if - * graphical support cannot be passively detected + * graphical support cannot be passively detected */ public static boolean isGraphicsSupportPassivelyDetected() { - if (! hasConsole()) { + if (!hasConsole()) { return false; } final String term = System.getenv("TERM"); @@ -286,7 +294,6 @@ public static boolean isGraphicsSupportPassivelyDetected() { return term != null && (term.equalsIgnoreCase("kitty") || term.equalsIgnoreCase("xterm-kitty") || term.equalsIgnoreCase("wezterm") - || term.equalsIgnoreCase("konsole") - ) || termProgram != null && termProgram.equalsIgnoreCase("wezterm"); + || term.equalsIgnoreCase("konsole")) || termProgram != null && termProgram.equalsIgnoreCase("wezterm"); } } diff --git a/src/main/java/org/jboss/logmanager/handlers/DelayedHandler.java b/src/main/java/org/jboss/logmanager/handlers/DelayedHandler.java index 15f100f9..27b2586b 100644 --- a/src/main/java/org/jboss/logmanager/handlers/DelayedHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/DelayedHandler.java @@ -44,7 +44,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({ "unused", "WeakerAccess" }) public class DelayedHandler extends ExtHandler { private final Map> queues = new HashMap<>(); @@ -98,7 +98,7 @@ public DelayedHandler(LogContext logContext, int queueLimit) { * The given queue limit value is used to limit the length of each level queue. * The warning threshold specifies that only queues with the threshold level or higher will report overrun errors. * - * @param queueLimit the queue limit + * @param queueLimit the queue limit * @param warnThreshold the threshold level to report queue overruns for */ public DelayedHandler(int queueLimit, Level warnThreshold) { @@ -110,8 +110,8 @@ public DelayedHandler(int queueLimit, Level warnThreshold) { * The given queue limit value is used to limit the length of each level queue. * The warning threshold specifies that only queues with the threshold level or higher will report overrun errors. * - * @param logContext the log context to use for level checks on replay, or {@code null} for none - * @param queueLimit the queue limit + * @param logContext the log context to use for level checks on replay, or {@code null} for none + * @param queueLimit the queue limit * @param warnThreshold the threshold level to report queue overruns for */ public DelayedHandler(LogContext logContext, int queueLimit, Level warnThreshold) { @@ -151,7 +151,9 @@ protected void doPublish(final ExtLogRecord record) { Level level = record.getLevel(); Deque q = queues.computeIfAbsent(level, DelayedHandler::newDeque); if (q.size() >= queueLimit && level.intValue() >= warnThreshold.intValue()) { - reportError("The delayed handler's queue was overrun and log record(s) were lost. Did you forget to configure logging?", null, ErrorManager.WRITE_FAILURE); + reportError( + "The delayed handler's queue was overrun and log record(s) were lost. Did you forget to configure logging?", + null, ErrorManager.WRITE_FAILURE); } enqueueOrdered(q, record); } @@ -164,7 +166,7 @@ protected void doPublish(final ExtLogRecord record) { /** * Enqueue the log record such that the queue's order (by sequence number) is maintained. * - * @param q the queue + * @param q the queue * @param record the record */ private void enqueueOrdered(Deque q, ExtLogRecord record) { @@ -206,7 +208,7 @@ private Supplier drain() { public ExtLogRecord get() { ExtLogRecord min = null; int minIdx = 0; - for (int i = 0; i < size; i ++) { + for (int i = 0; i < size; i++) { ExtLogRecord item = current.get(i); if (compareSeq(min, item) > 0) { min = item; @@ -244,7 +246,7 @@ public final void close() throws SecurityException { formatter = new PatternFormatter("%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n"); } StandardOutputStreams.printError("The DelayedHandler was closed before any children handlers were " + - "configured. Messages will be written to stderr."); + "configured. Messages will be written to stderr."); // Always attempt to drain the queue Supplier drain = drain(); ExtLogRecord record; @@ -367,7 +369,8 @@ private void activate() { final LogContext logContext = this.logContext; Supplier drain = drain(); while ((record = drain.get()) != null) { - if (isEnabled() && isLoggable(record) && (logContext == null || logContext.getLogger(record.getLoggerName()).isLoggable(record.getLevel()))) { + if (isEnabled() && isLoggable(record) + && (logContext == null || logContext.getLogger(record.getLoggerName()).isLoggable(record.getLevel()))) { publishToNestedHandlers(record); } } diff --git a/src/main/java/org/jboss/logmanager/handlers/FileHandler.java b/src/main/java/org/jboss/logmanager/handlers/FileHandler.java index fe2c8e82..5853f881 100644 --- a/src/main/java/org/jboss/logmanager/handlers/FileHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/FileHandler.java @@ -53,7 +53,7 @@ public FileHandler(final Formatter formatter) { * Construct a new instance with the given formatter and output file. * * @param formatter the formatter - * @param file the file + * @param file the file * @throws FileNotFoundException if the file could not be found on open */ public FileHandler(final Formatter formatter, final File file) throws FileNotFoundException { @@ -65,8 +65,8 @@ public FileHandler(final Formatter formatter, final File file) throws FileNotFou * Construct a new instance with the given formatter, output file, and append setting. * * @param formatter the formatter - * @param file the file - * @param append {@code true} to append, {@code false} to overwrite + * @param file the file + * @param append {@code true} to append, {@code false} to overwrite * @throws FileNotFoundException if the file could not be found on open */ public FileHandler(final Formatter formatter, final File file, final boolean append) throws FileNotFoundException { @@ -88,7 +88,7 @@ public FileHandler(final File file) throws FileNotFoundException { /** * Construct a new instance with the given output file and append setting. * - * @param file the file + * @param file the file * @param append {@code true} to append, {@code false} to overwrite * @throws FileNotFoundException if the file could not be found on open */ @@ -111,7 +111,7 @@ public FileHandler(final String fileName) throws FileNotFoundException { * Construct a new instance with the given output file and append setting. * * @param fileName the file name - * @param append {@code true} to append, {@code false} to overwrite + * @param append {@code true} to append, {@code false} to overwrite * @throws FileNotFoundException if the file could not be found on open */ public FileHandler(final String fileName, final boolean append) throws FileNotFoundException { @@ -160,12 +160,12 @@ public void setFile(File file) throws FileNotFoundException { this.file = file; ok = true; } finally { - if (! ok) { + if (!ok) { safeClose(bos); } } } finally { - if (! ok) { + if (!ok) { safeClose(fos); } } diff --git a/src/main/java/org/jboss/logmanager/handlers/OutputStreamHandler.java b/src/main/java/org/jboss/logmanager/handlers/OutputStreamHandler.java index de1af7c2..e8d9fc6e 100644 --- a/src/main/java/org/jboss/logmanager/handlers/OutputStreamHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/OutputStreamHandler.java @@ -19,17 +19,17 @@ package org.jboss.logmanager.handlers; -import org.jboss.logmanager.formatters.Formatters; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; - import java.nio.charset.Charset; import java.util.logging.ErrorManager; import java.util.logging.Formatter; +import org.jboss.logmanager.formatters.Formatters; + /** - * An output stream handler which supports any {@code OutputStream}, using the specified encoding. If no encoding is + * An output stream handler which supports any {@code OutputStream}, using the specified encoding. If no encoding is * specified, the platform default is used. */ public class OutputStreamHandler extends WriterHandler { @@ -56,7 +56,7 @@ public OutputStreamHandler(final Formatter formatter) { * Construct a new instance. * * @param outputStream the output stream to use - * @param formatter the formatter to use + * @param formatter the formatter to use */ public OutputStreamHandler(final OutputStream outputStream, final Formatter formatter) { setFormatter(formatter); @@ -88,7 +88,7 @@ public Charset getCharset() { } } - /** {@inheritDoc} Setting a writer will replace any target output stream. */ + /** {@inheritDoc} Setting a writer will replace any target output stream. */ public void setWriter(final Writer writer) { lock.lock(); try { @@ -103,7 +103,7 @@ public void setWriter(final Writer writer) { } /** - * Set the output stream to write to. The output stream will then belong to this handler; when the handler is + * Set the output stream to write to. The output stream will then belong to this handler; when the handler is * closed or a new writer or output stream is set, this output stream will be closed. * * @param outputStream the new output stream or {@code null} for none @@ -144,8 +144,10 @@ OutputStream getOutputStream() { } private Writer getNewWriter(OutputStream newOutputStream) { - if (newOutputStream == null) return null; - final UninterruptibleOutputStream outputStream = new UninterruptibleOutputStream(new UncloseableOutputStream(newOutputStream)); + if (newOutputStream == null) + return null; + final UninterruptibleOutputStream outputStream = new UninterruptibleOutputStream( + new UncloseableOutputStream(newOutputStream)); return new OutputStreamWriter(outputStream, getCharset()); } } diff --git a/src/main/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandler.java b/src/main/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandler.java index db857e43..5efa6e5b 100644 --- a/src/main/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandler.java @@ -36,7 +36,7 @@ import org.jboss.logmanager.ExtLogRecord; /** - * A file handler which rotates the log at a preset time interval. The interval is determined by the content of the + * A file handler which rotates the log at a preset time interval. The interval is determined by the content of the * suffix string which is passed in to {@link #setSuffix(String)}. */ public class PeriodicRotatingFileHandler extends FileHandler { @@ -70,7 +70,7 @@ public PeriodicRotatingFileHandler(final String fileName) throws FileNotFoundExc * Construct a new instance with the given output file and append setting. * * @param fileName the file name - * @param append {@code true} to append, {@code false} to overwrite + * @param append {@code true} to append, {@code false} to overwrite * * @throws FileNotFoundException if the file could not be found on open */ @@ -81,7 +81,7 @@ public PeriodicRotatingFileHandler(final String fileName, final boolean append) /** * Construct a new instance with the given output file. * - * @param file the file + * @param file the file * @param suffix the format suffix to use * * @throws FileNotFoundException if the file could not be found on open @@ -94,12 +94,13 @@ public PeriodicRotatingFileHandler(final File file, final String suffix) throws /** * Construct a new instance with the given output file and append setting. * - * @param file the file + * @param file the file * @param suffix the format suffix to use * @param append {@code true} to append, {@code false} to overwrite * @throws FileNotFoundException if the file could not be found on open */ - public PeriodicRotatingFileHandler(final File file, final String suffix, final boolean append) throws FileNotFoundException { + public PeriodicRotatingFileHandler(final File file, final String suffix, final boolean append) + throws FileNotFoundException { super(file, append); setSuffix(suffix); } @@ -117,17 +118,17 @@ public void setFile(final File file) throws FileNotFoundException { } } - /** {@inheritDoc} This implementation checks to see if the scheduled rollover time has yet occurred. */ + /** {@inheritDoc} This implementation checks to see if the scheduled rollover time has yet occurred. */ protected void preWrite(final ExtLogRecord record) { Instant recordInstant = record.getInstant(); - if (! recordInstant.isBefore(nextRollover)) { + if (!recordInstant.isBefore(nextRollover)) { rollOver(); calcNextRollover(recordInstant); } } /** - * Set the suffix string. The string is in a format which can be understood by {@link DateTimeFormatter}. + * Set the suffix string. The string is in a format which can be understood by {@link DateTimeFormatter}. * The period of the rotation is automatically calculated based on the suffix. *

    * If the suffix ends with {@code .gz} or {@code .zip} the file will be compressed on rotation. @@ -142,25 +143,43 @@ public void setSuffix(String suffix) throws IllegalArgumentException { final DateTimeFormatter format = DateTimeFormatter.ofPattern(dateSuffix).withZone(timeZone.toZoneId()); final int len = dateSuffix.length(); Period period = Period.NEVER; - for (int i = 0; i < len; i ++) { + for (int i = 0; i < len; i++) { switch (dateSuffix.charAt(i)) { - case 'y': period = min(period, Period.YEAR); break; - case 'M': period = min(period, Period.MONTH); break; + case 'y': + period = min(period, Period.YEAR); + break; + case 'M': + period = min(period, Period.MONTH); + break; case 'w': - case 'W': period = min(period, Period.WEEK); break; + case 'W': + period = min(period, Period.WEEK); + break; case 'D': case 'd': case 'F': - case 'E': period = min(period, Period.DAY); break; - case 'a': period = min(period, Period.HALF_DAY); break; + case 'E': + period = min(period, Period.DAY); + break; + case 'a': + period = min(period, Period.HALF_DAY); + break; case 'H': case 'k': case 'K': - case 'h': period = min(period, Period.HOUR); break; - case 'm': period = min(period, Period.MINUTE); break; - case '\'': while (dateSuffix.charAt(++i) != '\''); break; + case 'h': + period = min(period, Period.HOUR); + break; + case 'm': + period = min(period, Period.MINUTE); + break; + case '\'': + while (dateSuffix.charAt(++i) != '\'') + ; + break; case 's': - case 'S': throw new IllegalArgumentException("Rotating by second or millisecond is not supported"); + case 'S': + throw new IllegalArgumentException("Rotating by second or millisecond is not supported"); } } lock.lock(); @@ -295,7 +314,7 @@ private static > T min(T a, T b) { } /** - * Possible period values. Keep in strictly ascending order of magnitude. + * Possible period values. Keep in strictly ascending order of magnitude. */ public enum Period { MINUTE, diff --git a/src/main/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandler.java b/src/main/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandler.java index 7f6275d3..1fdacdba 100644 --- a/src/main/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandler.java @@ -100,7 +100,8 @@ public PeriodicSizeRotatingFileHandler(final File file, final String suffix) thr * * @throws FileNotFoundException if the file could not be found on open */ - public PeriodicSizeRotatingFileHandler(final File file, final String suffix, final boolean append) throws FileNotFoundException { + public PeriodicSizeRotatingFileHandler(final File file, final String suffix, final boolean append) + throws FileNotFoundException { super(file, suffix, append); } @@ -114,7 +115,8 @@ public PeriodicSizeRotatingFileHandler(final File file, final String suffix, fin * * @throws FileNotFoundException if the file could not be found on open */ - public PeriodicSizeRotatingFileHandler(final File file, final String suffix, final long rotateSize, final int maxBackupIndex) throws FileNotFoundException { + public PeriodicSizeRotatingFileHandler(final File file, final String suffix, final long rotateSize, + final int maxBackupIndex) throws FileNotFoundException { super(file, suffix); this.rotateSize = rotateSize; this.maxBackupIndex = maxBackupIndex; @@ -131,13 +133,13 @@ public PeriodicSizeRotatingFileHandler(final File file, final String suffix, fin * * @throws FileNotFoundException if the file could not be found on open */ - public PeriodicSizeRotatingFileHandler(final File file, final String suffix, final long rotateSize, final int maxBackupIndex, final boolean append) throws FileNotFoundException { + public PeriodicSizeRotatingFileHandler(final File file, final String suffix, final long rotateSize, + final int maxBackupIndex, final boolean append) throws FileNotFoundException { super(file, suffix, append); this.rotateSize = rotateSize; this.maxBackupIndex = maxBackupIndex; } - @Override public void setOutputStream(final OutputStream outputStream) { lock.lock(); @@ -249,7 +251,8 @@ protected void preWrite(final ExtLogRecord record) { } // close the old file. setFileInternal(null, true); - getSuffixRotator().rotate(SecurityActions.getErrorManager(acc, this), file.toPath(), getNextSuffix(), maxBackupIndex); + getSuffixRotator().rotate(SecurityActions.getErrorManager(acc, this), file.toPath(), getNextSuffix(), + maxBackupIndex); // start with new file. setFileInternal(file, true); } catch (IOException e) { diff --git a/src/main/java/org/jboss/logmanager/handlers/QueueHandler.java b/src/main/java/org/jboss/logmanager/handlers/QueueHandler.java index 38bf8b2f..70789ed5 100644 --- a/src/main/java/org/jboss/logmanager/handlers/QueueHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/QueueHandler.java @@ -26,12 +26,13 @@ import java.util.logging.Handler; import java.util.logging.LogRecord; -import io.smallrye.common.constraint.Assert; import org.jboss.logmanager.ExtHandler; import org.jboss.logmanager.ExtLogRecord; +import io.smallrye.common.constraint.Assert; + /** - * A queue handler which retains the last few messages logged. The handler can be used as-is to remember recent + * A queue handler which retains the last few messages logged. The handler can be used as-is to remember recent * messages, or one or more handlers may be nested, which allows this handler to "replay" messages to the child * handler(s) upon request. * @@ -85,7 +86,9 @@ protected void doPublish(final ExtLogRecord record) { // Copy the MDC over record.copyMdc(); } - if (buffer.size() == limit) { buffer.removeFirst(); } + if (buffer.size() == limit) { + buffer.removeFirst(); + } buffer.addLast(record); } publishToNestedHandlers(record); @@ -95,7 +98,7 @@ protected void doPublish(final ExtLogRecord record) { } /** - * Get the queue length limit. This is the number of messages that will be saved before old messages roll off + * Get the queue length limit. This is the number of messages that will be saved before old messages roll off * of the queue. * * @return the queue length limit @@ -110,7 +113,7 @@ public int getLimit() { } /** - * Set the queue length limit. This is the number of messages that will be saved before old messages roll off + * Set the queue length limit. This is the number of messages that will be saved before old messages roll off * of the queue. * * @param limit the queue length limit @@ -137,7 +140,7 @@ public void addHandler(Handler handler) throws SecurityException { * all queued messages as well as all subsequent messages with no loss or reorder in between. * * @param handler the handler to add (must not be {@code null}) - * @param replay {@code true} to replay the prior messages, or {@code false} to add the handler without replaying + * @param replay {@code true} to replay the prior messages, or {@code false} to add the handler without replaying * @throws SecurityException if the handler was not allowed to be added */ public void addHandler(Handler handler, boolean replay) throws SecurityException { @@ -200,11 +203,12 @@ public String[] getQueueAsStrings() { */ public void replay() { final Handler[] handlers = getHandlers(); - if (handlers.length > 0) for (ExtLogRecord record : getQueue()) { - for (Handler handler : handlers) { - handler.publish(record); + if (handlers.length > 0) + for (ExtLogRecord record : getQueue()) { + for (Handler handler : handlers) { + handler.publish(record); + } } - } } private static IllegalArgumentException badQueueLength() { diff --git a/src/main/java/org/jboss/logmanager/handlers/SizeRotatingFileHandler.java b/src/main/java/org/jboss/logmanager/handlers/SizeRotatingFileHandler.java index 84f232dc..0f2088d1 100644 --- a/src/main/java/org/jboss/logmanager/handlers/SizeRotatingFileHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/SizeRotatingFileHandler.java @@ -60,7 +60,7 @@ public SizeRotatingFileHandler(final File file) throws FileNotFoundException { /** * Construct a new instance with the given output file and append setting. * - * @param file the file + * @param file the file * @param append {@code true} to append, {@code false} to overwrite * * @throws FileNotFoundException if the file could not be found on open @@ -84,7 +84,7 @@ public SizeRotatingFileHandler(final String fileName) throws FileNotFoundExcepti * Construct a new instance with the given output file and append setting. * * @param fileName the file name - * @param append {@code true} to append, {@code false} to overwrite + * @param append {@code true} to append, {@code false} to overwrite * * @throws FileNotFoundException if the file could not be found on open */ @@ -107,7 +107,8 @@ public SizeRotatingFileHandler(final long rotateSize, final int maxBackupIndex) * * @throws FileNotFoundException if the file could not be found on open */ - public SizeRotatingFileHandler(final File file, final long rotateSize, final int maxBackupIndex) throws FileNotFoundException { + public SizeRotatingFileHandler(final File file, final long rotateSize, final int maxBackupIndex) + throws FileNotFoundException { super(file); this.rotateSize = rotateSize; this.maxBackupIndex = maxBackupIndex; @@ -116,12 +117,13 @@ public SizeRotatingFileHandler(final File file, final long rotateSize, final int /** * Construct a new instance with the given output file and append setting. * - * @param file the file + * @param file the file * @param append {@code true} to append, {@code false} to overwrite * * @throws FileNotFoundException if the file could not be found on open */ - public SizeRotatingFileHandler(final File file, final boolean append, final long rotateSize, final int maxBackupIndex) throws FileNotFoundException { + public SizeRotatingFileHandler(final File file, final boolean append, final long rotateSize, final int maxBackupIndex) + throws FileNotFoundException { super(file, append); this.rotateSize = rotateSize; this.maxBackupIndex = maxBackupIndex; diff --git a/src/main/java/org/jboss/logmanager/handlers/SocketHandler.java b/src/main/java/org/jboss/logmanager/handlers/SocketHandler.java index 539d3c1a..2c10bd8e 100644 --- a/src/main/java/org/jboss/logmanager/handlers/SocketHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/SocketHandler.java @@ -30,6 +30,7 @@ import java.net.UnknownHostException; import java.util.logging.ErrorManager; import java.util.logging.Formatter; + import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; @@ -41,7 +42,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({ "unused", "WeakerAccess" }) public class SocketHandler extends ExtHandler { /** @@ -144,7 +145,8 @@ public SocketHandler(final Protocol protocol, final InetAddress address, final i * @throws UnknownHostException if an error occurs resolving the hostname * @see #SocketHandler(ClientSocketFactory, Protocol) */ - public SocketHandler(final SocketFactory socketFactory, final Protocol protocol, final String hostname, final int port) throws UnknownHostException { + public SocketHandler(final SocketFactory socketFactory, final Protocol protocol, final String hostname, final int port) + throws UnknownHostException { this(socketFactory, protocol, InetAddress.getByName(hostname), port); } @@ -160,7 +162,8 @@ public SocketHandler(final SocketFactory socketFactory, final Protocol protocol, * * @see #SocketHandler(ClientSocketFactory, Protocol) */ - public SocketHandler(final SocketFactory socketFactory, final Protocol protocol, final InetAddress address, final int port) { + public SocketHandler(final SocketFactory socketFactory, final Protocol protocol, final InetAddress address, + final int port) { this.socketFactory = socketFactory; this.clientSocketFactory = null; this.address = address; @@ -514,7 +517,8 @@ private ClientSocketFactory getClientSocketFactory() { private void writeHead(final Writer writer) { try { final Formatter formatter = getFormatter(); - if (formatter != null) writer.write(formatter.getHead(this)); + if (formatter != null) + writer.write(formatter.getHead(this)); } catch (Exception e) { reportError("Error writing section header", e, ErrorManager.WRITE_FAILURE); } @@ -523,7 +527,8 @@ private void writeHead(final Writer writer) { private void writeTail(final Writer writer) { try { final Formatter formatter = getFormatter(); - if (formatter != null) writer.write(formatter.getTail(this)); + if (formatter != null) + writer.write(formatter.getTail(this)); } catch (Exception ex) { reportError("Error writing section tail", ex, ErrorManager.WRITE_FAILURE); } @@ -531,7 +536,8 @@ private void writeTail(final Writer writer) { private void safeClose(Closeable c) { try { - if (c != null) c.close(); + if (c != null) + c.close(); } catch (Exception e) { reportError("Error closing resource", e, ErrorManager.CLOSE_FAILURE); } catch (Throwable ignored) { @@ -540,10 +546,11 @@ private void safeClose(Closeable c) { private void safeFlush(Flushable f) { try { - if (f != null) f.flush(); + if (f != null) + f.flush(); } catch (Exception e) { reportError("Error on flush", e, ErrorManager.FLUSH_FAILURE); } catch (Throwable ignored) { } } -} \ No newline at end of file +} diff --git a/src/main/java/org/jboss/logmanager/handlers/SslTcpOutputStream.java b/src/main/java/org/jboss/logmanager/handlers/SslTcpOutputStream.java index b4dd838c..1d2014b9 100644 --- a/src/main/java/org/jboss/logmanager/handlers/SslTcpOutputStream.java +++ b/src/main/java/org/jboss/logmanager/handlers/SslTcpOutputStream.java @@ -22,6 +22,7 @@ import java.io.Flushable; import java.io.IOException; import java.net.InetAddress; + import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; @@ -31,7 +32,7 @@ * * @author James R. Perkins */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({ "unused", "WeakerAccess" }) public class SslTcpOutputStream extends TcpOutputStream implements AutoCloseable, Flushable { /** @@ -92,7 +93,8 @@ public SslTcpOutputStream(final InetAddress address, final int port, final boole * * @throws IOException if an I/O error occurs when creating the socket */ - public SslTcpOutputStream(final SocketFactory socketFactory, final InetAddress address, final int port, final boolean blockOnReconnect) throws IOException { + public SslTcpOutputStream(final SocketFactory socketFactory, final InetAddress address, final int port, + final boolean blockOnReconnect) throws IOException { super(socketFactory, address, port, blockOnReconnect); } } diff --git a/src/main/java/org/jboss/logmanager/handlers/SuffixRotator.java b/src/main/java/org/jboss/logmanager/handlers/SuffixRotator.java index c7f28c95..661e8d0b 100644 --- a/src/main/java/org/jboss/logmanager/handlers/SuffixRotator.java +++ b/src/main/java/org/jboss/logmanager/handlers/SuffixRotator.java @@ -68,7 +68,7 @@ public enum CompressionType { private final CompressionType compressionType; private SuffixRotator(final AccessControlContext acc, final String originalSuffix, final String datePattern, - final String compressionSuffix, final CompressionType compressionType) { + final String compressionSuffix, final CompressionType compressionType) { this.acc = acc; this.originalSuffix = originalSuffix; this.datePattern = datePattern; @@ -255,14 +255,14 @@ private void move(final ErrorManager errorManager, final Path src, final Path ta Files.move(src, target, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { // Report the error, but allow the rotation to continue - errorManager.error(String.format("Failed to move file %s to %s.", src, target), e, ErrorManager.GENERIC_FAILURE); + errorManager.error(String.format("Failed to move file %s to %s.", src, target), e, + ErrorManager.GENERIC_FAILURE); } } else { AccessController.doPrivileged(new MoveFileAction(errorManager, src, target), acc); } } - private void archiveGzip(final Path source, final Path target) throws IOException { final byte[] buff = new byte[512]; try (final GZIPOutputStream out = new GZIPOutputStream(newOutputStream(target), true)) { @@ -354,7 +354,8 @@ public Path run() { return Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { // Report the error, but allow the rotation to continue - errorManager.error(String.format("Failed to move file %s to %s.", source, target), e, ErrorManager.GENERIC_FAILURE); + errorManager.error(String.format("Failed to move file %s to %s.", source, target), e, + ErrorManager.GENERIC_FAILURE); } return null; } diff --git a/src/main/java/org/jboss/logmanager/handlers/SyslogHandler.java b/src/main/java/org/jboss/logmanager/handlers/SyslogHandler.java index ed28249e..f15391ba 100644 --- a/src/main/java/org/jboss/logmanager/handlers/SyslogHandler.java +++ b/src/main/java/org/jboss/logmanager/handlers/SyslogHandler.java @@ -42,11 +42,11 @@ import java.time.format.DateTimeFormatterBuilder; import java.time.format.TextStyle; import java.util.Collection; -import java.util.concurrent.locks.ReentrantLock; import java.util.logging.ErrorManager; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.regex.Pattern; + import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; @@ -61,6 +61,7 @@ * UDP protocols. You can also override the {@link #setOutputStream(OutputStream) output stream} if a custom * protocol is needed. *

    + * *

      * 
      *  
    @@ -104,7 +105,9 @@
      *          
      *          
    - *          
    + *          
      *      
      *      
      *          
    @@ -121,9 +124,13 @@
      *      
      *          
      *          
    + * is set to {@code
    + * true
    + * }
      *          
    - *          
      *      
      *      
    @@ -131,24 +138,35 @@
      *          
      *          
    - *          
    + *          
      *      
      *      
      *          
      *          
      *          
    - *          
    + *          
      *      
      *      
      *          
      *          
      *          
    - *          
    + *          
      *      
      *      
      *          
    @@ -164,7 +182,7 @@
      *
      * @author James R. Perkins
      */
    -@SuppressWarnings({"WeakerAccess", "unused"})
    +@SuppressWarnings({ "WeakerAccess", "unused" })
     public class SyslogHandler extends ExtHandler {
     
         /**
    @@ -228,7 +246,8 @@ public static Severity fromLevel(final Level level) {
                 final int levelValue = level.intValue();
                 if (levelValue >= org.jboss.logmanager.Level.FATAL.intValue()) {
                     return Severity.EMERGENCY;
    -            } else if (levelValue >= org.jboss.logmanager.Level.SEVERE.intValue() || levelValue >= org.jboss.logmanager.Level.ERROR.intValue()) {
    +            } else if (levelValue >= org.jboss.logmanager.Level.SEVERE.intValue()
    +                    || levelValue >= org.jboss.logmanager.Level.ERROR.intValue()) {
                     return Severity.ERROR;
                 } else if (levelValue >= org.jboss.logmanager.Level.WARN.intValue() || levelValue >= Level.WARNING.intValue()) {
                     return Severity.WARNING;
    @@ -293,12 +312,14 @@ public String toString() {
          */
         public static enum SyslogType {
             /**
    -         * Formats the message according the the RFC-5424 specification (http://tools.ietf.org/html/rfc5424#section-6
    +         * Formats the message according the the RFC-5424 specification
    +         * (http://tools.ietf.org/html/rfc5424#section-6
              */
             RFC5424,
     
             /**
    -         * Formats the message according the the RFC-3164 specification (http://tools.ietf.org/html/rfc3164#section-4.1
    +         * Formats the message according the the RFC-3164 specification
    +         * (http://tools.ietf.org/html/rfc3164#section-4.1
              */
             RFC3164,
         }
    @@ -385,7 +406,8 @@ public SyslogHandler(final InetAddress serverAddress, final int port) throws IOE
          *
          * @throws IOException if an error occurs creating the UDP socket
          */
    -    public SyslogHandler(final String serverHostname, final int port, final Facility facility, final String hostname) throws IOException {
    +    public SyslogHandler(final String serverHostname, final int port, final Facility facility, final String hostname)
    +            throws IOException {
             this(serverHostname, port, facility, null, hostname);
         }
     
    @@ -401,7 +423,8 @@ public SyslogHandler(final String serverHostname, final int port, final Facility
          *
          * @throws IOException if an error occurs creating the UDP socket
          */
    -    public SyslogHandler(final InetAddress serverAddress, final int port, final Facility facility, final String hostname) throws IOException {
    +    public SyslogHandler(final InetAddress serverAddress, final int port, final Facility facility, final String hostname)
    +            throws IOException {
             this(serverAddress, port, facility, null, hostname);
         }
     
    @@ -418,7 +441,8 @@ public SyslogHandler(final InetAddress serverAddress, final int port, final Faci
          *
          * @throws IOException if an error occurs creating the UDP socket
          */
    -    public SyslogHandler(final String serverHostname, final int port, final Facility facility, final SyslogType syslogType, final String hostname) throws IOException {
    +    public SyslogHandler(final String serverHostname, final int port, final Facility facility, final SyslogType syslogType,
    +            final String hostname) throws IOException {
             this(InetAddress.getByName(serverHostname), port, facility, syslogType, hostname);
         }
     
    @@ -435,7 +459,8 @@ public SyslogHandler(final String serverHostname, final int port, final Facility
          *
          * @throws IOException if an error occurs creating the UDP socket
          */
    -    public SyslogHandler(final InetAddress serverAddress, final int port, final Facility facility, final SyslogType syslogType, final String hostname) throws IOException {
    +    public SyslogHandler(final InetAddress serverAddress, final int port, final Facility facility, final SyslogType syslogType,
    +            final String hostname) throws IOException {
             this(serverAddress, port, facility, syslogType, null, hostname);
         }
     
    @@ -453,7 +478,8 @@ public SyslogHandler(final InetAddress serverAddress, final int port, final Faci
          *
          * @throws IOException if an error occurs creating the UDP socket
          */
    -    public SyslogHandler(final String serverHostname, final int port, final Facility facility, final SyslogType syslogType, final Protocol protocol, final String hostname) throws IOException {
    +    public SyslogHandler(final String serverHostname, final int port, final Facility facility, final SyslogType syslogType,
    +            final Protocol protocol, final String hostname) throws IOException {
             this(InetAddress.getByName(serverHostname), port, facility, syslogType, protocol, hostname);
         }
     
    @@ -471,7 +497,8 @@ public SyslogHandler(final String serverHostname, final int port, final Facility
          *
          * @throws IOException if an error occurs creating the UDP socket
          */
    -    public SyslogHandler(final InetAddress serverAddress, final int port, final Facility facility, final SyslogType syslogType, final Protocol protocol, final String hostname) throws IOException {
    +    public SyslogHandler(final InetAddress serverAddress, final int port, final Facility facility, final SyslogType syslogType,
    +            final Protocol protocol, final String hostname) throws IOException {
             setCharsetPrivate(StandardCharsets.UTF_8);
             this.serverAddress = serverAddress;
             this.port = port;
    @@ -527,14 +554,15 @@ public final void doPublish(final ExtLogRecord record) {
                     }
     
                     // Trailer in bytes
    -                final byte[] trailer = delimiter == null ? new byte[] {0x00} : delimiter.getBytes(StandardCharsets.UTF_8);
    +                final byte[] trailer = delimiter == null ? new byte[] { 0x00 } : delimiter.getBytes(StandardCharsets.UTF_8);
     
                     // Buffer currently only has the header
                     final int maxMsgLen = maxLen - (header.length + (useDelimiter ? trailer.length : 0));
                     // Can't write the message if the header and trailer are bigger than the allowed length
                     if (maxMsgLen < 1) {
    -                    throw new IOException(String.format("The header and delimiter length, %d, is greater than the message length, %d, allows.",
    -                        (header.length + (useDelimiter ? trailer.length : 0)), maxLen));
    +                    throw new IOException(String.format(
    +                            "The header and delimiter length, %d, is greater than the message length, %d, allows.",
    +                            (header.length + (useDelimiter ? trailer.length : 0)), maxLen));
                     }
     
                     // Get the message
    @@ -592,7 +620,8 @@ private void sendMessage(final byte[] header, final ByteStringBuilder message, f
             }
             payload.append(header);
             payload.append(message);
    -        if (useDelimiter) payload.append(trailer);
    +        if (useDelimiter)
    +            payload.append(trailer);
             out.write(payload.toArray());
             // If this is a TcpOutputStream print any errors that may have occurred
             if (out instanceof TcpOutputStream) {
    @@ -720,8 +749,9 @@ public void setClientSocketFactory(final ClientSocketFactory clientSocketFactory
          *
          * @return {@code false}
          *
    -     * @deprecated escaping message values is not required per RFC5424
    -     * and is no longer supported in this handler
    +     * @deprecated escaping message values is not required per
    +     *             RFC5424
    +     *             and is no longer supported in this handler
          */
         @Deprecated
         public boolean isEscapeEnabled() {
    @@ -737,8 +767,9 @@ public boolean isEscapeEnabled() {
          *
          * @param escapeEnabled {@code true} to escape characters, {@code false} to not escape characters
          *
    -     * @deprecated escaping message values is not required per RFC5424
    -     * and is no longer supported in this handler
    +     * @deprecated escaping message values is not required per
    +     *             RFC5424
    +     *             and is no longer supported in this handler
          */
         @Deprecated
         public void setEscapeEnabled(final boolean escapeEnabled) {
    @@ -1174,30 +1205,34 @@ private void setOutputStream(final OutputStream out, final boolean outputStreamS
                 }
             } finally {
                 safeClose(oldOut);
    -            if (!ok) safeClose(out);
    +            if (!ok)
    +                safeClose(out);
             }
         }
     
         static void safeClose(final Closeable closeable) {
    -        if (closeable != null) try {
    -            closeable.close();
    -        } catch (Exception ignore) {
    -            // ignore
    -        }
    +        if (closeable != null)
    +            try {
    +                closeable.close();
    +            } catch (Exception ignore) {
    +                // ignore
    +            }
         }
     
         static void safeFlush(final Flushable flushable) {
    -        if (flushable != null) try {
    -            flushable.flush();
    -        } catch (Exception ignore) {
    -            // ignore
    -        }
    +        if (flushable != null)
    +            try {
    +                flushable.flush();
    +            } catch (Exception ignore) {
    +                // ignore
    +            }
         }
     
         private void init() {
             if (initializeConnection && !outputStreamSet) {
                 if (serverAddress == null || port < 0 || protocol == null) {
    -                throw new IllegalStateException("Invalid connection parameters. The port, server address and protocol must be set.");
    +                throw new IllegalStateException(
    +                        "Invalid connection parameters. The port, server address and protocol must be set.");
                 }
                 initializeConnection = false;
                 final OutputStream out;
    @@ -1362,7 +1397,8 @@ private ClientSocketFactory getClientSocketFactory() {
                 if (clientSocketFactory != null) {
                     return clientSocketFactory;
                 }
    -            final SocketFactory socketFactory = (protocol == Protocol.SSL_TCP ? SSLSocketFactory.getDefault() : SocketFactory.getDefault());
    +            final SocketFactory socketFactory = (protocol == Protocol.SSL_TCP ? SSLSocketFactory.getDefault()
    +                    : SocketFactory.getDefault());
                 return ClientSocketFactory.of(socketFactory, serverAddress, port);
             } finally {
                 lock.unlock();
    @@ -1372,7 +1408,8 @@ private ClientSocketFactory getClientSocketFactory() {
         private static String checkPrintableAscii(final String name, final String value) {
             if (value != null && PRINTABLE_ASCII_PATTERN.matcher(value).find()) {
                 final String upper = Character.toUpperCase(name.charAt(0)) + name.substring(1);
    -            throw new IllegalArgumentException(String.format("%s '%s' is invalid. The %s must be printable ASCII characters with no spaces.", upper, value, name));
    +            throw new IllegalArgumentException(String.format(
    +                    "%s '%s' is invalid. The %s must be printable ASCII characters with no spaces.", upper, value, name));
             }
             return value;
         }
    diff --git a/src/main/java/org/jboss/logmanager/handlers/TcpOutputStream.java b/src/main/java/org/jboss/logmanager/handlers/TcpOutputStream.java
    index 49f8c628..cb02659d 100644
    --- a/src/main/java/org/jboss/logmanager/handlers/TcpOutputStream.java
    +++ b/src/main/java/org/jboss/logmanager/handlers/TcpOutputStream.java
    @@ -49,7 +49,7 @@
      *
      * @author James R. Perkins
      */
    -@SuppressWarnings({"unused", "WeakerAccess"})
    +@SuppressWarnings({ "unused", "WeakerAccess" })
     public class TcpOutputStream extends OutputStream implements AutoCloseable, Flushable {
         private static final long retryTimeout = 5L;
         private static final long maxRetryTimeout = 40L;
    @@ -150,7 +150,8 @@ protected TcpOutputStream(final SocketFactory socketFactory, final InetAddress a
          * @throws IOException no longer throws an exception. If an exception occurs while attempting to connect the socket
          *                     a reconnect will be attempted on the next write.
          */
    -    protected TcpOutputStream(final SocketFactory socketFactory, final InetAddress address, final int port, final boolean blockOnReconnect) throws IOException {
    +    protected TcpOutputStream(final SocketFactory socketFactory, final InetAddress address, final int port,
    +            final boolean blockOnReconnect) throws IOException {
             this(ClientSocketFactory.of(socketFactory, address, port), blockOnReconnect);
         }
     
    @@ -174,7 +175,7 @@ public TcpOutputStream(final ClientSocketFactory socketFactory, final boolean bl
     
         @Override
         public void write(final int b) throws IOException {
    -        write(new byte[] {(byte) b}, 0, 1);
    +        write(new byte[] { (byte) b }, 0, 1);
         }
     
         @Override
    @@ -356,10 +357,11 @@ private Thread createThread() {
         }
     
         private static void safeClose(final Closeable closeable) {
    -        if (closeable != null) try {
    -            closeable.close();
    -        } catch (Exception ignore) {
    -        }
    +        if (closeable != null)
    +            try {
    +                closeable.close();
    +            } catch (Exception ignore) {
    +            }
         }
     
         private class RetryConnector implements Runnable {
    diff --git a/src/main/java/org/jboss/logmanager/handlers/UdpOutputStream.java b/src/main/java/org/jboss/logmanager/handlers/UdpOutputStream.java
    index 4e44dbea..0a8ded6f 100644
    --- a/src/main/java/org/jboss/logmanager/handlers/UdpOutputStream.java
    +++ b/src/main/java/org/jboss/logmanager/handlers/UdpOutputStream.java
    @@ -49,7 +49,7 @@ public UdpOutputStream(final ClientSocketFactory socketManager) throws SocketExc
     
         @Override
         public void write(final int b) throws IOException {
    -        final byte[] msg = new byte[] {(byte) b};
    +        final byte[] msg = new byte[] { (byte) b };
             final DatagramPacket packet = new DatagramPacket(msg, 1, socketAddress);
             socket.send(packet);
         }
    diff --git a/src/main/java/org/jboss/logmanager/handlers/UncloseableOutputStream.java b/src/main/java/org/jboss/logmanager/handlers/UncloseableOutputStream.java
    index b4fcbd86..7586a502 100644
    --- a/src/main/java/org/jboss/logmanager/handlers/UncloseableOutputStream.java
    +++ b/src/main/java/org/jboss/logmanager/handlers/UncloseableOutputStream.java
    @@ -19,8 +19,8 @@
     
     package org.jboss.logmanager.handlers;
     
    -import java.io.OutputStream;
     import java.io.IOException;
    +import java.io.OutputStream;
     
     /**
      * An output stream wrapper which drops calls to the {@code close()} method.
    diff --git a/src/main/java/org/jboss/logmanager/handlers/UncloseableWriter.java b/src/main/java/org/jboss/logmanager/handlers/UncloseableWriter.java
    index 61de4ed8..5ffc2df8 100644
    --- a/src/main/java/org/jboss/logmanager/handlers/UncloseableWriter.java
    +++ b/src/main/java/org/jboss/logmanager/handlers/UncloseableWriter.java
    @@ -19,8 +19,8 @@
     
     package org.jboss.logmanager.handlers;
     
    -import java.io.Writer;
     import java.io.IOException;
    +import java.io.Writer;
     
     /**
      * An output stream wrapper which drops calls to the {@code close()} method.
    @@ -71,4 +71,4 @@ public void flush() throws IOException {
         public void close() {
             // ignore
         }
    -}
    \ No newline at end of file
    +}
    diff --git a/src/main/java/org/jboss/logmanager/handlers/UninterruptibleOutputStream.java b/src/main/java/org/jboss/logmanager/handlers/UninterruptibleOutputStream.java
    index 3cc3b29a..a60eccc4 100644
    --- a/src/main/java/org/jboss/logmanager/handlers/UninterruptibleOutputStream.java
    +++ b/src/main/java/org/jboss/logmanager/handlers/UninterruptibleOutputStream.java
    @@ -19,13 +19,13 @@
     
     package org.jboss.logmanager.handlers;
     
    +import static java.lang.Thread.currentThread;
    +import static java.lang.Thread.interrupted;
    +
     import java.io.IOException;
     import java.io.InterruptedIOException;
     import java.io.OutputStream;
     
    -import static java.lang.Thread.currentThread;
    -import static java.lang.Thread.interrupted;
    -
     /**
      * An output stream which is not interruptible.
      *
    @@ -52,16 +52,17 @@ public UninterruptibleOutputStream(final OutputStream out) {
         public void write(final int b) throws IOException {
             boolean intr = false;
             try {
    -            for (;;) try {
    -                out.write(b);
    -                return;
    -            } catch (InterruptedIOException e) {
    -                final int transferred = e.bytesTransferred;
    -                if (transferred == 1) {
    +            for (;;)
    +                try {
    +                    out.write(b);
                         return;
    +                } catch (InterruptedIOException e) {
    +                    final int transferred = e.bytesTransferred;
    +                    if (transferred == 1) {
    +                        return;
    +                    }
    +                    intr |= interrupted();
                     }
    -                intr |= interrupted();
    -            }
             } finally {
                 if (intr) {
                     currentThread().interrupt();
    @@ -72,7 +73,7 @@ public void write(final int b) throws IOException {
         /**
          * Write the given bytes uninterruptibly.
          *
    -     * @param b the bytes to write
    +     * @param b   the bytes to write
          * @param off the offset into the array
          * @param len the length of the array to write
          * @throws IOException if an error occurs
    @@ -80,17 +81,18 @@ public void write(final int b) throws IOException {
         public void write(final byte[] b, int off, int len) throws IOException {
             boolean intr = false;
             try {
    -            while (len > 0) try {
    -                out.write(b, off, len);
    -                return;
    -            } catch (InterruptedIOException e) {
    -                final int transferred = e.bytesTransferred;
    -                if (transferred > 0) {
    -                    off += transferred;
    -                    len -= transferred;
    +            while (len > 0)
    +                try {
    +                    out.write(b, off, len);
    +                    return;
    +                } catch (InterruptedIOException e) {
    +                    final int transferred = e.bytesTransferred;
    +                    if (transferred > 0) {
    +                        off += transferred;
    +                        len -= transferred;
    +                    }
    +                    intr |= interrupted();
                     }
    -                intr |= interrupted();
    -            }
             } finally {
                 if (intr) {
                     currentThread().interrupt();
    @@ -106,12 +108,13 @@ public void write(final byte[] b, int off, int len) throws IOException {
         public void flush() throws IOException {
             boolean intr = false;
             try {
    -            for (;;) try {
    -                out.flush();
    -                return;
    -            } catch (InterruptedIOException e) {
    -                intr |= interrupted();
    -            }
    +            for (;;)
    +                try {
    +                    out.flush();
    +                    return;
    +                } catch (InterruptedIOException e) {
    +                    intr |= interrupted();
    +                }
             } finally {
                 if (intr) {
                     currentThread().interrupt();
    @@ -127,12 +130,13 @@ public void flush() throws IOException {
         public void close() throws IOException {
             boolean intr = false;
             try {
    -            for (;;) try {
    -                out.close();
    -                return;
    -            } catch (InterruptedIOException e) {
    -                intr |= interrupted();
    -            }
    +            for (;;)
    +                try {
    +                    out.close();
    +                    return;
    +                } catch (InterruptedIOException e) {
    +                    intr |= interrupted();
    +                }
             } finally {
                 if (intr) {
                     currentThread().interrupt();
    diff --git a/src/main/java/org/jboss/logmanager/handlers/WriterHandler.java b/src/main/java/org/jboss/logmanager/handlers/WriterHandler.java
    index 00442be6..45ccb56b 100644
    --- a/src/main/java/org/jboss/logmanager/handlers/WriterHandler.java
    +++ b/src/main/java/org/jboss/logmanager/handlers/WriterHandler.java
    @@ -20,15 +20,14 @@
     package org.jboss.logmanager.handlers;
     
     import java.io.BufferedWriter;
    -import java.io.Writer;
     import java.io.Closeable;
     import java.io.Flushable;
    -
    +import java.io.Writer;
     import java.util.logging.ErrorManager;
     import java.util.logging.Formatter;
     
    -import org.jboss.logmanager.ExtLogRecord;
     import org.jboss.logmanager.ExtHandler;
    +import org.jboss.logmanager.ExtLogRecord;
     
     /**
      * A handler which writes to any {@code Writer}.
    @@ -83,8 +82,8 @@ protected void doPublish(final ExtLogRecord record) {
         }
     
         /**
    -     * Execute any pre-write policy, such as file rotation.  The write lock is held during this method, so make
    -     * it quick.  The default implementation does nothing.
    +     * Execute any pre-write policy, such as file rotation. The write lock is held during this method, so make
    +     * it quick. The default implementation does nothing.
          *
          * @param record the record about to be logged
          */
    @@ -93,7 +92,7 @@ protected void preWrite(final ExtLogRecord record) {
         }
     
         /**
    -     * Set the writer.  The writer will then belong to this handler; when the handler is closed or a new writer is set,
    +     * Set the writer. The writer will then belong to this handler; when the handler is closed or a new writer is set,
          * this writer will be closed.
          *
          * @param writer the new writer, or {@code null} to disable logging
    @@ -121,7 +120,8 @@ public void setWriter(final Writer writer) {
                 }
             } finally {
                 safeClose(oldWriter);
    -            if (! ok) safeClose(writer);
    +            if (!ok)
    +                safeClose(writer);
             }
         }
     
    @@ -177,7 +177,8 @@ private void writeHead(final Writer writer) {
                     final String head = formatter.getHead(this);
                     if (checkHeadEncoding) {
                         if (!getCharset().newEncoder().canEncode(head)) {
    -                        reportError("Section header cannot be encoded into charset \"" + getCharset().name() + "\"", null, ErrorManager.GENERIC_FAILURE);
    +                        reportError("Section header cannot be encoded into charset \"" + getCharset().name() + "\"", null,
    +                                ErrorManager.GENERIC_FAILURE);
                             return;
                         }
                     }
    @@ -195,7 +196,8 @@ private void writeTail(final Writer writer) {
                     final String tail = formatter.getTail(this);
                     if (checkTailEncoding) {
                         if (!getCharset().newEncoder().canEncode(tail)) {
    -                        reportError("Section tail cannot be encoded into charset \"" + getCharset().name() + "\"", null, ErrorManager.GENERIC_FAILURE);
    +                        reportError("Section tail cannot be encoded into charset \"" + getCharset().name() + "\"", null,
    +                                ErrorManager.GENERIC_FAILURE);
                             return;
                         }
                     }
    @@ -238,17 +240,21 @@ public void close() throws SecurityException {
          */
         protected void safeClose(Closeable c) {
             try {
    -            if (c != null) c.close();
    +            if (c != null)
    +                c.close();
             } catch (Exception e) {
                 reportError("Error closing resource", e, ErrorManager.CLOSE_FAILURE);
    -        } catch (Throwable ignored) {}
    +        } catch (Throwable ignored) {
    +        }
         }
     
         void safeFlush(Flushable f) {
             try {
    -            if (f != null) f.flush();
    +            if (f != null)
    +                f.flush();
             } catch (Exception e) {
                 reportError("Error on flush", e, ErrorManager.FLUSH_FAILURE);
    -        } catch (Throwable ignored) {}
    +        } catch (Throwable ignored) {
    +        }
         }
     }
    diff --git a/src/test/java/org/jboss/logmanager/AcceptFilter.java b/src/test/java/org/jboss/logmanager/AcceptFilter.java
    index 2c49b227..458468d7 100644
    --- a/src/test/java/org/jboss/logmanager/AcceptFilter.java
    +++ b/src/test/java/org/jboss/logmanager/AcceptFilter.java
    @@ -23,8 +23,8 @@
     import java.util.logging.LogRecord;
     
     /**
    -* @author James R. Perkins
    -*/
    + * @author James R. Perkins
    + */
     public class AcceptFilter implements Filter {
     
         @Override
    diff --git a/src/test/java/org/jboss/logmanager/AssertingErrorManager.java b/src/test/java/org/jboss/logmanager/AssertingErrorManager.java
    index 5def9df7..1c047cc0 100644
    --- a/src/test/java/org/jboss/logmanager/AssertingErrorManager.java
    +++ b/src/test/java/org/jboss/logmanager/AssertingErrorManager.java
    @@ -78,8 +78,7 @@ public void error(final String msg, final Exception ex, final int code) {
                 }
                 try (
                         StringWriter sw = new StringWriter();
    -                    PrintWriter pw = new PrintWriter(sw)
    -            ) {
    +                    PrintWriter pw = new PrintWriter(sw)) {
                     pw.printf("LogManager error of type %s: %s%n", codeStr, msg);
                     if (ex != null) {
                         ex.printStackTrace(pw);
    diff --git a/src/test/java/org/jboss/logmanager/FileHandlerPerformanceTests.java b/src/test/java/org/jboss/logmanager/FileHandlerPerformanceTests.java
    index d3116865..7504dbee 100644
    --- a/src/test/java/org/jboss/logmanager/FileHandlerPerformanceTests.java
    +++ b/src/test/java/org/jboss/logmanager/FileHandlerPerformanceTests.java
    @@ -19,14 +19,14 @@
     
     package org.jboss.logmanager;
     
    -import org.jboss.logmanager.formatters.PatternFormatter;
    -import org.jboss.logmanager.handlers.FileHandler;
    -import org.junit.Test;
    -
     import java.io.File;
     import java.io.UnsupportedEncodingException;
     import java.util.logging.Formatter;
     
    +import org.jboss.logmanager.formatters.PatternFormatter;
    +import org.jboss.logmanager.handlers.FileHandler;
    +import org.junit.Test;
    +
     /**
      * @author Carlo de Wolf
      */
    diff --git a/src/test/java/org/jboss/logmanager/FilterTests.java b/src/test/java/org/jboss/logmanager/FilterTests.java
    index e881d5d3..7372d391 100644
    --- a/src/test/java/org/jboss/logmanager/FilterTests.java
    +++ b/src/test/java/org/jboss/logmanager/FilterTests.java
    @@ -19,28 +19,28 @@
     
     package org.jboss.logmanager;
     
    -import org.jboss.logmanager.ExtLogRecord.FormatStyle;
    -import org.junit.Ignore;
    -import org.junit.Test;
     import static org.junit.Assert.*;
    +
    +import java.util.concurrent.atomic.AtomicBoolean;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.logging.Filter;
    +import java.util.logging.Handler;
    +import java.util.logging.LogRecord;
    +import java.util.regex.Pattern;
    +
    +import org.jboss.logmanager.ExtLogRecord.FormatStyle;
     import org.jboss.logmanager.filters.AcceptAllFilter;
    -import org.jboss.logmanager.filters.DenyAllFilter;
     import org.jboss.logmanager.filters.AllFilter;
     import org.jboss.logmanager.filters.AnyFilter;
    +import org.jboss.logmanager.filters.DenyAllFilter;
     import org.jboss.logmanager.filters.InvertFilter;
     import org.jboss.logmanager.filters.LevelChangingFilter;
     import org.jboss.logmanager.filters.LevelFilter;
     import org.jboss.logmanager.filters.LevelRangeFilter;
     import org.jboss.logmanager.filters.RegexFilter;
     import org.jboss.logmanager.filters.SubstituteFilter;
    -
    -import java.util.logging.Filter;
    -import java.util.logging.Handler;
    -import java.util.logging.LogRecord;
    -
    -import java.util.concurrent.atomic.AtomicBoolean;
    -import java.util.concurrent.atomic.AtomicReference;
    -import java.util.regex.Pattern;
    +import org.junit.Ignore;
    +import org.junit.Test;
     
     public final class FilterTests {
     
    @@ -408,7 +408,7 @@ public void testRegexFilter2() {
             final Handler handler = new CheckingHandler(ran);
             final Logger logger = Logger.getLogger("filterTest");
             final ExtLogRecord record = new ExtLogRecord(Level.INFO, "This is a test %s", FormatStyle.PRINTF, "filterTest");
    -        record.setParameters(new String[] {"pest"});
    +        record.setParameters(new String[] { "pest" });
             logger.setUseParentHandlers(false);
             logger.addHandler(handler);
             logger.setLevel(Level.INFO);
    @@ -425,7 +425,7 @@ public void testRegexFilter3() {
             final Handler handler = new CheckingHandler(ran);
             final Logger logger = Logger.getLogger("filterTest");
             final ExtLogRecord record = new ExtLogRecord(Level.INFO, "This is a test %s", FormatStyle.PRINTF, "filterTest");
    -        record.setParameters(new String[] {"test"});
    +        record.setParameters(new String[] { "test" });
             logger.setUseParentHandlers(false);
             logger.addHandler(handler);
             logger.setLevel(Level.INFO);
    @@ -436,7 +436,7 @@ public void testRegexFilter3() {
         }
     
         @Test
    -    public void regexFilterExceptionNullMessageTest(){
    +    public void regexFilterExceptionNullMessageTest() {
             final ExtLogRecord logRecord = new ExtLogRecord(Level.ALL, null, null);
             final Filter filter = new RegexFilter("test");
             boolean isLoggable = filter.isLoggable(logRecord);
    @@ -492,14 +492,15 @@ public void testSubstituteFilter2() {
         @Test
         public void testSubstituteFilter3() {
             final Filter filter = new SubstituteFilter(Pattern.compile("t(es)t"), "lunch$1", true);
    -        final ExtLogRecord record = new ExtLogRecord(Level.INFO, "This is a test %s", FormatStyle.PRINTF, FilterTests.class.getName());
    -        record.setParameters(new String[] {"test"});
    +        final ExtLogRecord record = new ExtLogRecord(Level.INFO, "This is a test %s", FormatStyle.PRINTF,
    +                FilterTests.class.getName());
    +        record.setParameters(new String[] { "test" });
             filter.isLoggable(record);
             assertEquals("Substitution was not correctly applied", "This is a lunches lunches", record.getFormattedMessage());
         }
     
         @Test
    -    public void substituteFilterExceptionNullMessageTest(){
    +    public void substituteFilterExceptionNullMessageTest() {
             final ExtLogRecord logRecord = new ExtLogRecord(Level.ALL, null, null);
             final Filter filter = new SubstituteFilter(Pattern.compile("test"), "lunch", true);
             filter.isLoggable(logRecord);
    @@ -507,11 +508,11 @@ public void substituteFilterExceptionNullMessageTest(){
         }
     
         @Test
    -    public void substitutionFilterWithLogRecord(){
    +    public void substitutionFilterWithLogRecord() {
             final AtomicReference result = new AtomicReference();
             final Handler handler = new MessageCheckingHandler(result);
             final Logger logger = Logger.getLogger("filterTest");
    -        final Filter filter = new SubstituteFilter(Pattern.compile("test"),"lunch",true);
    +        final Filter filter = new SubstituteFilter(Pattern.compile("test"), "lunch", true);
     
             logger.setUseParentHandlers(false);
             logger.addHandler(handler);
    @@ -519,16 +520,14 @@ public void substitutionFilterWithLogRecord(){
             logger.setFilter(filter);
             handler.setLevel(Level.INFO);
     
    -        final LogRecord record = new LogRecord(Level.INFO,"{0}");
    +        final LogRecord record = new LogRecord(Level.INFO, "{0}");
             record.setLoggerName("filterTest");
    -        record.setParameters(new Object[]{"test"});
    +        record.setParameters(new Object[] { "test" });
     
             logger.log(record);
    -        assertEquals("The substitution was not correctly applied","lunch",result.get());
    +        assertEquals("The substitution was not correctly applied", "lunch", result.get());
         }
     
    -
    -
         private static final class MessageCheckingHandler extends Handler {
             private final AtomicReference msg;
     
    diff --git a/src/test/java/org/jboss/logmanager/HandlerTests.java b/src/test/java/org/jboss/logmanager/HandlerTests.java
    index ed3760d1..6508c3c5 100644
    --- a/src/test/java/org/jboss/logmanager/HandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/HandlerTests.java
    @@ -19,30 +19,31 @@
     
     package org.jboss.logmanager;
     
    -import org.junit.Test;
     import static org.junit.Assert.*;
    -import org.jboss.logmanager.handlers.WriterHandler;
    -import org.jboss.logmanager.handlers.OutputStreamHandler;
    -import org.jboss.logmanager.handlers.FileHandler;
    -import org.jboss.logmanager.formatters.PatternFormatter;
    -
    -import java.util.logging.Formatter;
     
    -import java.io.StringWriter;
     import java.io.ByteArrayOutputStream;
     import java.io.File;
     import java.io.FileInputStream;
    +import java.io.StringWriter;
     import java.io.UnsupportedEncodingException;
    +import java.util.logging.Formatter;
     import java.util.logging.Handler;
     import java.util.logging.LogRecord;
     
    +import org.jboss.logmanager.formatters.PatternFormatter;
    +import org.jboss.logmanager.handlers.FileHandler;
    +import org.jboss.logmanager.handlers.OutputStreamHandler;
    +import org.jboss.logmanager.handlers.WriterHandler;
    +import org.junit.Test;
    +
     public final class HandlerTests {
     
         private final Formatter testFormatter = new PatternFormatter("%m");
     
         @Test
         public void testNullHandler() throws Throwable {
    -        final ExtHandler handler = new ExtHandler(){};
    +        final ExtHandler handler = new ExtHandler() {
    +        };
             handler.setLevel(Level.ALL);
             handler.publish(new ExtLogRecord(Level.INFO, "Test message", null));
         }
    @@ -102,7 +103,8 @@ public void testFileHandler() throws Throwable {
                     final FileInputStream is = new FileInputStream(tempFile);
                     try {
                         int r;
    -                    while ((r = is.read()) != -1) os.write(r);
    +                    while ((r = is.read()) != -1)
    +                        os.write(r);
                         assertEquals("Test message", new String(os.toByteArray(), "utf-8"));
                         tempFile.deleteOnExit();
                     } finally {
    diff --git a/src/test/java/org/jboss/logmanager/LogContextCloseTests.java b/src/test/java/org/jboss/logmanager/LogContextCloseTests.java
    index db0b0664..e1869041 100644
    --- a/src/test/java/org/jboss/logmanager/LogContextCloseTests.java
    +++ b/src/test/java/org/jboss/logmanager/LogContextCloseTests.java
    @@ -52,7 +52,6 @@ public void resetTestObjects() {
             TestHandler.POJO_OBJECT = null;
         }
     
    -
         @Test
         public void testCloseLogContext() throws Exception {
             LogContext logContext = LogContext.create();
    @@ -127,7 +126,8 @@ private void assertEmptyContext(final LogContext logContext, final Logger... log
             Assert.assertTrue("Expected the useParentHandlers to be true for the root logger", rootLogger.getUseParentHandlers());
             final Collection children = rootLogger.getChildren();
             if (!children.isEmpty()) {
    -            final StringBuilder msg = new StringBuilder("Expected no children to be remaining on the root logger. Remaining loggers: ");
    +            final StringBuilder msg = new StringBuilder(
    +                    "Expected no children to be remaining on the root logger. Remaining loggers: ");
                 final Iterator iter = children.iterator();
                 while (iter.hasNext()) {
                     msg.append('\'').append(iter.next().getFullName()).append('\'');
    @@ -155,7 +155,8 @@ private void assertLoggerReset(final Logger logger) {
             final Handler[] handlers = logger.getHandlers();
             Assert.assertNull("Expected the filter to be null for logger " + loggerName, logger.getFilter());
             Assert.assertTrue("Empty handlers expected for logger " + loggerName, handlers == null || handlers.length == 0);
    -        Assert.assertEquals("Expected the level to be " + expectedLevel + " for logger " + loggerName, expectedLevel, logger.getLevel());
    +        Assert.assertEquals("Expected the level to be " + expectedLevel + " for logger " + loggerName, expectedLevel,
    +                logger.getLevel());
             Assert.assertFalse("Expected the useParentFilters to be false for logger " + loggerName, logger.getUseParentFilters());
             Assert.assertTrue("Expected the useParentHandlers to be true for logger " + loggerName, logger.getUseParentHandlers());
         }
    @@ -165,7 +166,6 @@ private void assertEmptyNames(final String description, final Collection
                     names.isEmpty());
         }
     
    -
         @SuppressWarnings("unused")
         public static class TestFilter implements Filter {
             private static PojoObject POJO_OBJECT;
    @@ -203,7 +203,7 @@ public void setPojoObject(final PojoObject pojoObject) {
             }
         }
     
    -    @SuppressWarnings({"unused", "WeakerAccess"})
    +    @SuppressWarnings({ "unused", "WeakerAccess" })
         public static class TestHandler extends ExtHandler {
             private static PojoObject POJO_OBJECT;
             private static Handler[] HANDLERS;
    @@ -241,7 +241,7 @@ public void addHandler(final Handler handler) throws SecurityException {
                     throw new RuntimeException("Cannot add a null handler");
                 }
                 if (HANDLERS == null) {
    -                HANDLERS = new Handler[] {handler};
    +                HANDLERS = new Handler[] { handler };
                 } else {
                     final int len = HANDLERS.length + 1;
                     HANDLERS = Arrays.copyOf(HANDLERS, len);
    diff --git a/src/test/java/org/jboss/logmanager/LoggerTests.java b/src/test/java/org/jboss/logmanager/LoggerTests.java
    index b1ff6fcf..87cb2cd6 100644
    --- a/src/test/java/org/jboss/logmanager/LoggerTests.java
    +++ b/src/test/java/org/jboss/logmanager/LoggerTests.java
    @@ -19,18 +19,18 @@
     
     package org.jboss.logmanager;
     
    -import org.jboss.logmanager.filters.RegexFilter;
    -import org.jboss.logmanager.formatters.PatternFormatter;
    -import org.junit.Test;
     import static org.junit.Assert.*;
     
     import java.util.ArrayList;
     import java.util.Collections;
     import java.util.List;
    +import java.util.concurrent.atomic.AtomicBoolean;
     import java.util.logging.Handler;
     import java.util.logging.LogRecord;
     
    -import java.util.concurrent.atomic.AtomicBoolean;
    +import org.jboss.logmanager.filters.RegexFilter;
    +import org.jboss.logmanager.formatters.PatternFormatter;
    +import org.junit.Test;
     
     public final class LoggerTests {
     
    @@ -59,10 +59,12 @@ public void testSafeClone() {
     
         @Test
         public void testCategories() {
    -        assertNotNull("Logger not created with category: " + LoggerTests.class.getName(), Logger.getLogger(LoggerTests.class.getName()));
    +        assertNotNull("Logger not created with category: " + LoggerTests.class.getName(),
    +                Logger.getLogger(LoggerTests.class.getName()));
             assertNotNull("Logger not created with category: Spaced Logger Name", Logger.getLogger("Spaced Logger Name"));
             assertNotNull("Logger not created with category: /../Weird/Path", Logger.getLogger("/../Weird/Path"));
    -        assertNotNull("Logger not created with category: random.chars.`~!@#$%^&*()-=_+[]{}\\|;':\",.<>/?", Logger.getLogger("random.chars.`~!@#$%^&*()-=_+[]{}\\|;':\",.<>/?"));
    +        assertNotNull("Logger not created with category: random.chars.`~!@#$%^&*()-=_+[]{}\\|;':\",.<>/?",
    +                Logger.getLogger("random.chars.`~!@#$%^&*()-=_+[]{}\\|;':\",.<>/?"));
         }
     
         @Test
    @@ -78,9 +80,12 @@ public void testHandlerAdd() {
             boolean f2 = false;
             boolean f3 = false;
             for (Handler handler : logger.getHandlers()) {
    -            if (handler == h1) f1 = true;
    -            if (handler == h2) f2 = true;
    -            if (handler == h3) f3 = true;
    +            if (handler == h1)
    +                f1 = true;
    +            if (handler == h2)
    +                f2 = true;
    +            if (handler == h3)
    +                f3 = true;
             }
             assertTrue("Handler 1 missing", f1);
             assertTrue("Handler 2 missing", f2);
    @@ -97,7 +102,8 @@ public void testHandlerAdd2() {
             boolean f1 = false;
             final Handler[] handlers = logger.getHandlers();
             for (Handler handler : handlers) {
    -            if (handler == h1) f1 = true;
    +            if (handler == h1)
    +                f1 = true;
             }
             assertTrue("Handler 1 missing", f1);
             assertEquals("Extra handlers missing", 3, handlers.length);
    @@ -117,9 +123,12 @@ public void testHandlerRemove() {
             boolean f2 = false;
             boolean f3 = false;
             for (Handler handler : logger.getHandlers()) {
    -            if (handler == h1) f1 = true;
    -            if (handler == h2) f2 = true;
    -            if (handler == h3) f3 = true;
    +            if (handler == h1)
    +                f1 = true;
    +            if (handler == h2)
    +                f2 = true;
    +            if (handler == h3)
    +                f3 = true;
             }
             assertFalse("Handler 1 wasn't removed", f1);
             assertTrue("Handler 2 missing", f2);
    @@ -149,9 +158,12 @@ public void testHandlerClear() {
             boolean f2 = false;
             boolean f3 = false;
             for (Handler handler : logger.getHandlers()) {
    -            if (handler == h1) f1 = true;
    -            if (handler == h2) f2 = true;
    -            if (handler == h3) f3 = true;
    +            if (handler == h1)
    +                f1 = true;
    +            if (handler == h2)
    +                f2 = true;
    +            if (handler == h3)
    +                f3 = true;
             }
             assertFalse("Handler 1 wasn't removed", f1);
             assertFalse("Handler 2 wasn't removed", f2);
    diff --git a/src/test/java/org/jboss/logmanager/MapTestUtils.java b/src/test/java/org/jboss/logmanager/MapTestUtils.java
    index d385dd3c..994b6a00 100644
    --- a/src/test/java/org/jboss/logmanager/MapTestUtils.java
    +++ b/src/test/java/org/jboss/logmanager/MapTestUtils.java
    @@ -48,7 +48,8 @@ public static  void compareMaps(final Map m1, final Map m2) {
             for (Map.Entry entry1 : m1.entrySet()) {
                 final V value2 = m2.get(entry1.getKey());
                 Assert.assertEquals(
    -                    String.format("Value %s from the first map does not match value %s from the second map with key %s.", entry1.getValue(), value2, entry1.getKey()),
    +                    String.format("Value %s from the first map does not match value %s from the second map with key %s.",
    +                            entry1.getValue(), value2, entry1.getKey()),
                         entry1.getValue(), value2);
             }
         }
    diff --git a/src/test/java/org/jboss/logmanager/PropertyValuesTests.java b/src/test/java/org/jboss/logmanager/PropertyValuesTests.java
    index 47593911..ace0f5bf 100644
    --- a/src/test/java/org/jboss/logmanager/PropertyValuesTests.java
    +++ b/src/test/java/org/jboss/logmanager/PropertyValuesTests.java
    @@ -33,7 +33,7 @@ public class PropertyValuesTests extends MapTestUtils {
     
         @Test
         public void testStringToMap() {
    -        Map map = MapBuilder.create()
    +        Map map = MapBuilder. create()
                     .add("key1", "value1")
                     .add("key2", "value2")
                     .add("key3", "value3")
    @@ -41,7 +41,7 @@ public void testStringToMap() {
             Map parsedMap = PropertyValues.stringToMap("key1=value1,key2=value2,key3=value3");
             compareMaps(map, parsedMap);
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("key=1", "value1")
                     .add("key=2", "value,2")
                     .add("key3", "value,3")
    @@ -49,7 +49,7 @@ public void testStringToMap() {
             parsedMap = PropertyValues.stringToMap("key\\=1=value1,key\\=2=value\\,2,key3=value\\,3");
             compareMaps(map, parsedMap);
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("key=", "value,")
                     .add("key2", "value2")
                     .add("key\\", "value\\")
    @@ -58,7 +58,7 @@ public void testStringToMap() {
             parsedMap = PropertyValues.stringToMap("key\\==value\\,,key2=value2,key\\\\=value\\\\,this=some=thing\\\\thing=some");
             compareMaps(map, parsedMap);
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("key1", "value1")
                     .add("key2", null)
                     .add("key3", "value3")
    @@ -67,7 +67,7 @@ public void testStringToMap() {
             parsedMap = PropertyValues.stringToMap("key1=value1,key2=,key3=value3,key4");
             compareMaps(map, parsedMap);
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("company", "Red Hat, Inc.")
                     .add("product", "JBoss")
                     .add("name", "First \"nick\" Last")
    @@ -81,22 +81,24 @@ public void testStringToMap() {
     
         @Test
         public void testStringToMapValueExpressions() {
    -        Map map = MapBuilder.create()
    +        Map map = MapBuilder. create()
                     .add("key1", "${org.jboss.logmanager.test.sysprop1}")
                     .add("key2=", "${org.jboss.logmanager.test.sysprop2}")
                     .build();
    -        Map parsedMap = PropertyValues.stringToMap("key1=${org.jboss.logmanager.test.sysprop1},key2\\==${org.jboss.logmanager.test.sysprop2}");
    +        Map parsedMap = PropertyValues
    +                .stringToMap("key1=${org.jboss.logmanager.test.sysprop1},key2\\==${org.jboss.logmanager.test.sysprop2}");
             compareMaps(map, parsedMap);
         }
     
         @Test
         public void testStringToEnumMap() throws Exception {
    -        Map map = MapBuilder.create()
    +        Map map = MapBuilder. create()
                     .add(Key.EXCEPTION_CAUSED_BY, "cause")
                     .add(Key.MESSAGE, "msg")
                     .add(Key.HOST_NAME, "hostname")
                     .build();
    -        EnumMap parsedMap = PropertyValues.stringToEnumMap(Key.class, "EXCEPTION_CAUSED_BY=cause,MESSAGE=msg,HOST_NAME=hostname");
    +        EnumMap parsedMap = PropertyValues.stringToEnumMap(Key.class,
    +                "EXCEPTION_CAUSED_BY=cause,MESSAGE=msg,HOST_NAME=hostname");
             compareMaps(map, parsedMap);
     
             parsedMap = PropertyValues.stringToEnumMap(Key.class, "exception-caused-by=cause,message=msg,host-name=hostname");
    @@ -105,29 +107,30 @@ public void testStringToEnumMap() throws Exception {
     
         @Test
         public void testMapToString() throws Exception {
    -        Map map = MapBuilder.create()
    +        Map map = MapBuilder. create()
                     .add("key1", "value1")
                     .add("key2", "value2")
                     .add("key3", "value3")
                     .build();
             Assert.assertEquals("key1=value1,key2=value2,key3=value3", PropertyValues.mapToString(map));
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("key=1", "value1")
                     .add("key=2", "value,2")
                     .add("key3", "value,3")
                     .build();
             Assert.assertEquals("key\\=1=value1,key\\=2=value\\,2,key3=value\\,3", PropertyValues.mapToString(map));
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("key=", "value,")
                     .add("key2", "value2")
                     .add("key\\", "value\\")
                     .add("this", "some=thing\\thing=some")
                     .build();
    -        Assert.assertEquals("key\\==value\\,,key2=value2,key\\\\=value\\\\,this=some=thing\\\\thing=some", PropertyValues.mapToString(map));
    +        Assert.assertEquals("key\\==value\\,,key2=value2,key\\\\=value\\\\,this=some=thing\\\\thing=some",
    +                PropertyValues.mapToString(map));
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("key1", "value1")
                     .add("key2", null)
                     .add("key3", "value3")
    @@ -135,7 +138,7 @@ public void testMapToString() throws Exception {
                     .build();
             Assert.assertEquals("key1=value1,key2=,key3=value3,key4=", PropertyValues.mapToString(map));
     
    -        map = MapBuilder.create()
    +        map = MapBuilder. create()
                     .add("company", "Red Hat, Inc.")
                     .add("product", "JBoss")
                     .add("name", "First \"nick\" Last")
    diff --git a/src/test/java/org/jboss/logmanager/SystemLoggerIT.java b/src/test/java/org/jboss/logmanager/SystemLoggerIT.java
    index 9e0ad770..1e98dd88 100644
    --- a/src/test/java/org/jboss/logmanager/SystemLoggerIT.java
    +++ b/src/test/java/org/jboss/logmanager/SystemLoggerIT.java
    @@ -31,6 +31,7 @@
     import java.util.List;
     import java.util.Locale;
     import java.util.concurrent.TimeUnit;
    +
     import jakarta.json.Json;
     import jakarta.json.JsonArray;
     import jakarta.json.JsonArrayBuilder;
    @@ -193,4 +194,4 @@ private static String findJavaCommand() {
             }
             return "java";
         }
    -}
    \ No newline at end of file
    +}
    diff --git a/src/test/java/org/jboss/logmanager/TestLogContextConfigurator.java b/src/test/java/org/jboss/logmanager/TestLogContextConfigurator.java
    index 4530d39e..acc87123 100644
    --- a/src/test/java/org/jboss/logmanager/TestLogContextConfigurator.java
    +++ b/src/test/java/org/jboss/logmanager/TestLogContextConfigurator.java
    @@ -26,6 +26,7 @@
     import java.util.Map;
     import java.util.logging.Level;
     import java.util.logging.Logger;
    +
     import jakarta.json.Json;
     import jakarta.json.stream.JsonGenerator;
     
    diff --git a/src/test/java/org/jboss/logmanager/configuration/PropertyConfigurationTests.java b/src/test/java/org/jboss/logmanager/configuration/PropertyConfigurationTests.java
    index 1f7fec2a..f65fbd9a 100644
    --- a/src/test/java/org/jboss/logmanager/configuration/PropertyConfigurationTests.java
    +++ b/src/test/java/org/jboss/logmanager/configuration/PropertyConfigurationTests.java
    @@ -79,8 +79,7 @@ public void readConfigs() throws Exception {
                     .forEach((configFile) -> {
                         try (
                                 LogContext logContext = LogContext.create();
    -                            Reader reader = Files.newBufferedReader(configFile, StandardCharsets.UTF_8)
    -                    ) {
    +                            Reader reader = Files.newBufferedReader(configFile, StandardCharsets.UTF_8)) {
                             final Properties properties = new Properties();
                             properties.load(reader);
                             PropertyConfigurator.configure(logContext, properties);
    diff --git a/src/test/java/org/jboss/logmanager/formatters/BannerFormatterTests.java b/src/test/java/org/jboss/logmanager/formatters/BannerFormatterTests.java
    index 5e437cab..c546ab60 100644
    --- a/src/test/java/org/jboss/logmanager/formatters/BannerFormatterTests.java
    +++ b/src/test/java/org/jboss/logmanager/formatters/BannerFormatterTests.java
    @@ -44,9 +44,11 @@ public void testBanner() throws Exception {
             Assert.assertEquals(FALLBACK_OK, fallbackSupplier.get());
             TextBannerFormatter tbf = new TextBannerFormatter(fallbackSupplier, emptyFormatter);
             Assert.assertEquals(FALLBACK_OK, tbf.getHead(null));
    -        tbf = new TextBannerFormatter(TextBannerFormatter.createResourceSupplier("non-existent-banner.txt", fallbackSupplier), emptyFormatter);
    +        tbf = new TextBannerFormatter(TextBannerFormatter.createResourceSupplier("non-existent-banner.txt", fallbackSupplier),
    +                emptyFormatter);
             Assert.assertEquals(FALLBACK_OK, tbf.getHead(null));
    -        tbf = new TextBannerFormatter(TextBannerFormatter.createResourceSupplier("test-banner.txt", fallbackSupplier), emptyFormatter);
    +        tbf = new TextBannerFormatter(TextBannerFormatter.createResourceSupplier("test-banner.txt", fallbackSupplier),
    +                emptyFormatter);
             final InputStream is = BannerFormatterTests.class.getResourceAsStream("/test-banner.txt");
             Assert.assertNotNull(is);
             try (is) {
    @@ -59,15 +61,18 @@ public void testBanner() throws Exception {
                 tbf = new TextBannerFormatter(TextBannerFormatter.createFileSupplier(tempFile, fallbackSupplier), emptyFormatter);
                 Assert.assertEquals(TEST_BANNER_FILE, tbf.getHead(null));
                 // and, the URL version...
    -            tbf = new TextBannerFormatter(TextBannerFormatter.createUrlSupplier(tempFile.toUri().toURL(), fallbackSupplier), emptyFormatter);
    +            tbf = new TextBannerFormatter(TextBannerFormatter.createUrlSupplier(tempFile.toUri().toURL(), fallbackSupplier),
    +                    emptyFormatter);
                 Assert.assertEquals(TEST_BANNER_FILE, tbf.getHead(null));
             } finally {
                 try {
                     Files.delete(tempFile);
    -            } catch (Throwable ignored) {}
    +            } catch (Throwable ignored) {
    +            }
             }
             // non-existent file
    -        tbf = new TextBannerFormatter(TextBannerFormatter.createFileSupplier(Path.of("does not exist"), fallbackSupplier), emptyFormatter);
    +        tbf = new TextBannerFormatter(TextBannerFormatter.createFileSupplier(Path.of("does not exist"), fallbackSupplier),
    +                emptyFormatter);
             Assert.assertEquals(FALLBACK_OK, tbf.getHead(null));
         }
     }
    diff --git a/src/test/java/org/jboss/logmanager/formatters/JsonFormatterTests.java b/src/test/java/org/jboss/logmanager/formatters/JsonFormatterTests.java
    index 4c80a35c..6fb3902a 100644
    --- a/src/test/java/org/jboss/logmanager/formatters/JsonFormatterTests.java
    +++ b/src/test/java/org/jboss/logmanager/formatters/JsonFormatterTests.java
    @@ -26,6 +26,7 @@
     import java.util.HashMap;
     import java.util.LinkedHashMap;
     import java.util.Map;
    +
     import jakarta.json.Json;
     import jakarta.json.JsonObject;
     import jakarta.json.JsonReader;
    @@ -45,8 +46,7 @@
      */
     public class JsonFormatterTests extends AbstractTest {
         private static final Map KEY_OVERRIDES = new HashMap<>();
    -    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
    -            .ISO_OFFSET_DATE_TIME
    +    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME
                 .withZone(ZoneId.systemDefault());
     
         @Before
    @@ -87,13 +87,13 @@ public void testMetaData() throws Exception {
             formatter.setPrintDetails(true);
             formatter.setMetaData("context-id=context1");
             ExtLogRecord record = createLogRecord("Test formatted %s", "message");
    -        Map metaDataMap = MapBuilder.create()
    +        Map metaDataMap = MapBuilder. create()
                     .add("context-id", "context1")
                     .build();
             compare(record, formatter, metaDataMap);
     
             formatter.setMetaData("vendor=Red Hat\\, Inc.,product-type=JBoss");
    -        metaDataMap = MapBuilder.create()
    +        metaDataMap = MapBuilder. create()
                     .add("vendor", "Red Hat, Inc.")
                     .add("product-type", "JBoss")
                     .build();
    @@ -197,7 +197,8 @@ private static void compare(final ExtLogRecord record, final JsonObject json, fi
             validateStackTrace(json, hasFormatted, hasStructured);
         }
     
    -    private static void validateStackTrace(final JsonObject json, final boolean validateFormatted, final boolean validateStructured) {
    +    private static void validateStackTrace(final JsonObject json, final boolean validateFormatted,
    +            final boolean validateStructured) {
             if (validateFormatted) {
                 Assert.assertNotNull(json.get(getKey(Key.STACK_TRACE)));
             }
    diff --git a/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java b/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java
    index 709f0077..78a28120 100644
    --- a/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java
    +++ b/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java
    @@ -300,7 +300,6 @@ public void qualifiedHost() {
             Assert.assertEquals("jboss", formatter.format(record));
         }
     
    -
         private void systemProperties(final String propertyPrefix) throws Exception {
             final ExtLogRecord record = createLogRecord("test");
             PatternFormatter formatter = new PatternFormatter("%" + propertyPrefix + "{org.jboss.logmanager.testProp}");
    @@ -331,7 +330,8 @@ private void systemProperties(final String propertyPrefix) throws Exception {
         }
     
         protected static ExtLogRecord createLogRecord(final String msg) {
    -        final ExtLogRecord result = new ExtLogRecord(org.jboss.logmanager.Level.INFO, msg, PatternFormatterTests.class.getName());
    +        final ExtLogRecord result = new ExtLogRecord(org.jboss.logmanager.Level.INFO, msg,
    +                PatternFormatterTests.class.getName());
             result.setSourceClassName(PatternFormatterTests.class.getName());
             result.setLoggerName(CATEGORY);
             return result;
    diff --git a/src/test/java/org/jboss/logmanager/formatters/StackTraceFormatterTests.java b/src/test/java/org/jboss/logmanager/formatters/StackTraceFormatterTests.java
    index 47afab6b..bf2d859b 100644
    --- a/src/test/java/org/jboss/logmanager/formatters/StackTraceFormatterTests.java
    +++ b/src/test/java/org/jboss/logmanager/formatters/StackTraceFormatterTests.java
    @@ -166,7 +166,9 @@ private void testDepth(final int depth) {
     
         private void checkMessage(final String msg, final String text, final boolean shouldExist, final int depth) {
             final boolean test = (shouldExist || depth < 0);
    -        Assert.assertEquals(String.format("Depth %d should %s contained \"%s\": %s", depth, (test ? "have" : "not have"), text, msg), msg.contains(text), test);
    +        Assert.assertEquals(
    +                String.format("Depth %d should %s contained \"%s\": %s", depth, (test ? "have" : "not have"), text, msg),
    +                msg.contains(text), test);
         }
     
         private Throwable createMultiNestedCause() {
    @@ -176,14 +178,12 @@ private Throwable createMultiNestedCause() {
             suppressed1.addSuppressed(nested1);
             suppressed1.addSuppressed(new IllegalStateException("Nested 1-2"));
     
    -
             final RuntimeException suppressed2 = new RuntimeException("Suppressed 2");
             final IllegalStateException nested2 = new IllegalStateException("Nested 2");
             nested2.addSuppressed(new RuntimeException("Nested 2a"));
             suppressed2.addSuppressed(nested2);
             suppressed2.addSuppressed(new IllegalStateException("Nested 2-2"));
     
    -
             final RuntimeException suppressed3 = new RuntimeException("Suppressed 3");
             final IllegalStateException nested3 = new IllegalStateException("Nested 3");
             nested3.addSuppressed(new RuntimeException("Nested 3a"));
    diff --git a/src/test/java/org/jboss/logmanager/formatters/XmlFormatterTests.java b/src/test/java/org/jboss/logmanager/formatters/XmlFormatterTests.java
    index e93fa488..3cd7d762 100644
    --- a/src/test/java/org/jboss/logmanager/formatters/XmlFormatterTests.java
    +++ b/src/test/java/org/jboss/logmanager/formatters/XmlFormatterTests.java
    @@ -25,6 +25,7 @@
     import java.util.Collections;
     import java.util.LinkedHashMap;
     import java.util.Map;
    +
     import javax.xml.XMLConstants;
     import javax.xml.stream.XMLInputFactory;
     import javax.xml.stream.XMLStreamConstants;
    @@ -49,8 +50,7 @@
      * @author James R. Perkins
      */
     public class XmlFormatterTests extends AbstractTest {
    -    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
    -            .ISO_OFFSET_DATE_TIME
    +    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME
                 .withZone(ZoneId.systemDefault());
     
         @Test
    @@ -171,7 +171,8 @@ private static Map getMap(final XMLStreamReader reader) throws X
                 while (reader.hasNext() && (state = reader.next()) != XMLStreamConstants.END_ELEMENT) {
                     if (state == XMLStreamConstants.CHARACTERS) {
                         String text = sanitize(reader.getText());
    -                    if (text == null || text.isEmpty()) continue;
    +                    if (text == null || text.isEmpty())
    +                        continue;
                         Assert.fail(String.format("Invalid text found: %s", text));
                     }
                     final String key = reader.getLocalName();
    diff --git a/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java b/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java
    index 9bf6a4b9..b76cbe78 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java
    @@ -133,7 +133,8 @@ protected ExtLogRecord createLogRecord(final org.jboss.logmanager.Level level, f
          * @throws IOException if an error occurs while reading the GZIP file
          */
         static void validateGzipContents(final Path path, final String expectedContains) throws IOException {
    -        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(Files.newInputStream(path))))) {
    +        try (BufferedReader reader = new BufferedReader(
    +                new InputStreamReader(new GZIPInputStream(Files.newInputStream(path))))) {
                 String line;
                 while ((line = reader.readLine()) != null) {
                     if (line.contains(expectedContains)) {
    @@ -154,17 +155,22 @@ static void validateGzipContents(final Path path, final String expectedContains)
          *
          * @throws IOException if an error occurs reading the zip file
          */
    -    static void validateZipContents(final Path path, final String expectedFileName, final String expectedContains) throws IOException {
    -        try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" +  path.toUri().toASCIIString()), Collections.singletonMap("create", "true"))) {
    +    static void validateZipContents(final Path path, final String expectedFileName, final String expectedContains)
    +            throws IOException {
    +        try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + path.toUri().toASCIIString()),
    +                Collections.singletonMap("create", "true"))) {
                 final Path file = zipFs.getPath(zipFs.getSeparator(), expectedFileName);
                 Assert.assertTrue(String.format("Expected file %s not found.", expectedFileName), Files.exists(file));
                 final List lines = Files.readAllLines(file, StandardCharsets.UTF_8);
    -            Assert.assertFalse(String.format("File %s appears to be empty in zip file %s.", expectedFileName, path), lines.isEmpty());
    -            Assert.assertTrue(String.format("ZIP file %s missing contents: %s", path, expectedContains), lines.get(0).contains(expectedContains));
    +            Assert.assertFalse(String.format("File %s appears to be empty in zip file %s.", expectedFileName, path),
    +                    lines.isEmpty());
    +            Assert.assertTrue(String.format("ZIP file %s missing contents: %s", path, expectedContains),
    +                    lines.get(0).contains(expectedContains));
             }
         }
     
    -    static void compareArchiveContents(final Path archive1, final Path archive2, final String expectedFileName) throws IOException {
    +    static void compareArchiveContents(final Path archive1, final Path archive2, final String expectedFileName)
    +            throws IOException {
             Collection lines1 = Collections.emptyList();
             Collection lines2 = Collections.emptyList();
     
    @@ -204,7 +210,8 @@ static void compareArchiveContents(final Path archive1, final Path archive2, fin
         }
     
         private static Collection readAllLinesFromZip(final Path path, final String expectedFileName) throws IOException {
    -        try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + path.toUri().toASCIIString()), Collections.singletonMap("create", "true"))) {
    +        try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + path.toUri().toASCIIString()),
    +                Collections.singletonMap("create", "true"))) {
                 final Path file = zipFs.getPath(zipFs.getSeparator(), expectedFileName);
                 Assert.assertTrue(String.format("Expected file %s not found.", expectedFileName), Files.exists(file));
                 return Files.readAllLines(file, StandardCharsets.UTF_8);
    @@ -213,7 +220,8 @@ private static Collection readAllLinesFromZip(final Path path, final Str
     
         private static Collection readAllLinesFromGzip(final Path path) throws IOException {
             final Collection lines = new ArrayList<>();
    -        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(Files.newInputStream(path))))) {
    +        try (BufferedReader reader = new BufferedReader(
    +                new InputStreamReader(new GZIPInputStream(Files.newInputStream(path))))) {
                 String line;
                 while ((line = reader.readLine()) != null) {
                     lines.add(line);
    diff --git a/src/test/java/org/jboss/logmanager/handlers/AssertingErrorManager.java b/src/test/java/org/jboss/logmanager/handlers/AssertingErrorManager.java
    index ce75adab..9ef41817 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/AssertingErrorManager.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/AssertingErrorManager.java
    @@ -78,8 +78,7 @@ public void error(final String msg, final Exception ex, final int code) {
                 }
                 try (
                         StringWriter sw = new StringWriter();
    -                    PrintWriter pw = new PrintWriter(sw)
    -            ) {
    +                    PrintWriter pw = new PrintWriter(sw)) {
                     pw.printf("LogManager error of type %s: %s%n", codeStr, msg);
                     ex.printStackTrace(pw);
                     Assert.fail(sw.toString());
    diff --git a/src/test/java/org/jboss/logmanager/handlers/AsyncHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/AsyncHandlerTests.java
    index 07265532..061eeff6 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/AsyncHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/AsyncHandlerTests.java
    @@ -28,8 +28,8 @@
     import org.jboss.logmanager.Level;
     import org.jboss.logmanager.MDC;
     import org.jboss.logmanager.NDC;
    -import org.jboss.logmanager.handlers.AsyncHandler.OverflowAction;
     import org.jboss.logmanager.formatters.PatternFormatter;
    +import org.jboss.logmanager.handlers.AsyncHandler.OverflowAction;
     import org.junit.After;
     import org.junit.Assert;
     import org.junit.Before;
    diff --git a/src/test/java/org/jboss/logmanager/handlers/DelayedHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/DelayedHandlerTests.java
    index a600e080..7f90a2da 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/DelayedHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/DelayedHandlerTests.java
    @@ -30,7 +30,6 @@
     import java.util.logging.Logger;
     import java.util.stream.Collectors;
     
    -import io.smallrye.common.cpu.ProcessorInfo;
     import org.jboss.logmanager.AssertingErrorManager;
     import org.jboss.logmanager.ExtHandler;
     import org.jboss.logmanager.ExtLogRecord;
    @@ -39,6 +38,8 @@
     import org.junit.Assert;
     import org.junit.Test;
     
    +import io.smallrye.common.cpu.ProcessorInfo;
    +
     /**
      * @author James R. Perkins
      */
    @@ -85,7 +86,6 @@ public void testQueuedMessages() {
             Assert.assertEquals("Test message 6", TestHandler.MESSAGES.get(4).getFormattedMessage());
         }
     
    -
         @Test
         public void testAllLoggedAfterActivation() throws Exception {
             final ExecutorService service = createExecutor();
    @@ -120,7 +120,8 @@ public void testAllLoggedAfterActivation() throws Exception {
                         .collect(Collectors.toList());
                 missing.removeAll(ints);
                 Collections.sort(missing);
    -            Assert.assertEquals(String.format("Missing the following entries: %s", missing), ITERATIONS, TestHandler.MESSAGES.size());
    +            Assert.assertEquals(String.format("Missing the following entries: %s", missing), ITERATIONS,
    +                    TestHandler.MESSAGES.size());
     
             } finally {
                 Assert.assertTrue(service.shutdownNow().isEmpty());
    @@ -165,7 +166,8 @@ public void testAllLoggedMidActivation() throws Exception {
                         .collect(Collectors.toList());
                 missing.removeAll(ints);
                 Collections.sort(missing);
    -            Assert.assertEquals(String.format("Missing the following entries: %s", missing), ITERATIONS, TestHandler.MESSAGES.size());
    +            Assert.assertEquals(String.format("Missing the following entries: %s", missing), ITERATIONS,
    +                    TestHandler.MESSAGES.size());
     
             } finally {
                 Assert.assertTrue(service.shutdownNow().isEmpty());
    @@ -251,4 +253,4 @@ public void close() throws SecurityException {
                 super.close();
             }
         }
    -}
    \ No newline at end of file
    +}
    diff --git a/src/test/java/org/jboss/logmanager/handlers/ExtHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/ExtHandlerTests.java
    index 9450471e..096f3540 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/ExtHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/ExtHandlerTests.java
    @@ -37,7 +37,7 @@ public void testHandlerClose() throws Exception {
             final CloseHandler parent = new CloseHandler();
             final CloseHandler child1 = new CloseHandler();
             final CloseHandler child2 = new CloseHandler();
    -        parent.setHandlers(new CloseHandler[] {child1, child2, new CloseHandler()});
    +        parent.setHandlers(new CloseHandler[] { child1, child2, new CloseHandler() });
     
             // Ensure all handlers are not closed
             Assert.assertFalse(parent.closed);
    diff --git a/src/test/java/org/jboss/logmanager/handlers/OutputStreamHandlerTest.java b/src/test/java/org/jboss/logmanager/handlers/OutputStreamHandlerTest.java
    index d0e79ef1..34e16ceb 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/OutputStreamHandlerTest.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/OutputStreamHandlerTest.java
    @@ -92,5 +92,4 @@ public void testSetNullEncodingOnOutputStream() throws Exception {
             assertThat(out.toString(), is("Hello World"));
         }
     
    -
     }
    diff --git a/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java
    index 047d1c79..1ba49ab5 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java
    @@ -100,12 +100,7 @@ public void testArchiveRotateZip() throws Exception {
         }
     
         @Test
    -    @BMRule(name = "Test failed rotated",
    -            targetClass = "java.nio.file.Files",
    -            targetMethod = "move",
    -            targetLocation = "AT ENTRY",
    -            condition = "$2.getFileName().toString().matches(\"periodic-rotating-file-handler\\\\.log\\\\.\\\\d+\")",
    -            action = "throw new IOException(\"Fail on purpose\")")
    +    @BMRule(name = "Test failed rotated", targetClass = "java.nio.file.Files", targetMethod = "move", targetLocation = "AT ENTRY", condition = "$2.getFileName().toString().matches(\"periodic-rotating-file-handler\\\\.log\\\\.\\\\d+\")", action = "throw new IOException(\"Fail on purpose\")")
         public void testFailedRotate() throws Exception {
             final Calendar cal = Calendar.getInstance();
             final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + rotateFormatter.format(cal.getTime()));
    @@ -143,10 +138,10 @@ record = createLogRecord(Level.INFO, "Date: %s", nextDate);
             Assert.assertTrue("Expected the line to contain the date: " + nextDate, lines.get(0).contains(nextDate));
     
             // The file should not have been rotated
    -        Assert.assertTrue("The rotated file '" + rotatedFile.toString() + "' exists and should not", Files.notExists(rotatedFile));
    +        Assert.assertTrue("The rotated file '" + rotatedFile.toString() + "' exists and should not",
    +                Files.notExists(rotatedFile));
         }
     
    -
         private void testRotate(final Calendar cal, final Path rotatedFile) throws Exception {
             final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
             final int currentDay = cal.get(Calendar.DAY_OF_MONTH);
    diff --git a/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java
    index 17131665..b5994b2f 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java
    @@ -51,8 +51,7 @@ public class PeriodicSizeRotatingFileHandlerTests extends AbstractHandlerTest {
         private final File logFile = new File(BASE_LOG_DIR, FILENAME);
     
         private static final List supportedPeriods = new ArrayList();
    -    private static final Map periodFormatMap =
    -        new HashMap();
    +    private static final Map periodFormatMap = new HashMap();
     
         static {
             supportedPeriods.add(Calendar.YEAR);
    @@ -168,15 +167,17 @@ public void testBootRotate() throws Exception {
         @Test
         @Ignore("LOGMGR-82")
         public void testPeriodicAndSizeRotate() throws Exception {
    -        for (int i=0; i < supportedPeriods.size(); i++) {
    +        for (int i = 0; i < supportedPeriods.size(); i++) {
                 //To cut down on unnecessary testing, let's only test
                 //the periods +/- two from this period
    -            int j = i-2;
    -            if (j < 0) j = 0;
    +            int j = i - 2;
    +            if (j < 0)
    +                j = 0;
     
                 int handlerPeriod = supportedPeriods.get(i);
    -            for (; j <= i+2; j++) {
    -                if (j >= supportedPeriods.size()) break;
    +            for (; j <= i + 2; j++) {
    +                if (j >= supportedPeriods.size())
    +                    break;
                     int logMessagePeriod = supportedPeriods.get(j);
                     testPeriodicAndSizeRotate0(handlerPeriod, logMessagePeriod, true);
                     testPeriodicAndSizeRotate0(handlerPeriod, logMessagePeriod, false);
    @@ -204,17 +205,12 @@ public void testArchiveRotateSizeOnlyGzip() throws Exception {
     
         @Test
         public void testArchiveRotateSizeOnlyZip() throws Exception {
    -        testArchiveRotate(null,".zip", false);
    -        testArchiveRotate(null,".zip", true);
    +        testArchiveRotate(null, ".zip", false);
    +        testArchiveRotate(null, ".zip", true);
         }
     
         @Test
    -    @BMRule(name = "Test failed rotated",
    -            targetClass = "java.nio.file.Files",
    -            targetMethod = "move",
    -            targetLocation = "AT ENTRY",
    -            condition = "$2.getFileName().toString().equals(\"rotating-file-handler.log.2\")",
    -            action = "throw new IOException(\"Fail on purpose\")")
    +    @BMRule(name = "Test failed rotated", targetClass = "java.nio.file.Files", targetMethod = "move", targetLocation = "AT ENTRY", condition = "$2.getFileName().toString().equals(\"rotating-file-handler.log.2\")", action = "throw new IOException(\"Fail on purpose\")")
         public void testFailedRotate() throws Exception {
             final PeriodicSizeRotatingFileHandler handler = new PeriodicSizeRotatingFileHandler();
             configureHandlerDefaults(handler);
    @@ -241,7 +237,8 @@ public void testFailedRotate() throws Exception {
             Assert.assertTrue("Expected the last line to end with 99: " + lastLine, lastLine.endsWith("99"));
         }
     
    -    private void testArchiveRotate(final String dateSuffix, final String archiveSuffix, final boolean rotateOnBoot) throws Exception {
    +    private void testArchiveRotate(final String dateSuffix, final String archiveSuffix, final boolean rotateOnBoot)
    +            throws Exception {
             final String currentDate = dateSuffix == null ? "" : LocalDate.now().format(DateTimeFormatter.ofPattern(dateSuffix));
             PeriodicSizeRotatingFileHandler handler = new PeriodicSizeRotatingFileHandler();
             configureHandlerDefaults(handler);
    @@ -371,7 +368,7 @@ private void testPeriodicAndSizeRotate0(int handlerPeriod, int logMessagePeriod,
     
         private boolean shouldRotate(int logMessagePeriod, int handlerPeriod, boolean testSize) {
             if (testSize) {
    -          return true;
    +            return true;
             }
     
             // If the time period added to the log message is greater than the time period specified
    @@ -381,7 +378,7 @@ private boolean shouldRotate(int logMessagePeriod, int handlerPeriod, boolean te
             if (logMessagePeriod > handlerPeriod) {
                 Calendar cal = Calendar.getInstance();
                 if (isPeriodOneLess(logMessagePeriod, handlerPeriod) &&
    -                cal.get(logMessagePeriod) == cal.getActualMaximum(logMessagePeriod)) {
    +                    cal.get(logMessagePeriod) == cal.getActualMaximum(logMessagePeriod)) {
                     return true;
                 } else {
                     return false;
    @@ -414,27 +411,27 @@ public ErrorCreator(int handlerPeriod, int logMessagePeriod, boolean testSize) {
             }
     
             public String create(boolean expectRotation, File log) throws Exception {
    -              StringBuilder builder = new StringBuilder();
    -              if (expectRotation) {
    -                  builder.append("Expected log rotation, but it didn't happen\n");
    -              } else {
    -                  builder.append("Expected NO log rotation, but it happened anyways\n");
    -              }
    -
    -              builder.append("Handler: " + periodFormatMap.get(handlerPeriod).toPattern());
    -              builder.append(" ; ");
    -              builder.append("Message: " + periodFormatMap.get(logMessagePeriod).toPattern());
    -              builder.append(" ; ");
    -              builder.append("testSize=" + testSize);
    -
    -              builder.append("\nChecking for log file here: ");
    -              builder.append(log.getPath() + "\n");
    -              builder.append("List of log files:\n");
    -              for (String f : BASE_LOG_DIR.list()) {
    -                  builder.append("\t" + f + "\n");
    -              }
    -              builder.append("-- End of listing --");
    -              return builder.toString();
    +            StringBuilder builder = new StringBuilder();
    +            if (expectRotation) {
    +                builder.append("Expected log rotation, but it didn't happen\n");
    +            } else {
    +                builder.append("Expected NO log rotation, but it happened anyways\n");
    +            }
    +
    +            builder.append("Handler: " + periodFormatMap.get(handlerPeriod).toPattern());
    +            builder.append(" ; ");
    +            builder.append("Message: " + periodFormatMap.get(logMessagePeriod).toPattern());
    +            builder.append(" ; ");
    +            builder.append("testSize=" + testSize);
    +
    +            builder.append("\nChecking for log file here: ");
    +            builder.append(log.getPath() + "\n");
    +            builder.append("List of log files:\n");
    +            for (String f : BASE_LOG_DIR.list()) {
    +                builder.append("\t" + f + "\n");
    +            }
    +            builder.append("-- End of listing --");
    +            return builder.toString();
             }
         }
     }
    diff --git a/src/test/java/org/jboss/logmanager/handlers/SimpleServer.java b/src/test/java/org/jboss/logmanager/handlers/SimpleServer.java
    index 6d6335a4..404d8c9b 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/SimpleServer.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/SimpleServer.java
    @@ -35,6 +35,7 @@
     import java.util.concurrent.LinkedBlockingDeque;
     import java.util.concurrent.TimeUnit;
     import java.util.concurrent.atomic.AtomicBoolean;
    +
     import javax.net.ServerSocketFactory;
     import javax.net.ssl.SSLServerSocketFactory;
     
    @@ -67,14 +68,12 @@ static SimpleServer createTcpServer() throws IOException {
             return server;
         }
     
    -
         static SimpleServer createTlsServer(final int port) throws IOException, GeneralSecurityException {
             final SimpleServer server = new TcpServer(SSLServerSocketFactory.getDefault(), new LinkedBlockingDeque<>(), port);
             server.start();
             return server;
         }
     
    -
         static SimpleServer createTlsServer() throws IOException, GeneralSecurityException {
             final SimpleServer server = new TcpServer(SSLServerSocketFactory.getDefault(), new LinkedBlockingDeque<>());
             server.start();
    @@ -117,7 +116,8 @@ private static class TcpServer extends SimpleServer {
             private final ServerSocket serverSocket;
             private volatile Socket socket;
     
    -        private TcpServer(final ServerSocketFactory serverSocketFactory, final BlockingQueue data, final int port) throws IOException {
    +        private TcpServer(final ServerSocketFactory serverSocketFactory, final BlockingQueue data, final int port)
    +                throws IOException {
                 super(data);
                 this.serverSocket = serverSocketFactory.createServerSocket(port);
                 this.data = data;
    diff --git a/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java
    index 53ae39f5..c745362e 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java
    @@ -211,12 +211,7 @@ public void testArchiveRotateZip() throws Exception {
          * size, shouldn't matter as each uses the same rotation logic in the SuffixRotator.
          */
         @Test
    -    @BMRule(name = "Test failed rotated",
    -            targetClass = "java.nio.file.Files",
    -            targetMethod = "move",
    -            targetLocation = "AT ENTRY",
    -            condition = "$2.getFileName().toString().equals(\"rotating-file-handler.log.2\")",
    -            action = "throw new IOException(\"Fail on purpose\")")
    +    @BMRule(name = "Test failed rotated", targetClass = "java.nio.file.Files", targetMethod = "move", targetLocation = "AT ENTRY", condition = "$2.getFileName().toString().equals(\"rotating-file-handler.log.2\")", action = "throw new IOException(\"Fail on purpose\")")
         public void testFailedRotate() throws Exception {
             final SizeRotatingFileHandler handler = new SizeRotatingFileHandler();
             configureHandlerDefaults(handler);
    diff --git a/src/test/java/org/jboss/logmanager/handlers/SocketHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/SocketHandlerTests.java
    index 2dc57ef1..6a38d828 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/SocketHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/SocketHandlerTests.java
    @@ -25,6 +25,7 @@
     import java.util.concurrent.TimeUnit;
     import java.util.function.Supplier;
     import java.util.logging.ErrorManager;
    +
     import javax.net.ssl.SSLContext;
     
     import org.jboss.logmanager.ExtLogRecord;
    @@ -46,8 +47,9 @@ public class SocketHandlerTests extends AbstractHandlerTest {
         // https://bugs.openjdk.java.net/browse/JDK-8219991
         private final String JAVA_VERSION = System.getProperty("java.version");
         private final String JDK_8219991_ERROR_MESSAGE = "https://bugs.openjdk.java.net/browse/JDK-8219991";
    -    private final Boolean JDK_8219991 = JAVA_VERSION.startsWith("1.8") || (JAVA_VERSION.startsWith("11.0.8") && System.getProperty("java.vendor")
    -            .contains("Oracle"));
    +    private final Boolean JDK_8219991 = JAVA_VERSION.startsWith("1.8")
    +            || (JAVA_VERSION.startsWith("11.0.8") && System.getProperty("java.vendor")
    +                    .contains("Oracle"));
     
         public SocketHandlerTests() throws UnknownHostException {
             address = InetAddress.getByName(System.getProperty("org.jboss.test.address", "127.0.0.1"));
    @@ -57,8 +59,7 @@ public SocketHandlerTests() throws UnknownHostException {
         public void testTcpConnection() throws Exception {
             try (
                     SimpleServer server = SimpleServer.createTcpServer();
    -                SocketHandler handler = createHandler(Protocol.TCP, server.getPort())
    -        ) {
    +                SocketHandler handler = createHandler(Protocol.TCP, server.getPort())) {
                 final ExtLogRecord record = createLogRecord("Test TCP handler");
                 handler.publish(record);
                 final String msg = server.timeoutPoll();
    @@ -71,8 +72,7 @@ public void testTcpConnection() throws Exception {
         public void testTlsConnection() throws Exception {
             try (
                     SimpleServer server = SimpleServer.createTlsServer();
    -                SocketHandler handler = createHandler(Protocol.SSL_TCP, server.getPort())
    -        ) {
    +                SocketHandler handler = createHandler(Protocol.SSL_TCP, server.getPort())) {
                 final ExtLogRecord record = createLogRecord("Test TLS handler");
                 handler.publish(record);
                 final String msg = server.timeoutPoll();
    @@ -85,8 +85,7 @@ public void testTlsConnection() throws Exception {
         public void testUdpConnection() throws Exception {
             try (
                     SimpleServer server = SimpleServer.createUdpServer();
    -                SocketHandler handler = createHandler(Protocol.UDP, server.getPort())
    -        ) {
    +                SocketHandler handler = createHandler(Protocol.UDP, server.getPort())) {
                 final ExtLogRecord record = createLogRecord("Test UDP handler");
                 handler.publish(record);
                 final String msg = server.timeoutPoll();
    @@ -100,8 +99,7 @@ public void testTcpPortChange() throws Exception {
             try (
                     SimpleServer server1 = SimpleServer.createTcpServer();
                     SimpleServer server2 = SimpleServer.createTcpServer();
    -                SocketHandler handler = createHandler(Protocol.TCP, server1.getPort())
    -        ) {
    +                SocketHandler handler = createHandler(Protocol.TCP, server1.getPort())) {
                 final int port = server1.getPort();
                 final int altPort = server2.getPort();
                 ExtLogRecord record = createLogRecord("Test TCP handler " + port);
    @@ -164,8 +162,7 @@ public void testTcpReconnect() throws Exception {
     
                 // Publish a record to a running server
                 try (
    -                    SimpleServer server = SimpleServer.createTcpServer()
    -            ) {
    +                    SimpleServer server = SimpleServer.createTcpServer()) {
                     handler = createHandler(Protocol.TCP, server.getPort());
                     handler.setErrorManager(AssertingErrorManager.of(ErrorManager.FLUSH_FAILURE));
                     final ExtLogRecord record = createLogRecord("Test TCP handler");
    @@ -182,8 +179,7 @@ public void testTcpReconnect() throws Exception {
                 final ExtLogRecord record = createLogRecord("Test TCP handler");
                 handler.publish(record);
                 try (
    -                    SimpleServer server = SimpleServer.createTcpServer(handler.getPort())
    -            ) {
    +                    SimpleServer server = SimpleServer.createTcpServer(handler.getPort())) {
                     final SocketHandler socketHandler = handler;
                     // Keep writing a record until a successful record is published or a timeout occurs
                     final String msg = timeout(() -> {
    diff --git a/src/test/java/org/jboss/logmanager/handlers/SyslogHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/SyslogHandlerTests.java
    index 944b8992..221a3f76 100644
    --- a/src/test/java/org/jboss/logmanager/handlers/SyslogHandlerTests.java
    +++ b/src/test/java/org/jboss/logmanager/handlers/SyslogHandlerTests.java
    @@ -26,8 +26,8 @@
     import java.util.logging.Level;
     
     import org.jboss.logmanager.ExtLogRecord;
    -import org.jboss.logmanager.handlers.SyslogHandler.SyslogType;
     import org.jboss.logmanager.formatters.PatternFormatter;
    +import org.jboss.logmanager.handlers.SyslogHandler.SyslogType;
     import org.junit.After;
     import org.junit.Assert;
     import org.junit.Before;
    @@ -72,14 +72,16 @@ public void testRFC5424Tcp() throws Exception {
             // Create the record
             handler.setHostname("test");
             ExtLogRecord record = createRecord(cal, MSG);
    -        String expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - " + BOM + MSG + '\n';
    +        String expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid()
    +                + " - - " + BOM + MSG + '\n';
             handler.publish(record);
             Assert.assertEquals(expectedMessage, createString(out));
     
             // Create the record
             out.reset();
             record = createRecord(cal, MSG);
    -        expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - " + BOM + MSG + '\n';
    +        expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - "
    +                + BOM + MSG + '\n';
             handler.publish(record);
             Assert.assertEquals(expectedMessage, createString(out));
     
    @@ -88,7 +90,8 @@ record = createRecord(cal, MSG);
             record = createRecord(cal, MSG);
             handler.setHostname("test");
             handler.setAppName("java");
    -        expectedMessage = "<14>1 2012-01-31T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - " + BOM + MSG + '\n';
    +        expectedMessage = "<14>1 2012-01-31T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - "
    +                + BOM + MSG + '\n';
             handler.publish(record);
             Assert.assertEquals(expectedMessage, createString(out));
         }
    @@ -130,8 +133,9 @@ public void testOctetCounting() throws Exception {
             // Create the record
             handler.setHostname("test");
             ExtLogRecord record = createRecord(cal, MSG);
    -        String expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - " + BOM + MSG;
    -        expectedMessage = byteLen(expectedMessage)+ " " + expectedMessage;
    +        String expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid()
    +                + " - - " + BOM + MSG;
    +        expectedMessage = byteLen(expectedMessage) + " " + expectedMessage;
             handler.publish(record);
             Assert.assertEquals(expectedMessage, createString(out));
         }
    @@ -151,7 +155,8 @@ public void testTruncation() throws Exception {
             final String part2 = "Truncated portion of the message that will not be shown in.";
             final String message = part1 + " " + part2;
     
    -        final String header = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - " + BOM;
    +        final String header = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid()
    +                + " - - " + BOM;
     
             handler.setMaxLength(byteLen(header, part1));
             handler.setTruncate(true);
    @@ -194,7 +199,8 @@ public void testNullMessage() throws Exception {
             // Create the record
             handler.setHostname("test");
             ExtLogRecord record = createRecord(cal, null);
    -        final String expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - " + BOM + "null";
    +        final String expectedMessage = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java "
    +                + handler.getPid() + " - - " + BOM + "null";
             handler.publish(record);
             Assert.assertEquals(expectedMessage, createString(out));
         }
    @@ -211,7 +217,8 @@ private void testMultibyteTruncation(final String part1, final String part2, fin
             handler.setHostname("test");
             String message = part1 + " " + part2;
     
    -        final String header = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid() + " - - " + BOM;
    +        final String header = "<14>1 2012-01-09T04:39:22.000" + calculateTimeZone(cal) + " test java " + handler.getPid()
    +                + " - - " + BOM;
     
             handler.setMaxLength(byteLen(header, part1));
             handler.setTruncate(true);
    @@ -219,7 +226,8 @@ private void testMultibyteTruncation(final String part1, final String part2, fin
             ExtLogRecord record = createRecord(cal, message);
             String expectedMessage = header + part1;
             handler.publish(record);
    -        Assert.assertTrue(String.format("Expected: %s:%n Received: %s", expectedMessage, createString(out)), Arrays.equals(expectedMessage.getBytes(ENCODING), out.toByteArray()));
    +        Assert.assertTrue(String.format("Expected: %s:%n Received: %s", expectedMessage, createString(out)),
    +                Arrays.equals(expectedMessage.getBytes(ENCODING), out.toByteArray()));
     
             out.reset();
             // Wrap a message
    @@ -227,7 +235,8 @@ private void testMultibyteTruncation(final String part1, final String part2, fin
             handler.publish(record);
             // Extra space from message
             expectedMessage = header + part1 + header + " " + part2;
    -        Assert.assertTrue(String.format("Expected: %s:%n Received: %s", expectedMessage, createString(out)), Arrays.equals(expectedMessage.getBytes(ENCODING), out.toByteArray()));
    +        Assert.assertTrue(String.format("Expected: %s:%n Received: %s", expectedMessage, createString(out)),
    +                Arrays.equals(expectedMessage.getBytes(ENCODING), out.toByteArray()));
     
             // Reset out, write the message with a maximum length of the current length minus 1 to ensure the multi-byte character was not written at the end
             out.reset();
    @@ -235,7 +244,8 @@ private void testMultibyteTruncation(final String part1, final String part2, fin
             handler.setMaxLength(byteLen(header, part1) - 1);
             expectedMessage = header + part1.substring(0, part1.length() - charsToTruncate);
             handler.publish(record);
    -        Assert.assertTrue(String.format("Expected: %s:%n Received: %s", expectedMessage, createString(out)), Arrays.equals(expectedMessage.getBytes(ENCODING), out.toByteArray()));
    +        Assert.assertTrue(String.format("Expected: %s:%n Received: %s", expectedMessage, createString(out)),
    +                Arrays.equals(expectedMessage.getBytes(ENCODING), out.toByteArray()));
         }
     
         private static ExtLogRecord createRecord(final Calendar cal, final String message) {
    
    The name of the host the messages are being sent from. See {@link #setHostname(String)} for more * details{@link String String}{@code null}{@code + * null + * }
    syslogType
    delimiterThe delimiter to use at the end of the message if {@link #setUseMessageDelimiter(boolean) useDelimiter} - * is set to {@code true}{@link String String}For {@link Protocol#UDP UDP} {@code null} - For {@link Protocol#TCP TCP} or {@link Protocol#SSL_TCP + * For {@link Protocol#UDP UDP} {@code + * null + * } - For {@link Protocol#TCP TCP} or {@link Protocol#SSL_TCP * SSL_TCP} {@code \n}
    Whether or not the message should be appended with a {@link #setMessageDelimiter(String) * delimiter}{@code boolean}For {@link Protocol#UDP UDP} {@code false} - For {@link Protocol#TCP TCP} or {@link Protocol#SSL_TCP - * SSL_TCP} {@code true}For {@link Protocol#UDP UDP} {@code + * false + * } - For {@link Protocol#TCP TCP} or {@link Protocol#SSL_TCP + * SSL_TCP} {@code + * true + * }
    useCountingFramingPrefixes the size of the message, mainly used for {@link Protocol#TCP TCP} or {@link Protocol#SSL_TCP - * SSL_TCP}, connections to the message being sent to the syslog server. See http://tools.ietf.org/html/rfc6587 + * SSL_TCP}, connections to the message being sent to the syslog server. See http://tools.ietf.org/html/rfc6587 * for more details on framing types.{@code boolean}{@code false}{@code + * false + * }
    truncateWhether or not a message, including the header, should truncate the message if the length in bytes is - * greater than the {@link #setMaxLength(int) maximum length}. If set to {@code false} messages will be split and sent + * greater than the {@link #setMaxLength(int) maximum length}. If set to {@code + * false + * } messages will be split and sent * with the same header values.{@code boolean}{@code true}{@code + * true + * }
    maxLength