diff --git a/.asf.yaml b/.asf.yaml
index 4522b2ba79..b7e94937c1 100644
--- a/.asf.yaml
+++ b/.asf.yaml
@@ -23,7 +23,8 @@ notifications:
pullrequests: issues@commons.apache.org
jira_options: link label
jobs: notifications@commons.apache.org
- issues_bot_dependabot: notifications@commons.apache.org
- pullrequests_bot_dependabot: notifications@commons.apache.org
+ # commits_bot_dependabot: dependabot@commons.apache.org
+ issues_bot_dependabot: dependabot@commons.apache.org
+ pullrequests_bot_dependabot: dependabot@commons.apache.org
issues_bot_codecov-commenter: notifications@commons.apache.org
pullrequests_bot_codecov-commenter: notifications@commons.apache.org
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 00079caf1b..90ec55f742 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -18,10 +18,8 @@ updates:
- package-ecosystem: "maven"
directory: "/"
schedule:
- interval: "weekly"
- day: "friday"
+ interval: "quarterly"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
- interval: "weekly"
- day: "friday"
+ interval: "quarterly"
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index e17973cb0c..9ff35c83e7 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -22,7 +22,9 @@ Thanks for your contribution to [Apache Commons](https://commons.apache.org/)! Y
Before you push a pull request, review this list:
- [ ] Read the [contribution guidelines](CONTRIBUTING.md) for this project.
+- [ ] Read the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) if you use Artificial Intelligence (AI).
+- [ ] I used AI to create any part of, or all of, this pull request. Which AI tool was used to create this pull request, and to what extent did it contribute?
- [ ] Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
-- [ ] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible but is a best-practice.
+- [ ] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible, but it is a best practice.
- [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
-- [ ] Each commit in the pull request should have a meaningful subject line and body. Note that commits might be squashed by a maintainer on merge.
+- [ ] Each commit in the pull request should have a meaningful subject line and body. Note that a maintainer may squash commits during the merge process.
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index 771c8d0b56..e072e3dd79 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -37,6 +37,7 @@ jobs:
security-events: write
strategy:
+ max-parallel: 20
fail-fast: false
matrix:
language: [ 'java' ]
@@ -45,10 +46,10 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ - uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 #v5.0.3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
@@ -57,7 +58,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
- uses: github/codeql-action/init@ff0a06e83cb2de871e5a09832bc6a81e7276941f # 3.28.18
+ uses: github/codeql-action/init@c6f931105cb2c34c8f901cc885ba1e2e259cf745 # v4.34.0
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -68,7 +69,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
- uses: github/codeql-action/autobuild@ff0a06e83cb2de871e5a09832bc6a81e7276941f # 3.28.18
+ uses: github/codeql-action/autobuild@c6f931105cb2c34c8f901cc885ba1e2e259cf745 # v4.34.0
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -82,4 +83,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@ff0a06e83cb2de871e5a09832bc6a81e7276941f # 3.28.18
+ uses: github/codeql-action/analyze@c6f931105cb2c34c8f901cc885ba1e2e259cf745 # v4.34.0
diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml
index 33573cf948..a04da50909 100644
--- a/.github/workflows/dependency-review.yml
+++ b/.github/workflows/dependency-review.yml
@@ -26,6 +26,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 'Checkout Repository'
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: 'Dependency Review PR'
- uses: actions/dependency-review-action@da24556b548a50705dd671f47852072ea4c105d9 # v4.7.1
+ uses: actions/dependency-review-action@3c4e3dcb1aa7874d2c16be7d79418e9b7efd6261 # v4.8.2
diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
index d182b41b99..ca5362ba4e 100644
--- a/.github/workflows/maven.yml
+++ b/.github/workflows/maven.yml
@@ -26,19 +26,20 @@ jobs:
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
strategy:
+ max-parallel: 20
matrix:
- java: [ 8, 11, 17, 21, 24 ]
+ java: [ 8, 11, 17, 21, 25 ]
experimental: [false]
include:
- - java: 25-ea
+ - java: 26-ea
experimental: true
steps:
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Set up JDK ${{ matrix.java }}
- uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
+ uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
diff --git a/.github/workflows/scorecards-analysis.yml b/.github/workflows/scorecards-analysis.yml
index 52752cbe67..7182c34001 100644
--- a/.github/workflows/scorecards-analysis.yml
+++ b/.github/workflows/scorecards-analysis.yml
@@ -40,12 +40,12 @@ jobs:
steps:
- name: "Checkout code"
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: "Run analysis"
- uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # 2.4.1
+ uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # 2.4.3
with:
results_file: results.sarif
results_format: sarif
@@ -57,13 +57,13 @@ jobs:
publish_results: true
- name: "Upload artifact"
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # 4.6.2
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
name: SARIF file
path: results.sarif
retention-days: 5
- name: "Upload to code-scanning"
- uses: github/codeql-action/upload-sarif@ff0a06e83cb2de871e5a09832bc6a81e7276941f # 3.28.18
+ uses: github/codeql-action/upload-sarif@c6f931105cb2c34c8f901cc885ba1e2e259cf745 # v4.34.0
with:
sarif_file: results.sarif
diff --git a/.gitignore b/.gitignore
index 92a1b2a4a3..c5860d17e9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,3 +18,8 @@ site-content
.project
.externalToolBuilders
/.checkstyle
+/.DS_Store
+
+# NetBeans files
+nb-configuration.xml
+nbactions.xml
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 29041c11c4..9d1083cc5e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -69,7 +69,7 @@ Making Changes
+ Respect the original code style:
+ Only use spaces for indentation; you can check for unnecessary whitespace with `git diff` before committing.
+ Create minimal diffs - disable _On Save_ actions like _Reformat Source Code_ or _Organize Imports_. If you feel the source code should be reformatted create a separate PR for this change first.
-+ Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible but is a best-practice.
++ Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible but is a best practice.
Unit tests are typically in the `src/test/java` directory.
+ Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
+ Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
diff --git a/NOTICE.txt b/NOTICE.txt
index 0c73fbda69..167fda3832 100644
--- a/NOTICE.txt
+++ b/NOTICE.txt
@@ -1,5 +1,5 @@
Apache Commons Text
-Copyright 2014-2025 The Apache Software Foundation
+Copyright 2014-2026 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (https://www.apache.org/).
diff --git a/README.md b/README.md
index 7487c1f2a9..3cd07a15d7 100644
--- a/README.md
+++ b/README.md
@@ -45,12 +45,12 @@ Apache Commons Text
[](https://github.com/apache/commons-text/actions/workflows/maven.yml)
[](https://search.maven.org/artifact/org.apache.commons/commons-text)
-[](https://javadoc.io/doc/org.apache.commons/commons-text/1.13.1)
+[](https://javadoc.io/doc/org.apache.commons/commons-text/1.15.0)
[](https://github.com/apache/commons-text/actions/workflows/codeql-analysis.yml)
[](https://api.securityscorecards.dev/projects/github.com/apache/commons-text)
-Apache Commons Text is a set of utility functions and reusable components for the purpose of processing
- and manipulating text that should be of use in a Java environment.
+Apache Commons Text is a set of utility functions and reusable components for processing
+ and manipulating text in a Java environment.
Documentation
-------------
@@ -69,7 +69,7 @@ Alternatively, you can pull it from the central Maven repositories:
org.apache.commonscommons-text
- 1.13.1
+ 1.15.0
```
@@ -90,8 +90,8 @@ There are some guidelines which will make applying PRs easier for us:
+ Respect the existing code style for each file.
+ Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change.
+ Provide JUnit tests for your changes and make sure your changes don't break any existing tests by running `mvn`.
-+ Before you pushing a PR, run `mvn` (by itself), this runs the default goal, which contains all build checks.
-+ To see the code coverage report, regardless of coverage failures, run `mvn clean site -Dcommons.jacoco.haltOnFailure=false`
++ Before you push a PR, run `mvn` (without arguments). This runs the default goal which contains all build checks.
++ To see the code coverage report, regardless of coverage failures, run `mvn clean site -Dcommons.jacoco.haltOnFailure=false -Pjacoco`
If you plan to contribute on a regular basis, please consider filing a [contributor license agreement](https://www.apache.org/licenses/#clas).
You can learn more about contributing via GitHub in our [contribution guidelines](CONTRIBUTING.md).
diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt
index fdec18aa43..f299b31453 100644
--- a/RELEASE-NOTES.txt
+++ b/RELEASE-NOTES.txt
@@ -14,6 +14,118 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+Apache Commons Text 1.15.0 Release Notes
+----------------------------------------
+
+The Apache Commons Text team is pleased to announce the release of Apache Commons Text 1.15.0.
+
+Apache Commons Text is a set of utility functions and reusable components for processing
+and manipulating text in a Java environment.
+
+Release 1.15.0. This is a feature and maintenance release. Java 8 or later is required.
+
+
+New features
+------------
+
+* Add experimental CycloneDX VEX file #683. Thanks to Piotr P. Karwasz, Gary Gregory.
+* TEXT-235: Add Damerau-Levenshtein distance #687. Thanks to LorgeN, Gary Gregory.
+* Add unit tests to increase coverage #719. Thanks to Michael Hausegger, Gary Gregory.
+* Add new test for CharSequenceTranslator#with() #725. Thanks to Michael Hausegger, Gary Gregory.
+* Add tests and assertions to org.apache.commons.text.similarity to get to 100% code coverage #727, #728. Thanks to Michael Hausegger.
+
+Fixed Bugs
+----------
+
+* Fix exception message typo in XmlStringLookup.XmlStringLookup(Map, Path...). Thanks to Gary Gregory.
+* TEXT-236: Inserting at the end of a TextStringBuilder throws a StringIndexOutOfBoundsException. Thanks to Pierre Post, Sumit Bera, Alex Herbert, Gary Gregory.
+* Fix TextStringBuilderTest.testAppendToCharBuffer() to use proper argument type #724. Thanks to Michael Hausegger.
+* Fix Apache RAT plugin console warnings. Thanks to Gary Gregory.
+* Fix site XML to use version 2.0.0 XML schema. Thanks to Gary Gregory.
+* Removed unreachable threshold verification code in src/main/java/org/apache/commons/text/similarity #730. Thanks to Michael Hausegger.
+* Enable secure processing for the XML parser in XmlStringLookup in case the underlying JAXP implementation doesn't #729. Thanks to 김민재 (minjas0507), Gary Gregory, Piotr Karwasz.
+
+Changes
+-------
+
+* Bump org.apache.commons:commons-parent from 85 to 93 #704, #723, #726. Thanks to Gary Gregory.
+* Bump commons.bytebuddy.version from 1.17.6 to 1.18.2 #696, #722. Thanks to Gary Gregory.
+* Bump graalvm.version from 24.2.2 to 25.0.1 #703, #716. Thanks to Gary Gregory, Dependabot.
+* Bump org.apache.commons:commons-lang3 from 3.18.0 to 3.20.0. Thanks to Gary Gregory.
+* Bump commons-io:commons-io from 2.20.0 to 2.21.0. Thanks to Gary Gregory.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-text/changes.html
+
+For complete information on Apache Commons Text, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons Text website:
+
+https://commons.apache.org/proper/commons-text
+
+Download page: https://commons.apache.org/proper/commons-text/download_text.cgi
+
+Have fun!
+-Apache Commons Team
+
+-----------------------------------------------------------------------------
+
+Apache Commons Text 1.14.0 Release Notes
+----------------------------------------
+
+The Apache Commons Text team is pleased to announce the release of Apache Commons Text 1.14.0.
+
+Apache Commons Text is a set of utility functions and reusable components for processing
+and manipulating text in a Java environment.
+
+Release 1.14.0. Requires Java 8 or above.
+
+
+New features
+------------
+
+* Interface StringLookup now extends UnaryOperator. Thanks to Gary Gregory.
+* Interface TextRandomProvider extends IntUnaryOperator. Thanks to Gary Gregory.
+* Add RandomStringGenerator.Builder.usingRandom(IntUnaryOperator). Thanks to Gary Gregory.
+* Add PMD check to default Maven goal. Thanks to Gary Gregory.
+* Add org.apache.commons.text.RandomStringGenerator.Builder.setAccumulate(boolean). Thanks to Gary Gregory.
+
+Fixed Bugs
+----------
+
+* Fix PMD UnnecessaryFullyQualifiedName in StringLookupFactory. Thanks to Gary Gregory.
+* Fix PMD UnnecessaryFullyQualifiedName in DefaultStringLookupsHolder. Thanks to Gary Gregory.
+* Fix PMD UnnecessaryFullyQualifiedName in PropertiesStringLookup. Thanks to Gary Gregory.
+* Fix PMD UnnecessaryFullyQualifiedName in JavaPlatformStringLookup. Thanks to Gary Gregory.
+* Fix PMD UnnecessaryFullyQualifiedName in StringSubstitutor. Thanks to Gary Gregory.
+* Fix PMD UnnecessaryFullyQualifiedName in StrSubstitutor. Thanks to Gary Gregory.
+* Fix PMD UnnecessaryFullyQualifiedName in AlphabetConverter. Thanks to Gary Gregory.
+* Fix PMD AvoidBranchingStatementAsLastInLoop in TextStringBuilder. Thanks to Gary Gregory.
+* Fix PMD AvoidBranchingStatementAsLastInLoop in StrBuilder. Thanks to Gary Gregory.
+* org.apache.commons.text.translate.LookupTranslator.LookupTranslator(Map CharSequence>) now throws NullPointerException instead of java.security.InvalidParameterException. Thanks to Gary Gregory.
+
+Changes
+-------
+
+* Bump org.apache.commons:commons-parent from 81 to 85 #668. Thanks to Dependabot, Gary Gregory.
+* Bump commons-io:commons-io from 2.18.0 to 2.20.0. Thanks to Gary Gregory.
+* Bump graalvm.version from 24.2.0 to 24.2.2 #665, #681. Thanks to Dependabot, Gary Gregory.
+* Bump commons.bytebuddy.version from 1.17.5 to 1.17.6 (#677). Thanks to Dependabot.
+* Bump org.apache.commons:commons-lang3 from 3.17.0 to 3.18.0 #680. Thanks to Dependabot.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-text/changes.html
+
+For complete information on Apache Commons Text, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons Text website:
+
+https://commons.apache.org/proper/commons-text
+
+Download page: https://commons.apache.org/proper/commons-text/download_text.cgi
+
+Have fun!
+-Apache Commons Team
+
+-----------------------------------------------------------------------------
Apache Commons Text 1.13.1 Release Notes
----------------------------------------
@@ -53,22 +165,6 @@ Have fun!
-----------------------------------------------------------------------------
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
-https://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
-
Apache Commons Text Version 1.13.0 Release Notes
------------------------------------------------
@@ -141,22 +237,6 @@ Have fun!
-----------------------------------------------------------------------------
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
-https://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
-
Apache Commons Text Version 1.12.0 Release Notes
------------------------------------------------
@@ -206,22 +286,6 @@ Have fun!
-----------------------------------------------------------------------------
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
-https://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
-
Apache Commons Text Version 1.11.0 Release Notes
------------------------------------------------
@@ -318,7 +382,7 @@ New features
* TEXT-207: Add DoubleFormat utility.
* TEXT-190: Document negative limit for WordUtils abbreviate method Thanks to Benjamin Bing.
-* TEXT-188: Speed up LevenshteinDistance with threshold by exiting early Thanks to Jakob Vesterstrm.
+* TEXT-188: Speed up LevenshteinDistance with threshold by exiting early Thanks to Jakob Vesterstrøm.
* TEXT-185: Release Notes page hasn't been updated for 1.9 release yet. Thanks to Larry West, Gary Gregory.
* Add StrBuilder.isNotEmpty(). Thanks to Gary Gregory.
diff --git a/pom.xml b/pom.xml
index 6f2f38a328..bc8e9a9200 100644
--- a/pom.xml
+++ b/pom.xml
@@ -7,7 +7,7 @@
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -20,10 +20,10 @@
org.apache.commonscommons-parent
- 84
+ 97commons-text
- 1.14.0-SNAPSHOT
+ 1.15.1-SNAPSHOTApache Commons TextApache Commons Text is a set of utility functions and reusable components for processing
and manipulating text in a Java environment.
@@ -33,31 +33,25 @@
ISO-8859-1UTF-8
- 2025-04-10T21:38:03Z
+ 2025-12-07T22:18:14Z1.81.8
-
texttextorg.apache.commons.text
-
- 1.14.0
- 1.14.1
+ 1.15.01
+ 1.15.2(Java 8+)
-
TEXT12318221
-
texthttps://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-textsite-content
-
- 3.17.0
- 1.17.5
+ 3.20.0
+ 1.18.71.6false1.37
-
org.apache.commons.lang3;version="${commons.lang3.version}",
@@ -65,10 +59,9 @@
org.apache.commons.lang3.time;version="${commons.lang3.version}",
*
-
- 1.13.1
+ 1.15.0RC1truescm:svn:https://dist.apache.org/repos/dist/dev/commons/${commons.componentid}
@@ -78,15 +71,15 @@
commons.releaseManagerName
commons.releaseManagerKey
-->
- 0.8.12
+
true1.00
- 0.97
- 0.98
+ 0.99
+ 0.990.95
- 0.94
- 0.98
+ 0.99
+ 0.97
@@ -100,6 +93,11 @@
junit-jupitertest
+
+ org.junit-pioneer
+ junit-pioneer
+ test
+ net.bytebuddy
@@ -117,7 +115,7 @@
commons-iocommons-io
- 2.19.0
+ 2.21.0test
@@ -138,24 +136,28 @@
${jmh.version}test
+
+ org.apache.commons
+ commons-csv
+ 1.14.1
+ test
+
-
- clean verify apache-rat:check japicmp:cmp checkstyle:check spotbugs:check javadoc:javadoc
+ clean verify apache-rat:check japicmp:cmp checkstyle:check pmd:check spotbugs:check javadoc:javadocorg.apache.ratapache-rat-plugin
-
- site-content/**
- src/site/resources/download_text.cgi
- src/site/resources/release-notes/RELEASE-NOTES-*.txt
- src/test/resources/org/apache/commons/text/stringEscapeUtilsTestData.txt
- src/test/resources/org/apache/commons/text/lcs-perf-analysis-inputs.csv
- src/test/resources/org/apache/commons/text/oss-fuzz/**
-
+
+ site-content/**
+ src/site/resources/download_text.cgi
+ src/site/resources/release-notes/RELEASE-NOTES-*.txt
+ src/test/resources/org/apache/commons/text/stringEscapeUtilsTestData.txt
+ src/test/resources/org/apache/commons/text/oss-fuzz/**
+
@@ -242,7 +244,6 @@
-
@@ -336,9 +337,7 @@
-
2014
-
kinow
@@ -376,7 +375,6 @@
djones@apache.org
-
Don Jeba
@@ -421,18 +419,14 @@
https://ali-ghanbari.github.io/
-
scm:git:https://gitbox.apache.org/repos/asf/commons-textscm:git:https://gitbox.apache.org/repos/asf/commons-texthttps://gitbox.apache.org/repos/asf?p=commons-text.git
-
- jirahttps://issues.apache.org/jira/browse/TEXT
-
apache.website
@@ -440,7 +434,10 @@
scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text/
-
+
+ GitHub
+ https://github.com/apache/commons-text/actions
+
@@ -513,7 +510,7 @@
[22,)
- 24.2.1
+ 25.0.15.2.0
@@ -607,13 +604,45 @@
+
benchmarktrueorg.apache
+
+
+ org.openjdk.jmh
+ jmh-core
+ ${commons.jmh.version}
+ test
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${commons.jmh.version}
+ test
+
+
+ org.apache.commons
+ commons-collections4
+ 4.5.0
+ test
+
+
+
+
+ maven-compiler-plugin
+ ${commons.compiler.version}
+
+
+ **/*
+
+
+
+
org.codehaus.mojoexec-maven-plugin
@@ -629,12 +658,12 @@
java-classpath
-
+ org.openjdk.jmh.Main-rfjson-rff
- target/jmh-result.${benchmark}.json
+ target/jmh-result.json${benchmark}
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index a2ffe138dc..a3ae6cc2bc 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -37,350 +37,387 @@ and commit
The type attribute can be add,update,fix,remove.
-->
-
-
+Apache Commons Text Changes
-
-
-
- Interface StringLookup now extends UnaryOperator<String>.
- Interface TextRandomProvider extends IntUnaryOperator.
- Add RandomStringGenerator.Builder.usingRandom(IntUnaryOperator).
-
- Bump org.apache.commons:commons-parent from 81 to 84 #668.
- Bump commons-io:commons-io from 2.18.0 to 2.19.0.
- Bump graalvm.version from 24.2.0 to 24.2.1 #665.
-
-
-
- Remove -nouses directive from maven-bundle-plugin. OSGi package imports now state 'uses' definitions for package imports, this doesn't affect JPMS (from org.apache.commons:commons-parent:80).
- Deprecate EntityArrays.EntityArrays().
- StringLookupFactory.DefaultStringLookupsHolder.createDefaultStringLookups() maps DefaultStringLookup.LOCAL_HOST twice instead of once for LOCAL_HOST and LOOPBACK_ADDRESS.
-
-
- Bump org.apache.commons:commons-parent from 79 to 81.
- Bump commons.bytebuddy.version from 1.16.1 to 1.17.5 #643, #659, #660.
- Bump graalvm.version from 24.1.2 to 24.2.0 #653.
-
-
-
- Add StringLookupFactory.loopbackAddressStringLookup().
- Add StringLookupFactory.KEY_LOOPBACK_ADDRESS.
- Add DefaultStringLookup.LOOPBACK_ADDRESS.
- Add richer inputs in package org.apache.commons.text.similarity with SimilarityInput.
- Add HammingDistance.apply(SimilarityInput, SimilarityInput).
- Add JaccardDistance.apply(SimilarityInput, SimilarityInput).
- Add JaccardSimilarity.apply(SimilarityInput, SimilarityInput).
- Add JaroWinklerDistance.apply(SimilarityInput, SimilarityInput).
- Add JaroWinklerSimilarity.apply(SimilarityInput, SimilarityInput).
- Add LevenshteinDetailedDistance.apply(SimilarityInput, SimilarityInput).
- Add LevenshteinDistance.apply(SimilarityInput, SimilarityInput).
-
- Fix build on Java 22.
- Fix build on Java 23-ea.
- Make package-private constructor private: StrLookup.MapStrLookup.MapStrLookup(Map).
- Make package-private constructor private: StrLookup.SystemPropertiesStrLookup.SystemPropertiesStrLookup().
- Make package-private class private and final: MapStrLookup.
- Make package-private class private: StrMatcher.CharMatcher.
- Make package-private class private: StrMatcher.CharSetMatcher.
- Make package-private class private: StrMatcher.NoMatcher.
- Make package-private class private: StrMatcher.StringMatcher.
- Make package-private class private: StrMatcher.TrimMatcher.
- Make package-private class private and final: IntersectionSimilarity.BagCount.
- Make package-private class private and final: IntersectionSimilarity.TinyCount.
- Deprecate LevenshteinDistance.LevenshteinDistance() in favor of LevenshteinDistance.getDefaultInstance().
- Deprecate LevenshteinDetailedDistance.LevenshteinDetailedDistance() in favor of LevenshteinDetailedDistance.getDefaultInstance().
- Improve StrBuilder documentation for new line text.
- Improve TextStringBuilder documentation for new line text #547.
- Required OSGi Import-Package version numbers in MANIFEST.MF #627.
-
- Bump org.apache.commons:commons-parent from 69 to 78 #542, #557, #571, #581, #584, #593, #600, #603, #614.
- Bump tests on Java >= 22 org.graalvm.*:* from 24.0.0 to 24.1.1 #592, #610.
- Bump commons.bytebuddy.version from 1.14.13 to 1.16.1 #538, #548, #553, #565, #579, #582, #585, #596, #597, #604, #612, #620, #623, #625, #640.
- Bump SpotBugs from 4.8.3 to 4.8.5.
- Bump org.assertj:assertj-core from 3.25.3 to 3.26.3 #554, #566.
- Bump org.codehaus.mojo:taglist-maven-plugin from 3.0.0 to 3.2.1 #564, #611.
- Bump org.apache.commons:commons-rng-simple from 1.5 to 1.6 #568.
- Bump org.apache.commons:commons-lang3 from 3.14.0 to 3.17.0 #569, #575, #586.
- Bump commons-io:commons-io from 2.16.1 to 2.18.0 #594, #628.
-
-
-
- Add StringLookupFactory.fileStringLookup(Path...) and deprecated fileStringLookup().
- Add StringLookupFactory.propertiesStringLookup(Path...) and deprecated propertiesStringLookup().
- Add StringLookupFactory.xmlStringLookup(Map, Path...) and deprecated xmlStringLookup() and xmlStringLookup(Map).
- Add StringLookupFactory.builder() for fencing Path resolution of the file, properties and XML lookups.
- Add DoubleFormat.Builder.get() as Builder now implements Supplier.
-
- WordUtils.containsAllWords() may throw PatternSyntaxException.
- Fix regression for determining whitespace in WordUtils #519.
- Deprecate Builder in favor of Supplier.
-
- Bump commons-lang3 from 3.13.0 to 3.14.0.
- Bump commons.bytebuddy.version from 1.14.9 to 1.14.13 #476, #482, #505, #521.
- Bump org.codehaus.mojo:exec-maven-plugin from 3.1.0 to 3.2.0 #474, #508.
- Bump commons-io from 2.15.0 to 2.16.1 #522, #527.
- Bump commons-parent from 64 to 69 #524.
- Bump org.assertj:assertj-core from 3.24.2 to 3.25.3.
-
-
-
- Fix StringTokenizer.getTokenList to return an independent modifiable list
- Fix Javadoc for StringEscapeUtils.escapeHtml4 #382
- TextStringBuidler#hashCode() allocates a String on each call #387.
- Fix Bundle-SymbolicName to use the package name org.apache.commons.text
- Add and use a package-private singleton for RegexTokenizer.
- Add and use a package-private singleton for CosineSimilarity.
- Add and use a package-private singleton for LongestCommonSubsequence.
- Add and use a package-private singleton for JaroWinklerSimilarity.
- Add and use a package-private singleton for JaccardSimilarity.
- [StepSecurity] ci: Harden GitHub Actions #428.
- Improve AlphabetConverter Javadoc #429.
- Fix exception message in IntersectionResult to make set-theoretic sense #438.
- Add null-check in RandomStringGenerator#Builder#selectFrom() to avoid NullPointerException #434.
- Add null-check in RandomStringGenerator#Builder#withinRange() to avoid NullPointerException.
- Fix TextStringBuilder to over-allocate when ensuring capacity #452.
- Constructor for ResourceBundleStringLookup should be private instead of package-private.
- Constructor for UrlDecoderStringLookup should be private instead of package-private.
- Constructor for UrlEncoderStringLookup should be private instead of package-private.
- Javadoc of org.apache.commons.text.lookup.DefaultStringLookup.XML is incorrect.
- Update DoubleFormat to state it is based on Double.toString. #467.
-
- Set SecureProcessing feature in XmlStringLookup by default.
- Add StringLookupFactory.xmlStringLookup(Map<String, Boolean>...).
- Add @FunctionalInterface to FormatFactory.
- Add RandomStringGenerator.builder().
- Add XmlEncoderStringLookup/XmlDecoderStringLookup #449.
- Add StringSubstitutor.toString().
-
- Bump actions/cache.
- Bump actions/setup-java.
- Bump actions/checkout.
- Bump pmd from 6.49.0 to 6.52.0 #364.
- Bump commons-rng-simple from 1.4 to 1.5 #370.
- Bump spotbugs-maven-plugin from 4.7.2.0 to 4.7.3.6 #371, #385.
- Bump spotbugs from 4.7.2 to 4.7.3 #373.
- Bump mockito-inline from 4.8.0 to 4.11.0 #380, #389, #396, #400.
- Bump jmh.version from 1.35 to 1.37 #388.
- Bump commons-parent from 54 to 64 #392, #401.
- Bump assertj-core from 3.23.1 to 3.24.2 #405, #410.
- Bump maven-checkstyle-plugin from 3.2.0 to 3.2.1 #407.
- Bump commons-io from 2.11.0 to 2.15.0.
- Bump commons-lang3 from 3.12.0 to 3.13.0.
-
-
-
- Fix CaseUtils when the input string contains only delimiters
- Add GraalVM test dependencies to fix test failures with Java 15.
- Incorrect values for Jaccard similarity with empty strings.
- StringSubstitutor map constructor throws NPE on 1.9 with null map.
- JaroWinklerDistance returns the same values as JaroWinklerSimilarity.
- Correct Javadoc in FileStringLookup.
- Minor Improvements #192, #196.
- Use StringUtils.INDEX_NOT_FOUND constant.
- Remove redundant local variable.
- Replace lambda with method reference.
- Simplify statements.
- Replace statement lambda with expression lambda.
- Use static class inner class in tests.
- Simplify assertion.
- Extract duplicate code.
- Set void return method.
- Remove unused exception from TextStringBuilder.readFrom(CharBuffer). This preserves binary compatibility but not source compatibility.
- StrBuilder.StrBuilderReader.skip(long): Throw an exception when an implicit narrowing conversion in a compound assignment would result in information loss or a numeric error such as an overflows.
- TextStringBuilder.TextStringBuilderReader.skip(long): Throw an exception when an implicit narrowing conversion in a compound assignment would result in information loss or a numeric error such as an overflows.
- TextStringBuilder.equals whatever the capacity is #281.
- A More Efficient Implementation for Calculating Size of Longest Common Subsequence.
- LookupTranslator returns count of chars consumed, not of codepoints consumed.
- Use Math.min() call instead of doing it manually. #335.
- TextStringBuilder: Throw OutOfMemoryError instead of NegativeArraySizeException.
- TextStringBuilder: Can't grow to sizes up to Integer.MAX_VALUE.
- Make default string lookups configurable via system property. Remove dns, url, and script lookups from defaults. If these lookups are required for use in StringSubstitutor.createInterpolator(), they must be enabled via system property. See StringLookupFactory for details.
-
- Add DoubleFormat utility.
- Document negative limit for WordUtils abbreviate method
- Speed up LevenshteinDistance with threshold by exiting early
- Release Notes page hasn't been updated for 1.9 release yet.
- Add StrBuilder.isNotEmpty().
-
- Bump actions/setup-java from v1.4.0 to 3 #147, #156, #155, #172, #215, #314.
- Bump github/codeql-action from 1 to 2 #319.
- Bump checkstyle from 8.34 to 9.3, #141, #168, #182, #188, #193, #201, #208, #211, #228, #235, #245, #253, #255, #262, #270, #280, #287, #299, #315, #321.
- Bump spotbugs-maven-plugin from 4.0.0 to 4.7.2.0, #144, #150, #167, #176, #194, #210, #223, #250, #268, #273, #277, #278, #286, #293, #303, #320, #325, #338, #344, #354.
- Bump spotbugs from 4.1.3 to 4.7.2 #175, 189, #209, #218, #247, #256, #264, #275, #284, #289, #296, #306, #355.
- Bump mockito-inline from 3.4.4 to 4.8.0, #143, #148, #149, #152, #153, #154, #158, #159, #166, #177, #180, #187, #195, #197, #207, #216, #231, #236, #237, #243, #258, #259, #260, #261, #272, #285, #291, #305, #317, #330, #331, #347, #352.
- Bump junit-jupiter from 5.6.2 to 5.9.1 #163, #204, #232, #265, #269, #288, #343, #357.
- Bump assertj-core from 3.16.1 to 3.23.1 #151, #157, #160, #178, #184, #199, #244, #267, #294.
- Bump commons-io from 2.7 to 2.11.0 #161 #251.
- Bump commons-parent from 51 to 54 #145, #358.
- Bump maven-pmd-plugin from 3.13.0 to 3.19.0 #186, #263, #302, #334, #349, #353.
- Bump pmd from 6.42.0 to 6.46.0.
- Bump graalvm.version from 20.2.0 to 22.0.0.2 #185, #198, #206, #227, #252, #276, #295, #300.
- Bump commons.japicmp.version from 0.14.3 to 0.16.0.
- Bump commons.jacoco.version 0.8.5 to 0.8.8; fixes Java 15 build.
- Bump maven-checkstyle-plugin from 3.1.1 to 3.2.0 #202, #348.
- Bump commons-lang3 3.11 -> 3.12.0.
- Bump commons.javadoc.version from 3.2.0 to 3.4.1.
- Bump commons.project-info.version from 3.1.0 to 3.1.2.
- Bump jmh.version from 1.32 to 1.35 #254, #292, #313.
- Bump commons-rng-simple from 1.3 to 1.4 #266.
- Bump taglist-maven-plugin from 2.4 to 3.0.0 #297.
- Bump commons.pmd-impl.version from 6.44.0 to 6.49.0 #323, #336, #345, #350.
- Bump exec-maven-plugin from 3.0.0 to 3.1.0 #340.
-
-
- Removed non-existing parameter from Javadocs and spelled out parameters in throws.
- StringEscapeUtils.unescapeCsv doesn't remove quotes at begin and end of string.
- ScriptStringLookup does not accept ":" #126.
- StringSubstitutor incorrectly removes some escape characters.
- Fix Javadocs #135.
- Fix typos #137.
- Make ConstantStringLookup.constantCache final #136.
- Simplify if in CaseUtils #134.
- [javadoc] Fix compiler warnings in Java code example in Javadoc #124.
- Update from Apache Commons Lang 3.9 to 3.11.
- Add StringMatcher.size().
- Refactor TextStringBuilder.readFrom(Readable), extracting readFrom(CharBuffer) and readFrom(Reader).
- Add BiStringLookup and implementation BiFunctionStringLookup.
- Add org.apache.commons.text.StringSubstitutor.StringSubstitutor(StringSubstitutor).
- Add org.apache.commons.text.TextStringBuilder.TextStringBuilder(CharSequence).
- Add org.apache.commons.text.TextStringBuilder.drainChar(int).
- Add org.apache.commons.text.TextStringBuilder.drainChars(int, int, char[]. int).
- Add org.apache.commons.text.TextStringBuilder.isNotEmpty().
- Add org.apache.commons.text.TextStringBuilder.isReallocated().
- Add org.apache.commons.text.TextStringBuilder.readFrom(Reader, int).
- Add org.apache.commons.text.TextStringBuilder.set(String).
- Add org.apache.commons.text.TextStringBuilder.wrap(char[]).
- Add org.apache.commons.text.TextStringBuilder.wrap(char[], int).
- Add org.apache.commons.text.io.StringSubstitutorReader.
- Add org.apache.commons.text.lookup.StringLookupFactory.functionStringLookup(Function<String, V>).
- Add org.apache.commons.text.matcher.StringMatcher.isMatch(CharSequence, int).
- Add org.apache.commons.text.matcher.StringMatcher.isMatch(CharSequence, int, int, int).
- Add org.apache.commons.text.matcher.StringMatcherFactory.andMatcher(StringMatcher...).
- Add org.apache.commons.text.matcher.StringMatcherFactory.stringMatcher(char...).
- [build] Skip clirr since we use JApiCmp.
- [test] junit-jupiter 5.5.1 -> 5.5.2.
- [test] org.assertj:assertj-core 3.13.2 -> 3.16.1.
- [build] com.puppycrawl.tools:checkstyle 8.23 -> 8.34.
- [build] Update JUnit from 5.5.2 to 5.6.2.
- [build] commons.jacoco.version 0.8.4 -> 0.8.5.
- [build] commons.javadoc.version 3.1.1 -> 3.2.0.
- [build] commons.japicmp.version 0.14.1 -> 0.14.3.
- [build] checkstyle.plugin.version 3.1.0 -> 3.1.1.
- [build] checkstyle.version 8.27 -> 8.33.
- [build] org.apache.commons:commons-parent 48 -> 51.
- [build] maven-pmd-plugin 3.12.0 -> 3.13.0.
- [build] org.mockito 3.3.3 -> 3.4.4.
-
-
-
- commons-text web page missing "RELEASE-NOTES-1.7.txt"
- (doc) Fixed wrong value for Jaro-Winkler example #117
- Add helper factory method org.apache.commons.text.StringSubstitutor.createInterpolator().
- Add String lookup for host names and IP addresses (DnsStringLookup).
- StringLookupFactory.addDefaultStringLookups(Map) does not convert keys to lower case.
- Expand Javadoc for StringSubstitutor and friends.
- [site] checkstyle.version 8.21 -> 8.23.
-
-
-
- WordUtils.wrap must calculate offset increment from wrapOn pattern length
- Jaro Winkler Distance refers to similarity
- Add an enum to the lookup package that lists all StringLookups
- Add a toggle to throw an exception when a variable is unknown in StringSubstitutor
- TextStringBuilder append sub-sequence not consistent with Appendable.
- Fix possible infinite loop in WordUtils.wrap for a regex pattern that would trigger on a match of 0 length
- Make prefixSet in LookupTranslator a BitSet
- Fix the RegexTokenizer to use a static Pattern
- Remove rounding from JaccardDistance and JaccardSimilarity
- Fix the JaroWinklerSimilarity to use StringUtils.equals to test for CharSequence equality
- Add a generic IntersectionSimilarity measure
- Update Apache Commons Lang from 3.8.1 to 3.9.
- ResourceBundleStringLookup.lookup(String) throws MissingResourceException instead of returning null.
- Update tests from org.assertj:assertj-core 3.12.1 to 3.12.2.
- Update site from com.puppycrawl.tools:checkstyle 8.18 to 8.21.
-
-
-
- Add the resource string bundle string lookup to the default set of lookups
- Add StringLookupFactory methods for the URL encoder and decoder string lookups
- org.apache.commons.text.lookup.StringLookupFactory.interpolatorStringLookup() should reuse a singleton instance
- Add a Base64 encoder string lookup.
-
-
-
- Improve JaccardSimilarity computational cost
- JSON escaping incorrect for the delete control character
- Fixes JaroWinklerDistance: Wrong results due to precision of transpositions
- JaroWinklerDistance: Calculation deviates from definition
- Update Apache Commons Lang from 3.7 to 3.8.1
- Add a XML file XPath string lookup.
- Add a Properties file string lookup.
- Add a script string lookup.
- Add a file string lookup.
- Add a URL string lookup.
- Add a Base64 string lookup.
- Add org.apache.commons.text.lookup.StringLookupFactory.resourceBundleStringLookup(String).
- Add URL encoder and decoder string lookups.
- Add constant string lookup like the one in Apache Commons Configuration.
-
-
-
- StringEscapeUtils#unescapeJson does not unescape double quotes and forward slash
- Remove mention of SQL escaping from user guide
- Update Java requirement from version 7 to 8.
- Allow full customization with new API org.apache.commons.text.lookup.StringLookupFactory.interpolatorStringLookup(Map<String, StringLookup>, StringLookup, boolean).
- WordUtils.wrap throws StringIndexOutOfBoundsException when wrapLength is Integer.MAX_VALUE.
-
-
-
- Add Automatic-Module-Name MANIFEST entry for Java 9 compatibility
- Build failure with java 9-ea+159
- Add an interpolator string lookup: StringLookupFactory#interpolatorStringLookup()
- Add a StrSubstitutor replacement based on interfaces: StringSubstitutor
- Add a StrBuilder replacement based on the StringMatcher interface: TextStringBuilder
- Add a StrTokenizer replacement based on the StringMatcher interface: StringTokenizer
- Add a local host string lookup: LocalHostStringLookup
- StrLookup API confusing
-
-
-
- Upversion commons-lang to 3.7
- Exception thrown in ExtendedMessageFormat using quotes with custom registry
- StringEscapeUtils#UnEscapeJson doesn't recognize escape signs correctly
- StrSubstitutor: Ability to turn off substitution in values
- RandomStringGenerator able to pass multiple ranges to .withinRange()
- Deprecate isDelimiter and use HashSets for delimiter checks
- WordUtils.initials support for UTF-16 surrogate pairs
- WordUtils should treat an empty delimiter array as no delimiters
- Update RandomStringGenerator to accept a list of valid characters
- Add CharacterPredicates for ASCII letters (uppercase/lowercase) and arabic numerals
- Added CaseUtils class with camel case conversion support
- RandomStringGenerator should be able to generate a String with a random length
- Update commons-lang dependency to version 3.6
- Document that commons-csv should be used in preference to CsvTranslators
- NumericEntityUnescaper.options - fix TODO
- RandomStringGenerator claims to be immutable, but isn't
- Add StrLookup.resourceBundleLookup(ResourceBundle)
- Typo in LongestCommonSubsequence#logestCommonSubsequence
-
-
-
- WordUtils should use toXxxxCase(int) rather than toXxxxCase(char)
- WordUtils.abbreviate support
- Putting WordUtils back in to the codebase
- Add RandomStringGenerator
- RandomStringGenerator: allow users to provide source of randomness
- Correct round issue in Jaro Winkler implementation
- Similar to LANG-1025, clirr fails site build.
-
-
-
+
+ Improve test coverage #732.
+ TextStringBuilder.append(char[], int, int) uses wrong variable in exception message #735.
+
+
+ Bump org.apache.commons:commons-parent from 93 to 97.
+ Bump the level of test coverage checks.
+ Bump commons.bytebuddy.version from 1.18.2 to 1.18.4 #734.
+ Bump commons.bytebuddy.version from 1.18.4 to 1.18.7.
+
+
+
+ Fix exception message typo in XmlStringLookup.XmlStringLookup(Map, Path...).
+ Inserting at the end of a TextStringBuilder throws a StringIndexOutOfBoundsException.
+ Fix TextStringBuilderTest.testAppendToCharBuffer() to use proper argument type #724.
+ Fix Apache RAT plugin console warnings.
+ Fix site XML to use version 2.0.0 XML schema.
+ Removed unreachable threshold verification code in src/main/java/org/apache/commons/text/similarity #730.
+ Enable secure processing for the XML parser in XmlStringLookup in case the underlying JAXP implementation doesn't #729.
+
+ Add experimental CycloneDX VEX file #683.
+ Add Damerau-Levenshtein distance #687.
+ Add unit tests to increase coverage #719.
+ Add new test for CharSequenceTranslator#with() #725.
+ Add tests and assertions to org.apache.commons.text.similarity to get to 100% code coverage #727, #728.
+
+ Bump org.apache.commons:commons-parent from 85 to 93 #704, #723, #726.
+ Bump commons.bytebuddy.version from 1.17.6 to 1.18.2 #696, #722.
+ Bump graalvm.version from 24.2.2 to 25.0.1 #703, #716.
+ Bump org.apache.commons:commons-lang3 from 3.18.0 to 3.20.0.
+ Bump commons-io:commons-io from 2.20.0 to 2.21.0.
+
+
+
+ Fix PMD UnnecessaryFullyQualifiedName in StringLookupFactory.
+ Fix PMD UnnecessaryFullyQualifiedName in DefaultStringLookupsHolder.
+ Fix PMD UnnecessaryFullyQualifiedName in PropertiesStringLookup.
+ Fix PMD UnnecessaryFullyQualifiedName in JavaPlatformStringLookup.
+ Fix PMD UnnecessaryFullyQualifiedName in StringSubstitutor.
+ Fix PMD UnnecessaryFullyQualifiedName in StrSubstitutor.
+ Fix PMD UnnecessaryFullyQualifiedName in AlphabetConverter.
+ Fix PMD AvoidBranchingStatementAsLastInLoop in TextStringBuilder.
+ Fix PMD AvoidBranchingStatementAsLastInLoop in StrBuilder.
+ org.apache.commons.text.translate.LookupTranslator.LookupTranslator(Map CharSequence>) now throws NullPointerException instead of java.security.InvalidParameterException.
+
+ Interface StringLookup now extends UnaryOperator<String>.
+ Interface TextRandomProvider extends IntUnaryOperator.
+ Add RandomStringGenerator.Builder.usingRandom(IntUnaryOperator).
+ Add PMD check to default Maven goal.
+ Add org.apache.commons.text.RandomStringGenerator.Builder.setAccumulate(boolean).
+
+ Bump org.apache.commons:commons-parent from 81 to 85 #668.
+ Bump commons-io:commons-io from 2.18.0 to 2.20.0.
+ Bump graalvm.version from 24.2.0 to 24.2.2 #665, #681.
+ Bump commons.bytebuddy.version from 1.17.5 to 1.17.6 (#677).
+ Bump org.apache.commons:commons-lang3 from 3.17.0 to 3.18.0 #680.
+
+
+
+ Remove -nouses directive from maven-bundle-plugin. OSGi package imports now state 'uses' definitions for package imports, this doesn't affect JPMS (from org.apache.commons:commons-parent:80).
+ Deprecate EntityArrays.EntityArrays().
+ StringLookupFactory.DefaultStringLookupsHolder.createDefaultStringLookups() maps DefaultStringLookup.LOCAL_HOST twice instead of once for LOCAL_HOST and LOOPBACK_ADDRESS.
+
+
+ Bump org.apache.commons:commons-parent from 79 to 81.
+ Bump commons.bytebuddy.version from 1.16.1 to 1.17.5 #643, #659, #660.
+ Bump graalvm.version from 24.1.2 to 24.2.0 #653.
+
+
+
+ Add StringLookupFactory.loopbackAddressStringLookup().
+ Add StringLookupFactory.KEY_LOOPBACK_ADDRESS.
+ Add DefaultStringLookup.LOOPBACK_ADDRESS.
+ Add richer inputs in package org.apache.commons.text.similarity with SimilarityInput.
+ Add HammingDistance.apply(SimilarityInput, SimilarityInput).
+ Add JaccardDistance.apply(SimilarityInput, SimilarityInput).
+ Add JaccardSimilarity.apply(SimilarityInput, SimilarityInput).
+ Add JaroWinklerDistance.apply(SimilarityInput, SimilarityInput).
+ Add JaroWinklerSimilarity.apply(SimilarityInput, SimilarityInput).
+ Add LevenshteinDetailedDistance.apply(SimilarityInput, SimilarityInput).
+ Add LevenshteinDistance.apply(SimilarityInput, SimilarityInput).
+
+ Fix build on Java 22.
+ Fix build on Java 23-ea.
+ Make package-private constructor private: StrLookup.MapStrLookup.MapStrLookup(Map).
+ Make package-private constructor private: StrLookup.SystemPropertiesStrLookup.SystemPropertiesStrLookup().
+ Make package-private class private and final: MapStrLookup.
+ Make package-private class private: StrMatcher.CharMatcher.
+ Make package-private class private: StrMatcher.CharSetMatcher.
+ Make package-private class private: StrMatcher.NoMatcher.
+ Make package-private class private: StrMatcher.StringMatcher.
+ Make package-private class private: StrMatcher.TrimMatcher.
+ Make package-private class private and final: IntersectionSimilarity.BagCount.
+ Make package-private class private and final: IntersectionSimilarity.TinyCount.
+ Deprecate LevenshteinDistance.LevenshteinDistance() in favor of LevenshteinDistance.getDefaultInstance().
+ Deprecate LevenshteinDetailedDistance.LevenshteinDetailedDistance() in favor of LevenshteinDetailedDistance.getDefaultInstance().
+ Improve StrBuilder documentation for new line text.
+ Improve TextStringBuilder documentation for new line text #547.
+ Required OSGi Import-Package version numbers in MANIFEST.MF #627.
+
+ Bump org.apache.commons:commons-parent from 69 to 78 #542, #557, #571, #581, #584, #593, #600, #603, #614.
+ Bump tests on Java >= 22 org.graalvm.*:* from 24.0.0 to 24.1.1 #592, #610.
+ Bump commons.bytebuddy.version from 1.14.13 to 1.16.1 #538, #548, #553, #565, #579, #582, #585, #596, #597, #604, #612, #620, #623, #625, #640.
+ Bump SpotBugs from 4.8.3 to 4.8.5.
+ Bump org.assertj:assertj-core from 3.25.3 to 3.26.3 #554, #566.
+ Bump org.codehaus.mojo:taglist-maven-plugin from 3.0.0 to 3.2.1 #564, #611.
+ Bump org.apache.commons:commons-rng-simple from 1.5 to 1.6 #568.
+ Bump org.apache.commons:commons-lang3 from 3.14.0 to 3.17.0 #569, #575, #586.
+ Bump commons-io:commons-io from 2.16.1 to 2.18.0 #594, #628.
+
+
+
+ Add StringLookupFactory.fileStringLookup(Path...) and deprecated fileStringLookup().
+ Add StringLookupFactory.propertiesStringLookup(Path...) and deprecated propertiesStringLookup().
+ Add StringLookupFactory.xmlStringLookup(Map, Path...) and deprecated xmlStringLookup() and xmlStringLookup(Map).
+ Add StringLookupFactory.builder() for fencing Path resolution of the file, properties and XML lookups.
+ Add DoubleFormat.Builder.get() as Builder now implements Supplier.
+
+ WordUtils.containsAllWords() may throw PatternSyntaxException.
+ Fix regression for determining whitespace in WordUtils #519.
+ Deprecate Builder in favor of Supplier.
+
+ Bump commons-lang3 from 3.13.0 to 3.14.0.
+ Bump commons.bytebuddy.version from 1.14.9 to 1.14.13 #476, #482, #505, #521.
+ Bump org.codehaus.mojo:exec-maven-plugin from 3.1.0 to 3.2.0 #474, #508.
+ Bump commons-io from 2.15.0 to 2.16.1 #522, #527.
+ Bump commons-parent from 64 to 69 #524.
+ Bump org.assertj:assertj-core from 3.24.2 to 3.25.3.
+
+
+
+ Fix StringTokenizer.getTokenList to return an independent modifiable list
+ Fix Javadoc for StringEscapeUtils.escapeHtml4 #382
+ TextStringBuidler#hashCode() allocates a String on each call #387.
+ Fix Bundle-SymbolicName to use the package name org.apache.commons.text
+ Add and use a package-private singleton for RegexTokenizer.
+ Add and use a package-private singleton for CosineSimilarity.
+ Add and use a package-private singleton for LongestCommonSubsequence.
+ Add and use a package-private singleton for JaroWinklerSimilarity.
+ Add and use a package-private singleton for JaccardSimilarity.
+ [StepSecurity] ci: Harden GitHub Actions #428.
+ Improve AlphabetConverter Javadoc #429.
+ Fix exception message in IntersectionResult to make set-theoretic sense #438.
+ Add null-check in RandomStringGenerator#Builder#selectFrom() to avoid NullPointerException #434.
+ Add null-check in RandomStringGenerator#Builder#withinRange() to avoid NullPointerException.
+ Fix TextStringBuilder to over-allocate when ensuring capacity #452.
+ Constructor for ResourceBundleStringLookup should be private instead of package-private.
+ Constructor for UrlDecoderStringLookup should be private instead of package-private.
+ Constructor for UrlEncoderStringLookup should be private instead of package-private.
+ Javadoc of org.apache.commons.text.lookup.DefaultStringLookup.XML is incorrect.
+ Update DoubleFormat to state it is based on Double.toString. #467.
+
+ Set SecureProcessing feature in XmlStringLookup by default.
+ Add StringLookupFactory.xmlStringLookup(Map<String, Boolean>...).
+ Add @FunctionalInterface to FormatFactory.
+ Add RandomStringGenerator.builder().
+ Add XmlEncoderStringLookup/XmlDecoderStringLookup #449.
+ Add StringSubstitutor.toString().
+
+ Bump actions/cache.
+ Bump actions/setup-java.
+ Bump actions/checkout.
+ Bump pmd from 6.49.0 to 6.52.0 #364.
+ Bump commons-rng-simple from 1.4 to 1.5 #370.
+ Bump spotbugs-maven-plugin from 4.7.2.0 to 4.7.3.6 #371, #385.
+ Bump spotbugs from 4.7.2 to 4.7.3 #373.
+ Bump mockito-inline from 4.8.0 to 4.11.0 #380, #389, #396, #400.
+ Bump jmh.version from 1.35 to 1.37 #388.
+ Bump commons-parent from 54 to 64 #392, #401.
+ Bump assertj-core from 3.23.1 to 3.24.2 #405, #410.
+ Bump maven-checkstyle-plugin from 3.2.0 to 3.2.1 #407.
+ Bump commons-io from 2.11.0 to 2.15.0.
+ Bump commons-lang3 from 3.12.0 to 3.13.0.
+
+
+
+ Fix CaseUtils when the input string contains only delimiters
+ Add GraalVM test dependencies to fix test failures with Java 15.
+ Incorrect values for Jaccard similarity with empty strings.
+ StringSubstitutor map constructor throws NPE on 1.9 with null map.
+ JaroWinklerDistance returns the same values as JaroWinklerSimilarity.
+ Correct Javadoc in FileStringLookup.
+ Minor Improvements #192, #196.
+ Use StringUtils.INDEX_NOT_FOUND constant.
+ Remove redundant local variable.
+ Replace lambda with method reference.
+ Simplify statements.
+ Replace statement lambda with expression lambda.
+ Use static class inner class in tests.
+ Simplify assertion.
+ Extract duplicate code.
+ Set void return method.
+ Remove unused exception from TextStringBuilder.readFrom(CharBuffer). This preserves binary compatibility but not source compatibility.
+ StrBuilder.StrBuilderReader.skip(long): Throw an exception when an implicit narrowing conversion in a compound assignment would result in information loss or a numeric error such as an overflows.
+ TextStringBuilder.TextStringBuilderReader.skip(long): Throw an exception when an implicit narrowing conversion in a compound assignment would result in information loss or a numeric error such as an overflows.
+ TextStringBuilder.equals whatever the capacity is #281.
+ A More Efficient Implementation for Calculating Size of Longest Common Subsequence.
+ LookupTranslator returns count of chars consumed, not of codepoints consumed.
+ Use Math.min() call instead of doing it manually. #335.
+ TextStringBuilder: Throw OutOfMemoryError instead of NegativeArraySizeException.
+ TextStringBuilder: Can't grow to sizes up to Integer.MAX_VALUE.
+ Make default string lookups configurable via system property. Remove dns, url, and script lookups from defaults. If these lookups are required for use in StringSubstitutor.createInterpolator(), they must be enabled via system property. See StringLookupFactory for details.
+
+ Add DoubleFormat utility.
+ Document negative limit for WordUtils abbreviate method
+ Speed up LevenshteinDistance with threshold by exiting early
+ Release Notes page hasn't been updated for 1.9 release yet.
+ Add StrBuilder.isNotEmpty().
+
+ Bump actions/setup-java from v1.4.0 to 3 #147, #156, #155, #172, #215, #314.
+ Bump github/codeql-action from 1 to 2 #319.
+ Bump checkstyle from 8.34 to 9.3, #141, #168, #182, #188, #193, #201, #208, #211, #228, #235, #245, #253, #255, #262, #270, #280, #287, #299, #315, #321.
+ Bump spotbugs-maven-plugin from 4.0.0 to 4.7.2.0, #144, #150, #167, #176, #194, #210, #223, #250, #268, #273, #277, #278, #286, #293, #303, #320, #325, #338, #344, #354.
+ Bump spotbugs from 4.1.3 to 4.7.2 #175, 189, #209, #218, #247, #256, #264, #275, #284, #289, #296, #306, #355.
+ Bump mockito-inline from 3.4.4 to 4.8.0, #143, #148, #149, #152, #153, #154, #158, #159, #166, #177, #180, #187, #195, #197, #207, #216, #231, #236, #237, #243, #258, #259, #260, #261, #272, #285, #291, #305, #317, #330, #331, #347, #352.
+ Bump junit-jupiter from 5.6.2 to 5.9.1 #163, #204, #232, #265, #269, #288, #343, #357.
+ Bump assertj-core from 3.16.1 to 3.23.1 #151, #157, #160, #178, #184, #199, #244, #267, #294.
+ Bump commons-io from 2.7 to 2.11.0 #161 #251.
+ Bump commons-parent from 51 to 54 #145, #358.
+ Bump maven-pmd-plugin from 3.13.0 to 3.19.0 #186, #263, #302, #334, #349, #353.
+ Bump pmd from 6.42.0 to 6.46.0.
+ Bump graalvm.version from 20.2.0 to 22.0.0.2 #185, #198, #206, #227, #252, #276, #295, #300.
+ Bump commons.japicmp.version from 0.14.3 to 0.16.0.
+ Bump commons.jacoco.version 0.8.5 to 0.8.8; fixes Java 15 build.
+ Bump maven-checkstyle-plugin from 3.1.1 to 3.2.0 #202, #348.
+ Bump commons-lang3 3.11 -> 3.12.0.
+ Bump commons.javadoc.version from 3.2.0 to 3.4.1.
+ Bump commons.project-info.version from 3.1.0 to 3.1.2.
+ Bump jmh.version from 1.32 to 1.35 #254, #292, #313.
+ Bump commons-rng-simple from 1.3 to 1.4 #266.
+ Bump taglist-maven-plugin from 2.4 to 3.0.0 #297.
+ Bump commons.pmd-impl.version from 6.44.0 to 6.49.0 #323, #336, #345, #350.
+ Bump exec-maven-plugin from 3.0.0 to 3.1.0 #340.
+
+
+ Removed non-existing parameter from Javadocs and spelled out parameters in throws.
+ StringEscapeUtils.unescapeCsv doesn't remove quotes at begin and end of string.
+ ScriptStringLookup does not accept ":" #126.
+ StringSubstitutor incorrectly removes some escape characters.
+ Fix Javadocs #135.
+ Fix typos #137.
+ Make ConstantStringLookup.constantCache final #136.
+ Simplify if in CaseUtils #134.
+ [javadoc] Fix compiler warnings in Java code example in Javadoc #124.
+ Update from Apache Commons Lang 3.9 to 3.11.
+ Add StringMatcher.size().
+ Refactor TextStringBuilder.readFrom(Readable), extracting readFrom(CharBuffer) and readFrom(Reader).
+ Add BiStringLookup and implementation BiFunctionStringLookup.
+ Add org.apache.commons.text.StringSubstitutor.StringSubstitutor(StringSubstitutor).
+ Add org.apache.commons.text.TextStringBuilder.TextStringBuilder(CharSequence).
+ Add org.apache.commons.text.TextStringBuilder.drainChar(int).
+ Add org.apache.commons.text.TextStringBuilder.drainChars(int, int, char[]. int).
+ Add org.apache.commons.text.TextStringBuilder.isNotEmpty().
+ Add org.apache.commons.text.TextStringBuilder.isReallocated().
+ Add org.apache.commons.text.TextStringBuilder.readFrom(Reader, int).
+ Add org.apache.commons.text.TextStringBuilder.set(String).
+ Add org.apache.commons.text.TextStringBuilder.wrap(char[]).
+ Add org.apache.commons.text.TextStringBuilder.wrap(char[], int).
+ Add org.apache.commons.text.io.StringSubstitutorReader.
+ Add org.apache.commons.text.lookup.StringLookupFactory.functionStringLookup(Function<String, V>).
+ Add org.apache.commons.text.matcher.StringMatcher.isMatch(CharSequence, int).
+ Add org.apache.commons.text.matcher.StringMatcher.isMatch(CharSequence, int, int, int).
+ Add org.apache.commons.text.matcher.StringMatcherFactory.andMatcher(StringMatcher...).
+ Add org.apache.commons.text.matcher.StringMatcherFactory.stringMatcher(char...).
+ [build] Skip clirr since we use JApiCmp.
+ [test] junit-jupiter 5.5.1 -> 5.5.2.
+ [test] org.assertj:assertj-core 3.13.2 -> 3.16.1.
+ [build] com.puppycrawl.tools:checkstyle 8.23 -> 8.34.
+ [build] Update JUnit from 5.5.2 to 5.6.2.
+ [build] commons.jacoco.version 0.8.4 -> 0.8.5.
+ [build] commons.javadoc.version 3.1.1 -> 3.2.0.
+ [build] commons.japicmp.version 0.14.1 -> 0.14.3.
+ [build] checkstyle.plugin.version 3.1.0 -> 3.1.1.
+ [build] checkstyle.version 8.27 -> 8.33.
+ [build] org.apache.commons:commons-parent 48 -> 51.
+ [build] maven-pmd-plugin 3.12.0 -> 3.13.0.
+ [build] org.mockito 3.3.3 -> 3.4.4.
+
+
+ commons-text web page missing "RELEASE-NOTES-1.7.txt"
+ (doc) Fixed wrong value for Jaro-Winkler example #117
+ Add helper factory method org.apache.commons.text.StringSubstitutor.createInterpolator().
+ Add String lookup for host names and IP addresses (DnsStringLookup).
+ StringLookupFactory.addDefaultStringLookups(Map) does not convert keys to lower case.
+ Expand Javadoc for StringSubstitutor and friends.
+ [site] checkstyle.version 8.21 -> 8.23.
+
+
+ WordUtils.wrap must calculate offset increment from wrapOn pattern length
+ Jaro Winkler Distance refers to similarity
+ Add an enum to the lookup package that lists all StringLookups
+ Add a toggle to throw an exception when a variable is unknown in StringSubstitutor
+ TextStringBuilder append sub-sequence not consistent with Appendable.
+ Fix possible infinite loop in WordUtils.wrap for a regex pattern that would trigger on a match of 0 length
+ Make prefixSet in LookupTranslator a BitSet
+ Fix the RegexTokenizer to use a static Pattern
+ Remove rounding from JaccardDistance and JaccardSimilarity
+ Fix the JaroWinklerSimilarity to use StringUtils.equals to test for CharSequence equality
+ Add a generic IntersectionSimilarity measure
+ Update Apache Commons Lang from 3.8.1 to 3.9.
+ ResourceBundleStringLookup.lookup(String) throws MissingResourceException instead of returning null.
+ Update tests from org.assertj:assertj-core 3.12.1 to 3.12.2.
+ Update site from com.puppycrawl.tools:checkstyle 8.18 to 8.21.
+
+
+ Add the resource string bundle string lookup to the default set of lookups
+ Add StringLookupFactory methods for the URL encoder and decoder string lookups
+ org.apache.commons.text.lookup.StringLookupFactory.interpolatorStringLookup() should reuse a singleton instance
+ Add a Base64 encoder string lookup.
+
+
+ Improve JaccardSimilarity computational cost
+ JSON escaping incorrect for the delete control character
+ Fixes JaroWinklerDistance: Wrong results due to precision of transpositions
+ JaroWinklerDistance: Calculation deviates from definition
+ Update Apache Commons Lang from 3.7 to 3.8.1
+ Add a XML file XPath string lookup.
+ Add a Properties file string lookup.
+ Add a script string lookup.
+ Add a file string lookup.
+ Add a URL string lookup.
+ Add a Base64 string lookup.
+ Add org.apache.commons.text.lookup.StringLookupFactory.resourceBundleStringLookup(String).
+ Add URL encoder and decoder string lookups.
+ Add constant string lookup like the one in Apache Commons Configuration.
+
+
+ StringEscapeUtils#unescapeJson does not unescape double quotes and forward slash
+ Remove mention of SQL escaping from user guide
+ Update Java requirement from version 7 to 8.
+ Allow full customization with new API org.apache.commons.text.lookup.StringLookupFactory.interpolatorStringLookup(Map<String, StringLookup>, StringLookup, boolean).
+ WordUtils.wrap throws StringIndexOutOfBoundsException when wrapLength is Integer.MAX_VALUE.
+
+
+ Add Automatic-Module-Name MANIFEST entry for Java 9 compatibility
+ Build failure with java 9-ea+159
+ Add an interpolator string lookup: StringLookupFactory#interpolatorStringLookup()
+ Add a StrSubstitutor replacement based on interfaces: StringSubstitutor
+ Add a StrBuilder replacement based on the StringMatcher interface: TextStringBuilder
+ Add a StrTokenizer replacement based on the StringMatcher interface: StringTokenizer
+ Add a local host string lookup: LocalHostStringLookup
+ StrLookup API confusing
+
+
+ Upversion commons-lang to 3.7
+ Exception thrown in ExtendedMessageFormat using quotes with custom registry
+ StringEscapeUtils#UnEscapeJson doesn't recognize escape signs correctly
+ StrSubstitutor: Ability to turn off substitution in values
+ RandomStringGenerator able to pass multiple ranges to .withinRange()
+ Deprecate isDelimiter and use HashSets for delimiter checks
+ WordUtils.initials support for UTF-16 surrogate pairs
+ WordUtils should treat an empty delimiter array as no delimiters
+ Update RandomStringGenerator to accept a list of valid characters
+ Add CharacterPredicates for ASCII letters (uppercase/lowercase) and arabic numerals
+ Added CaseUtils class with camel case conversion support
+ RandomStringGenerator should be able to generate a String with a random length
+ Update commons-lang dependency to version 3.6
+ Document that commons-csv should be used in preference to CsvTranslators
+ NumericEntityUnescaper.options - fix TODO
+ RandomStringGenerator claims to be immutable, but isn't
+ Add StrLookup.resourceBundleLookup(ResourceBundle)
+ Typo in LongestCommonSubsequence#logestCommonSubsequence
+
+
+ WordUtils should use toXxxxCase(int) rather than toXxxxCase(char)
+ WordUtils.abbreviate support
+ Putting WordUtils back in to the codebase
+ Add RandomStringGenerator
+ RandomStringGenerator: allow users to provide source of randomness
+ Correct round issue in Jaro Winkler implementation
+ Similar to LANG-1025, clirr fails site build.
+
+
- Investigate locale issue in ExtendedMessageFormatTest
- Resolve PMD/CMD Violations
- Escape HTML characters only once: revert
- Fixing the 200 checkstyle errors present in 1.0-beta-1
- Mutable fields should be private
-
-
-
- Incorporate suggestions from RC2 into 1.0 release
- Naming packages org.apache.commons.text.beta
- Upgrading Jacoco for Java 9-ea compatibility.
- Refactor EntityArrays to have unmodifiableMaps in leu of String[][]
- Prepare site for 1.0 release
- Move CvsTranslators out of StringEscapeUtils and make them DRY
- Remove WordUtils to be added back in an upcoming 1.X release
- Possible attacks through StringEscapeUtils.escapeEcmaScrip better javadoc
- Remove RandomStringGenerator to be added back in the 1.1 release
- Upgrade from commons-parent version 41 to version 42
- Escape HTML characters only once
- Global vs local source of randomness
- Fluent API in "RandomStringBuilder"
- Fix JaroWinklerDistance in the manner of LUCENE-1297
- Add LCS similarity and distance
- Add class to generate random strings
- Unfinished class Javadoc for CosineDistance
- Consolidating since tags at 1.0, removing deprecated methods
- Add a builder to StringEscapeUtils
- Add shell/XSI escape/unescape support
- LevenshteinDistance reduce memory consumption
- Remove org.apache.commons.text.names, for later release than 1.0
- Add Jaccard Index and Jaccard Distance
- Move org.apache.commons.lang3.StringEscapeUtils.java into text
- Moving from commons-lang, the package org.apache.commons.lang3.text
- A more complex Levenshtein distance
- Add coveralls and Travis.ci integration
- Add alphabet converter
- Create Commons Text logo
- Improve HumanNameParser
- IP clearance for the names package
- Write user guide
- Work on the string metric, distance, and similarity definitions for the project
- Human name parser
- Create StringDistanceFrom class that contains a StringMetric and the "left" side string. This would have a method that accepts the "right" side string to test.
- Add Cosine Similarity and Cosine Distance
- Change (R) StringMetric.compare(CS left, CS right) to "apply" so that it is consistent with BiFunction.
- Allow extra information (e.g. Levenshtein threshold) to be stored as (final) fields in the StringMetric instance.
- Port Myers algorithm from [collections]
- Add Hamming distance
- Incorporate String algorithms from Commons Lang
-
-
+ Investigate locale issue in ExtendedMessageFormatTest
+ Resolve PMD/CMD Violations
+ Escape HTML characters only once: revert
+ Fixing the 200 checkstyle errors present in 1.0-beta-1
+ Mutable fields should be private
+
+
+ Incorporate suggestions from RC2 into 1.0 release
+ Naming packages org.apache.commons.text.beta
+ Upgrading Jacoco for Java 9-ea compatibility.
+ Refactor EntityArrays to have unmodifiableMaps in leu of String[][]
+ Prepare site for 1.0 release
+ Move CvsTranslators out of StringEscapeUtils and make them DRY
+ Remove WordUtils to be added back in an upcoming 1.X release
+ Possible attacks through StringEscapeUtils.escapeEcmaScrip better javadoc
+ Remove RandomStringGenerator to be added back in the 1.1 release
+ Upgrade from commons-parent version 41 to version 42
+ Escape HTML characters only once
+ Global vs local source of randomness
+ Fluent API in "RandomStringBuilder"
+ Fix JaroWinklerDistance in the manner of LUCENE-1297
+ Add LCS similarity and distance
+ Add class to generate random strings
+ Unfinished class Javadoc for CosineDistance
+ Consolidating since tags at 1.0, removing deprecated methods
+ Add a builder to StringEscapeUtils
+ Add shell/XSI escape/unescape support
+ LevenshteinDistance reduce memory consumption
+ Remove org.apache.commons.text.names, for later release than 1.0
+ Add Jaccard Index and Jaccard Distance
+ Move org.apache.commons.lang3.StringEscapeUtils.java into text
+ Moving from commons-lang, the package org.apache.commons.lang3.text
+ A more complex Levenshtein distance
+ Add coveralls and Travis.ci integration
+ Add alphabet converter
+ Create Commons Text logo
+ Improve HumanNameParser
+ IP clearance for the names package
+ Write user guide
+ Work on the string metric, distance, and similarity definitions for the project
+ Human name parser
+ Create StringDistanceFrom class that contains a StringMetric and the "left" side string. This would have a method that accepts the "right" side string to test.
+ Add Cosine Similarity and Cosine Distance
+ Change (R) StringMetric.compare(CS left, CS right) to "apply" so that it is consistent with BiFunction.
+ Allow extra information (e.g. Levenshtein threshold) to be stored as (final) fields in the StringMetric instance.
+ Port Myers algorithm from [collections]
+ Add Hamming distance
+ Incorporate String algorithms from Commons Lang
+
diff --git a/src/changes/release-notes.vm b/src/changes/release-notes.vm
index c9f6686a7e..35e7a381b8 100644
--- a/src/changes/release-notes.vm
+++ b/src/changes/release-notes.vm
@@ -32,7 +32,7 @@ See the License for the specific language governing permissions and
limitations under the License.
${project.name} ${version} Release Notes
-------------------------------------------------
+----------------------------------------
The ${developmentTeam} is pleased to announce the release of ${project.name} ${version}.
diff --git a/src/conf/checkstyle.xml b/src/conf/checkstyle.xml
index 7ae6627aff..0158804daa 100644
--- a/src/conf/checkstyle.xml
+++ b/src/conf/checkstyle.xml
@@ -85,6 +85,7 @@
+
diff --git a/src/conf/security/README.md b/src/conf/security/README.md
new file mode 100644
index 0000000000..4ac566bc6a
--- /dev/null
+++ b/src/conf/security/README.md
@@ -0,0 +1,61 @@
+
+
+# CycloneDX Documents for Apache Commons Text
+
+The Apache Commons Text project publishes multiple [CycloneDX](https://cyclonedx.org/) documents to help consumers assess the security of their applications using this library:
+
+## SBOM (Software Bill of Materials)
+
+Beginning with version `6.6.0`, Apache Commons Text publishes SBOMs in both **XML** and **JSON** formats to Maven Central. These documents describe all components and dependencies of the library, following standard Maven coordinates:
+
+* **Group ID:** `org.apache.commons`
+* **Artifact ID:** `commons-text`
+* **Classifier:** `cyclonedx`
+* **Type:** `xml` or `json`
+
+Each SBOM lists the library’s required and optional dependencies, helping consumers analyze the software supply chain and manage dependency risk.
+
+> [!NOTE]
+> The versions listed in the SBOM reflect the dependencies used during the build and test process for that specific release of Text.
+> Your own project may use different versions depending on your dependency management configuration.
+
+## VEX (Vulnerability Exploitability eXchange)
+
+An experimental [VEX](https://cyclonedx.org/capabilities/vex/) document is also published:
+
+👉 [`https://raw.githubusercontent.com/apache/commons-text/refs/heads/master/src/conf/security/VEX.cyclonedx.xml`](VEX.cyclonedx.xml)
+
+This document provides information about the **exploitability of known vulnerabilities** in the **dependencies** of Apache Commons Text.
+
+### When is a dependency vulnerability exploitable?
+
+Because Apache Commons libraries (including Text) do **not** bundle their dependencies, a vulnerability in a dependency is only exploitable if **both** of the following conditions are true:
+
+1. The vulnerable dependency is included in the consuming project.
+2. Apache Commons Text is explicitly listed as affected by the vulnerability.
+
+### Notes and Limitations
+
+* This VEX document is **experimental** and provided **as-is**.
+ The semantics of this document may change in the future.
+* The **absence** of a vulnerability entry does **not** indicate that Text is unaffected.
+* If a version of Text is not listed under the `affects` section of a vulnerability, that version may still be affected or not.
+* Only the **latest major version** of Text is currently assessed for vulnerabilities.
+* The `analysis` field in the VEX file uses **Markdown** formatting.
+
+For more information about CycloneDX, SBOMs, or VEX, visit [cyclonedx.org](https://cyclonedx.org/).
diff --git a/src/conf/security/VEX.cyclonedx.xml b/src/conf/security/VEX.cyclonedx.xml
new file mode 100644
index 0000000000..a347293699
--- /dev/null
+++ b/src/conf/security/VEX.cyclonedx.xml
@@ -0,0 +1,124 @@
+
+
+
+
+
+
+ 2025-08-04T11:45:36Z
+
+ org.apache.commons
+ commons-text
+ cpe:2.3:a:apache:commons_text:*:*:*:*:*:*:*:*
+ pkg:maven/org.apache.commons/commons-text?type=jar
+
+
+ The Apache Software Foundation
+ https://commons.apache.org
+
+ Apache Commons PMC
+ dev@commons.apache.org
+
+
+ Apache Commons Security Team
+ security@commons.apache.org
+
+
+
+
+
+
+ CVE-2025-48924
+
+
+ GHSA-j288-q9x7-2f5v
+
+ https://github.com/advisories/GHSA-j288-q9x7-2f5v
+
+
+
+
+ exploitable
+
+ update
+
+
+ CVE-2025-48924 is exploitable in Apache Commons Text versions 1.5 and later, but only when all the following conditions are met:
+
+ * The consuming project includes a vulnerable version of Commons Lang on the classpath.
+ As of version `1.14.1`, Commons Text no longer references a vulnerable version of the `commons-lang3` library in its POM file.
+ * Unvalidated or unsanitized user input is passed to the `StringSubstitutor` or `StringLookup` classes.
+ * An interpolator lookup created via `StringLookupFactory.interpolatorLookup()` is used.
+
+ If these conditions are satisfied, an attacker may cause an infinite loop by submitting a specially crafted input such as `${const:...}`.
+
+ 2025-07-29T12:26:42Z
+ 2025-07-29T12:26:42Z
+
+
+
+ main_component
+
+
+
+ affected
+
+
+
+
+
+
+
+
+
+
+
+ Apache Commons PMC
+ dev@commons.apache.org
+
+
+ 2025-07-29T12:26:42Z
+
+ This document provides information about the **exploitability of known vulnerabilities** in the **dependencies** of Apache Commons Text.
+
+ # When is a dependency vulnerability exploitable?
+
+ Because Apache Commons libraries do **not** bundle their dependencies, a vulnerability in a dependency is only exploitable if **both** of the following conditions are true:
+
+ 1. The vulnerable dependency is included in the consuming project.
+ 2. Apache Commons Text is explicitly listed as affected by the vulnerability.
+
+ # Notes and Limitations
+
+ * This VEX document is **experimental** and provided **as-is**.
+ The semantics of this document may change in the future.
+ * The **absence** of a vulnerability entry does **not** indicate that Text is unaffected.
+ * If a version of Text is not listed under the `affects` section of a vulnerability, that version may still be affected or not.
+ * Only the **latest major version** of Text is currently assessed for vulnerabilities.
+ * The `analysis` field in the VEX file uses **Markdown** formatting.
+
+
+
+
diff --git a/src/conf/spotbugs-exclude-filter.xml b/src/conf/spotbugs-exclude-filter.xml
index 2656019b49..c2b01f6b36 100644
--- a/src/conf/spotbugs-exclude-filter.xml
+++ b/src/conf/spotbugs-exclude-filter.xml
@@ -19,38 +19,39 @@
xmlns="https://github.com/spotbugs/filter/3.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://github.com/spotbugs/filter/3.0.0 https://raw.githubusercontent.com/spotbugs/spotbugs/3.1.0/spotbugs/etc/findbugsfilter.xsd">
-
-
+
+
+
+
+
+
+
-
-
-
-
@@ -62,14 +63,20 @@
-
+
-
-
+
+
-
+
+
+
+
+
+
+
diff --git a/src/main/java/org/apache/commons/text/AlphabetConverter.java b/src/main/java/org/apache/commons/text/AlphabetConverter.java
index acbb05b798..3864ac6a7f 100644
--- a/src/main/java/org/apache/commons/text/AlphabetConverter.java
+++ b/src/main/java/org/apache/commons/text/AlphabetConverter.java
@@ -82,8 +82,8 @@ public final class AlphabetConverter {
/**
* Creates new String that contains just the given code point.
*
- * @param i code point
- * @return a new string with the new code point
+ * @param i code point.
+ * @return a new string with the new code point.
* @see "http://www.oracle.com/us/technologies/java/supplementary-142654.html"
*/
private static String codePointToString(final int i) {
@@ -96,8 +96,8 @@ private static String codePointToString(final int i) {
/**
* Converts characters to integers.
*
- * @param chars array of characters
- * @return an equivalent array of integers
+ * @param chars array of characters.
+ * @return an equivalent array of integers.
*/
private static Integer[] convertCharsToIntegers(final Character[] chars) {
if (ArrayUtils.isEmpty(chars)) {
@@ -109,22 +109,19 @@ private static Integer[] convertCharsToIntegers(final Character[] chars) {
}
/**
- * Creates an alphabet converter, for converting from the original alphabet,
- * to the encoded alphabet, while leaving
- * the characters in doNotEncode as they are (if possible).
+ * Creates an alphabet converter, for converting from the original alphabet, to the encoded alphabet, while leaving the characters in doNotEncode
+ * as they are (if possible).
*
- *
Duplicate letters in either original or encoding will be ignored.
+ *
+ * Duplicate letters in either original or encoding will be ignored.
+ *
*
- * @param original an array of ints representing the original alphabet in
- * code points
- * @param encoding an array of ints representing the alphabet to be used for
- * encoding, in code points
- * @param doNotEncode an array of ints representing the chars to be encoded
- * using the original alphabet - every char
- * here must appear in both the previous params
- * @return The AlphabetConverter
- * @throws IllegalArgumentException if an AlphabetConverter cannot be
- * constructed
+ * @param original an array of ints representing the original alphabet in code points.
+ * @param encoding an array of ints representing the alphabet to be used for encoding, in code points.
+ * @param doNotEncode an array of ints representing the chars to be encoded using the original alphabet - every char here must appear in both the previous
+ * params.
+ * @return The AlphabetConverter.
+ * @throws IllegalArgumentException if an AlphabetConverter cannot be constructed.
*/
public static AlphabetConverter createConverter(
final Integer[] original,
@@ -242,7 +239,7 @@ public static AlphabetConverter createConverterFromChars(
final Character[] original,
final Character[] encoding,
final Character[] doNotEncode) {
- return AlphabetConverter.createConverter(
+ return createConverter(
convertCharsToIntegers(original),
convertCharsToIntegers(encoding),
convertCharsToIntegers(doNotEncode));
@@ -251,8 +248,8 @@ public static AlphabetConverter createConverterFromChars(
/**
* Creates a new converter from a map.
*
- * @param originalToEncoded a map returned from getOriginalToEncoded()
- * @return The reconstructed AlphabetConverter
+ * @param originalToEncoded a map returned from getOriginalToEncoded().
+ * @return The reconstructed AlphabetConverter.
* @see AlphabetConverter#getOriginalToEncoded()
*/
public static AlphabetConverter createConverterFromMap(final Map originalToEncoded) {
@@ -290,9 +287,9 @@ public static AlphabetConverter createConverterFromMap(final Map originalToEncoded,
final Map encodedToOriginal,
@@ -306,11 +303,11 @@ private AlphabetConverter(final Map originalToEncoded,
/**
* Recursive method used when creating encoder/decoder.
*
- * @param level at which point it should add a single encoding
- * @param currentEncoding current encoding
- * @param encoding letters encoding
- * @param originals original values
- * @param doNotEncodeMap map of values that should not be encoded
+ * @param level at which point it should add a single encoding.
+ * @param currentEncoding current encoding.
+ * @param encoding letters encoding.
+ * @param originals original values.
+ * @param doNotEncodeMap map of values that should not be encoded.
*/
private void addSingleEncoding(final int level,
final String currentEncoding,
@@ -363,11 +360,9 @@ private void addSingleEncoding(final int level,
/**
* Decodes a given string.
*
- * @param encoded a string that has been encoded using this
- * AlphabetConverter
- * @return The decoded string, {@code null} if the given string is null
- * @throws UnsupportedEncodingException if unexpected characters that
- * cannot be handled are encountered
+ * @param encoded a string that has been encoded using this AlphabetConverter.
+ * @return The decoded string, {@code null} if the given string is null.
+ * @throws UnsupportedEncodingException if unexpected characters that cannot be handled are encountered.
*/
public String decode(final String encoded)
throws UnsupportedEncodingException {
@@ -409,10 +404,9 @@ public String decode(final String encoded)
/**
* Encodes a given string.
*
- * @param original the string to be encoded
- * @return The encoded string, {@code null} if the given string is null
- * @throws UnsupportedEncodingException if chars that are not supported are
- * encountered
+ * @param original the string to be encoded.
+ * @return The encoded string, {@code null} if the given string is null.
+ * @throws UnsupportedEncodingException if chars that are not supported are encountered.
*/
public String encode(final String original)
throws UnsupportedEncodingException {
@@ -462,22 +456,18 @@ public boolean equals(final Object obj) {
}
/**
- * Gets the length of characters in the encoded alphabet that are necessary
- * for each character in the original
- * alphabet.
+ * Gets the length of characters in the encoded alphabet that are necessary for each character in the original alphabet.
*
- * @return The length of the encoded char
+ * @return The length of the encoded char.
*/
public int getEncodedCharLength() {
return encodedLetterLength;
}
/**
- * Gets the mapping from integer code point of source language to encoded
- * string. Use to reconstruct converter from
- * serialized map.
+ * Gets the mapping from integer code point of source language to encoded string. Use to reconstruct converter from serialized map.
*
- * @return The original map
+ * @return The original map.
*/
public Map getOriginalToEncoded() {
return Collections.unmodifiableMap(originalToEncoded);
diff --git a/src/main/java/org/apache/commons/text/Builder.java b/src/main/java/org/apache/commons/text/Builder.java
index 30063d1809..c0405b9a85 100644
--- a/src/main/java/org/apache/commons/text/Builder.java
+++ b/src/main/java/org/apache/commons/text/Builder.java
@@ -80,7 +80,7 @@
* @param the type of object that the builder will construct or compute.
* @since 1.0
* @see Supplier
- * @deprecated Use :@link Supplier}.
+ * @deprecated Use {@link Supplier}.
*/
@Deprecated
public interface Builder extends Supplier {
diff --git a/src/main/java/org/apache/commons/text/CharacterPredicate.java b/src/main/java/org/apache/commons/text/CharacterPredicate.java
index 0ec2c1fc94..93f6e35627 100644
--- a/src/main/java/org/apache/commons/text/CharacterPredicate.java
+++ b/src/main/java/org/apache/commons/text/CharacterPredicate.java
@@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.commons.text;
/**
- * A predicate for selecting code points. Implementations of this interface must
- * be thread safe.
+ * A predicate for selecting code points. Implementations of this interface must be thread safe.
*
* @since 1.0
*/
@@ -27,10 +27,8 @@ public interface CharacterPredicate {
/**
* Tests the code point with this predicate.
*
- * @param codePoint
- * the code point to test
- * @return {@code true} if the code point matches the predicate,
- * {@code false} otherwise
+ * @param codePoint the code point to test.
+ * @return {@code true} if the code point matches the predicate, {@code false} otherwise.
* @since 1.0
*/
boolean test(int codePoint);
diff --git a/src/main/java/org/apache/commons/text/CompositeFormat.java b/src/main/java/org/apache/commons/text/CompositeFormat.java
index 2918b205df..0072b23c98 100644
--- a/src/main/java/org/apache/commons/text/CompositeFormat.java
+++ b/src/main/java/org/apache/commons/text/CompositeFormat.java
@@ -47,8 +47,8 @@ public class CompositeFormat extends Format {
* Constructs a format that points its parseObject method to one implementation
* and its format method to another.
*
- * @param parser implementation
- * @param formatter implementation
+ * @param parser implementation.
+ * @param formatter implementation.
*/
public CompositeFormat(final Format parser, final Format formatter) {
this.parser = parser;
@@ -58,10 +58,10 @@ public CompositeFormat(final Format parser, final Format formatter) {
/**
* Formats the input.
*
- * @param obj the object to format
- * @param toAppendTo the {@link StringBuffer} to append to
- * @param pos the FieldPosition to use (or ignore).
- * @return {@code toAppendTo}
+ * @param obj the object to format.
+ * @param toAppendTo the {@link StringBuffer} to append to.
+ * @param pos the FieldPosition to use (or ignore).
+ * @return {@code toAppendTo}.
* @see Format#format(Object, StringBuffer, FieldPosition)
*/
@Override // Therefore has to use StringBuffer
@@ -91,11 +91,9 @@ public Format getParser() {
/**
* Parses the input.
*
- * @param source the String source
- * @param pos the ParsePosition containing the position to parse from, will
- * be updated according to parsing success (index) or failure
- * (error index)
- * @return The parsed Object
+ * @param source the String source.
+ * @param pos the ParsePosition containing the position to parse from, will be updated according to parsing success (index) or failure (error index).
+ * @return The parsed Object.
* @see Format#parseObject(String, ParsePosition)
*/
@Override
@@ -106,9 +104,9 @@ public Object parseObject(final String source, final ParsePosition pos) {
/**
* Parses and then reformats a String.
*
- * @param input String to reformat
- * @return A reformatted String
- * @throws ParseException thrown by parseObject(String) call
+ * @param input String to reformat.
+ * @return A reformatted String.
+ * @throws ParseException thrown by parseObject(String) call.
*/
public String reformat(final String input) throws ParseException {
return format(parseObject(input));
diff --git a/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java b/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java
index 56cdc4a7f6..4dcd957fe5 100644
--- a/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java
+++ b/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java
@@ -33,15 +33,20 @@
/**
* Extends {@link java.text.MessageFormat} to allow pluggable/additional formatting
- * options for embedded format elements. Client code should specify a registry
+ * options for embedded format elements.
+ *
+ * Client code should specify a registry
* of {@code FormatFactory} instances associated with {@code String}
* format names. This registry will be consulted when the format elements are
* parsed from the message pattern. In this way custom patterns can be specified,
* and the formats supported by {@link java.text.MessageFormat} can be overridden
* at the format and/or format style level (see MessageFormat). A "format element"
- * embedded in the message pattern is specified (()? signifies optionality):
+ * embedded in the message pattern is specified (()? signifies optionality):
+ *
* format-name and format-style values are trimmed of surrounding whitespace
@@ -75,15 +80,10 @@ public class ExtendedMessageFormat extends MessageFormat {
*/
private static final long serialVersionUID = -2362048321261811743L;
- /**
- * Our initial seed value for calculating hashes.
- */
- private static final int HASH_SEED = 31;
-
/**
* The empty string.
*/
- private static final String DUMMY_PATTERN = StringUtils.EMPTY;
+ private static final String EMPTY_PATTERN = StringUtils.EMPTY;
/**
* A comma.
@@ -91,12 +91,12 @@ public class ExtendedMessageFormat extends MessageFormat {
private static final char START_FMT = ',';
/**
- * A right side squiggly brace.
+ * A right curly bracket.
*/
private static final char END_FE = '}';
/**
- * A left side squiggly brace.
+ * A left curly bracket.
*/
private static final char START_FE = '{';
@@ -118,7 +118,7 @@ public class ExtendedMessageFormat extends MessageFormat {
/**
* Constructs a new ExtendedMessageFormat for the default locale.
*
- * @param pattern the pattern to use, not null
+ * @param pattern the pattern to use, not null.
* @throws IllegalArgumentException in case of a bad pattern.
*/
public ExtendedMessageFormat(final String pattern) {
@@ -128,8 +128,8 @@ public ExtendedMessageFormat(final String pattern) {
/**
* Constructs a new ExtendedMessageFormat.
*
- * @param pattern the pattern to use, not null
- * @param locale the locale to use, not null
+ * @param pattern the pattern to use, not null.
+ * @param locale the locale to use, not null.
* @throws IllegalArgumentException in case of a bad pattern.
*/
public ExtendedMessageFormat(final String pattern, final Locale locale) {
@@ -139,53 +139,43 @@ public ExtendedMessageFormat(final String pattern, final Locale locale) {
/**
* Constructs a new ExtendedMessageFormat.
*
- * @param pattern the pattern to use, not null
- * @param locale the locale to use, not null
- * @param registry the registry of format factories, may be null
+ * @param pattern the pattern to use, not null.
+ * @param locale the locale to use, not null.
+ * @param registry the registry of format factories, may be null.
* @throws IllegalArgumentException in case of a bad pattern.
*/
- public ExtendedMessageFormat(final String pattern,
- final Locale locale,
- final Map registry) {
- super(DUMMY_PATTERN);
+ public ExtendedMessageFormat(final String pattern, final Locale locale, final Map registry) {
+ super(EMPTY_PATTERN);
setLocale(locale);
- this.registry = registry != null
- ? Collections.unmodifiableMap(new HashMap<>(registry))
- : null;
+ this.registry = registry != null ? Collections.unmodifiableMap(new HashMap<>(registry)) : null;
applyPattern(pattern);
}
/**
* Constructs a new ExtendedMessageFormat for the default locale.
*
- * @param pattern the pattern to use, not null
- * @param registry the registry of format factories, may be null
+ * @param pattern the pattern to use, not null.
+ * @param registry the registry of format factories, may be null.
* @throws IllegalArgumentException in case of a bad pattern.
*/
- public ExtendedMessageFormat(final String pattern,
- final Map registry) {
+ public ExtendedMessageFormat(final String pattern, final Map registry) {
this(pattern, Locale.getDefault(Category.FORMAT), registry);
}
/**
- * Consumes a quoted string, adding it to {@code appendTo} if
- * specified.
+ * Consumes a quoted string, adding it to {@code appendTo} if specified.
*
- * @param pattern pattern to parse
- * @param pos current parse position
- * @param appendTo optional StringBuilder to append
+ * @param pattern pattern to parse.
+ * @param pos current parse position.
+ * @param appendTo optional StringBuilder to append.
*/
- private void appendQuotedString(final String pattern, final ParsePosition pos,
- final StringBuilder appendTo) {
- assert pattern.toCharArray()[pos.getIndex()] == QUOTE
- : "Quoted string must start with quote character";
-
+ private void appendQuotedString(final String pattern, final ParsePosition pos, final StringBuilder appendTo) {
+ assert pattern.toCharArray()[pos.getIndex()] == QUOTE : "Quoted string must start with quote character";
// handle quote character at the beginning of the string
if (appendTo != null) {
appendTo.append(QUOTE);
}
next(pos);
-
final int start = pos.getIndex();
final char[] c = pattern.toCharArray();
for (int i = pos.getIndex(); i < pattern.length(); i++) {
@@ -200,14 +190,13 @@ private void appendQuotedString(final String pattern, final ParsePosition pos,
next(pos);
}
}
- throw new IllegalArgumentException(
- "Unterminated quoted string at position " + start);
+ throw new IllegalArgumentException("Unterminated quoted string at position " + start);
}
/**
* Applies the specified pattern.
*
- * @param pattern String
+ * @param pattern String.
*/
@Override
public final void applyPattern(final String pattern) {
@@ -219,7 +208,6 @@ public final void applyPattern(final String pattern) {
final ArrayList foundFormats = new ArrayList<>();
final ArrayList foundDescriptions = new ArrayList<>();
final StringBuilder stripCustom = new StringBuilder(pattern.length());
-
final ParsePosition pos = new ParsePosition(0);
final char[] c = pattern.toCharArray();
int fmtCount = 0;
@@ -238,8 +226,7 @@ public final void applyPattern(final String pattern) {
Format format = null;
String formatDescription = null;
if (c[pos.getIndex()] == START_FMT) {
- formatDescription = parseFormatDescription(pattern,
- next(pos));
+ formatDescription = parseFormatDescription(pattern, next(pos));
format = getFormat(formatDescription);
if (format == null) {
stripCustom.append(START_FMT).append(formatDescription);
@@ -254,8 +241,7 @@ public final void applyPattern(final String pattern) {
throw new IllegalArgumentException("The validated expression is false");
}
if (c[pos.getIndex()] != END_FE) {
- throw new IllegalArgumentException(
- "Unreadable format element at position " + start);
+ throw new IllegalArgumentException("Unreadable format element at position " + start);
}
//$FALL-THROUGH$
default:
@@ -282,7 +268,8 @@ public final void applyPattern(final String pattern) {
/**
* Tests whether the specified Collection contains non-null elements.
- * @param coll to check
+ *
+ * @param coll to check.
* @return {@code true} if some Object was found, {@code false} otherwise.
*/
private boolean containsElements(final Collection> coll) {
@@ -292,38 +279,26 @@ private boolean containsElements(final Collection> coll) {
return coll.stream().anyMatch(Objects::nonNull);
}
- /**
- * Tests if this extended message format is equal to another object.
- *
- * @param obj the object to compare to
- * @return true if this object equals the other, otherwise false
- */
@Override
public boolean equals(final Object obj) {
- if (obj == this) {
+ if (this == obj) {
return true;
}
- if (obj == null) {
- return false;
- }
- if (!Objects.equals(getClass(), obj.getClass())) {
- return false;
- }
- final ExtendedMessageFormat rhs = (ExtendedMessageFormat) obj;
- if (!Objects.equals(toPattern, rhs.toPattern)) {
+ if (!super.equals(obj)) {
return false;
}
- if (!super.equals(obj)) {
+ if (!(obj instanceof ExtendedMessageFormat)) {
return false;
}
- return Objects.equals(registry, rhs.registry);
+ final ExtendedMessageFormat other = (ExtendedMessageFormat) obj;
+ return Objects.equals(registry, other.registry) && Objects.equals(toPattern, other.toPattern);
}
/**
* Gets a custom format from a format description.
*
- * @param desc String
- * @return Format
+ * @param desc String.
+ * @return Format.
*/
private Format getFormat(final String desc) {
if (registry != null) {
@@ -345,29 +320,26 @@ private Format getFormat(final String desc) {
/**
* Consumes quoted string only.
*
- * @param pattern pattern to parse
- * @param pos current parse position
+ * @param pattern pattern to parse.
+ * @param pos current parse position.
*/
private void getQuotedString(final String pattern, final ParsePosition pos) {
appendQuotedString(pattern, pos, null);
}
- /**
- * {@inheritDoc}
- */
@Override
public int hashCode() {
- int result = super.hashCode();
- result = HASH_SEED * result + Objects.hashCode(registry);
- return HASH_SEED * result + Objects.hashCode(toPattern);
+ final int prime = 31;
+ final int result = super.hashCode();
+ return prime * result + Objects.hash(registry, toPattern);
}
/**
* Inserts formats back into the pattern for toPattern() support.
*
- * @param pattern source
- * @param customPatterns The custom patterns to re-insert, if any
- * @return full pattern
+ * @param pattern source.
+ * @param customPatterns The custom patterns to re-insert, if any.
+ * @return full pattern.
*/
private String insertFormats(final String pattern, final ArrayList customPatterns) {
if (!containsElements(customPatterns)) {
@@ -409,8 +381,8 @@ private String insertFormats(final String pattern, final ArrayList custo
/**
* Advances parse position by 1.
*
- * @param pos ParsePosition
- * @return {@code pos}
+ * @param pos ParsePosition.
+ * @return {@code pos}.
*/
private ParsePosition next(final ParsePosition pos) {
pos.setIndex(pos.getIndex() + 1);
@@ -420,9 +392,9 @@ private ParsePosition next(final ParsePosition pos) {
/**
* Parses the format component of a format element.
*
- * @param pattern string to parse
- * @param pos current parse position
- * @return Format description String
+ * @param pattern string to parse.
+ * @param pos current parse position.
+ * @return Format description String.
*/
private String parseFormatDescription(final String pattern, final ParsePosition pos) {
final int start = pos.getIndex();
@@ -457,9 +429,9 @@ private String parseFormatDescription(final String pattern, final ParsePosition
/**
* Reads the argument index from the current format element.
*
- * @param pattern pattern to parse
- * @param pos current parse position
- * @return argument index
+ * @param pattern pattern to parse.
+ * @param pos current parse position.
+ * @return argument index.
*/
private int readArgumentIndex(final String pattern, final ParsePosition pos) {
final int start = pos.getIndex();
@@ -499,8 +471,8 @@ private int readArgumentIndex(final String pattern, final ParsePosition pos) {
/**
* Consumes whitespace from the current parse position.
*
- * @param pattern String to read
- * @param pos current position
+ * @param pattern String to read.
+ * @param pos current position.
*/
private void seekNonWs(final String pattern, final ParsePosition pos) {
int len = 0;
@@ -512,12 +484,11 @@ private void seekNonWs(final String pattern, final ParsePosition pos) {
}
/**
- * Throws UnsupportedOperationException - see class Javadoc for details.
+ * Throws UnsupportedOperationException, see class Javadoc for details.
*
- * @param formatElementIndex format element index
- * @param newFormat the new format
- * @throws UnsupportedOperationException always thrown since this isn't
- * supported by ExtendMessageFormat
+ * @param formatElementIndex format element index.
+ * @param newFormat the new format.
+ * @throws UnsupportedOperationException always thrown since this isn't supported by {@link ExtendedMessageFormat}.
*/
@Override
public void setFormat(final int formatElementIndex, final Format newFormat) {
@@ -525,12 +496,11 @@ public void setFormat(final int formatElementIndex, final Format newFormat) {
}
/**
- * Throws UnsupportedOperationException - see class Javadoc for details.
+ * Throws UnsupportedOperationException, see class Javadoc for details.
*
- * @param argumentIndex argument index
- * @param newFormat the new format
- * @throws UnsupportedOperationException always thrown since this isn't
- * supported by ExtendMessageFormat
+ * @param argumentIndex argument index.
+ * @param newFormat the new format.
+ * @throws UnsupportedOperationException always thrown since this isn't supported by {@link ExtendedMessageFormat}.
*/
@Override
public void setFormatByArgumentIndex(final int argumentIndex,
@@ -541,9 +511,8 @@ public void setFormatByArgumentIndex(final int argumentIndex,
/**
* Throws UnsupportedOperationException - see class Javadoc for details.
*
- * @param newFormats new formats
- * @throws UnsupportedOperationException always thrown since this isn't
- * supported by ExtendMessageFormat
+ * @param newFormats new formats.
+ * @throws UnsupportedOperationException always thrown since this isn't supported by {@link ExtendedMessageFormat}.
*/
@Override
public void setFormats(final Format[] newFormats) {
@@ -554,8 +523,7 @@ public void setFormats(final Format[] newFormats) {
* Throws UnsupportedOperationException - see class Javadoc for details.
*
* @param newFormats new formats
- * @throws UnsupportedOperationException always thrown since this isn't
- * supported by ExtendMessageFormat
+ * @throws UnsupportedOperationException always thrown since this isn't supported by {@link ExtendedMessageFormat}
*/
@Override
public void setFormatsByArgumentIndex(final Format[] newFormats) {
diff --git a/src/main/java/org/apache/commons/text/FormatFactory.java b/src/main/java/org/apache/commons/text/FormatFactory.java
index 75c48fb0cd..74bb95c0e4 100644
--- a/src/main/java/org/apache/commons/text/FormatFactory.java
+++ b/src/main/java/org/apache/commons/text/FormatFactory.java
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.commons.text;
import java.text.Format;
@@ -30,13 +31,11 @@ public interface FormatFactory {
/**
* Gets or creates a format instance.
*
- * @param name The format type name
- * @param arguments Arguments used to create the format instance. This allows the
- * {@code FormatFactory} to implement the "format style"
- * concept from {@link java.text.MessageFormat}.
- * @param locale The locale, may be null
- * @return The format instance
+ * @param name The format type name.
+ * @param arguments Arguments used to create the format instance. This allows the {@code FormatFactory} to implement the "format style" concept from
+ * {@link java.text.MessageFormat}.
+ * @param locale The locale, may be null.
+ * @return The format instance.
*/
Format getFormat(String name, String arguments, Locale locale);
-
}
diff --git a/src/main/java/org/apache/commons/text/FormattableUtils.java b/src/main/java/org/apache/commons/text/FormattableUtils.java
index 22d9006f60..f0be6ddb8d 100644
--- a/src/main/java/org/apache/commons/text/FormattableUtils.java
+++ b/src/main/java/org/apache/commons/text/FormattableUtils.java
@@ -26,9 +26,10 @@
/**
* Provides utilities for working with the {@code Formattable} interface.
*
- *
The {@link Formattable} interface provides basic control over formatting
- * when using a {@code Formatter}. It is primarily concerned with numeric precision
- * and padding, and is not designed to allow generalized alternate formats.
+ *
+ * The {@link Formattable} interface provides basic control over formatting when using a {@code Formatter}. It is primarily concerned with numeric precision and
+ * padding, and is not designed to allow generalized alternate formats.
+ *
*
* @since 1.0
*/
@@ -40,16 +41,15 @@ public class FormattableUtils {
private static final String SIMPLEST_FORMAT = "%s";
/**
- * Handles the common {@code Formattable} operations of truncate-pad-append,
- * with no ellipsis on precision overflow, and padding width underflow with
+ * Handles the common {@code Formattable} operations of truncate-pad-append, with no ellipsis on precision overflow, and padding width underflow with
* spaces.
*
- * @param seq the string to handle, not null
- * @param formatter the destination formatter, not null
- * @param flags the flags for formatting, see {@code Formattable}
- * @param width the width of the output, see {@code Formattable}
- * @param precision the precision of the output, see {@code Formattable}
- * @return The {@code formatter} instance, not null
+ * @param seq the string to handle, not null.
+ * @param formatter the destination formatter, not null.
+ * @param flags the flags for formatting, see {@code Formattable}.
+ * @param width the width of the output, see {@code Formattable}.
+ * @param precision the precision of the output, see {@code Formattable}.
+ * @return The {@code formatter} instance, not null.
*/
public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
final int precision) {
@@ -57,16 +57,15 @@ public static Formatter append(final CharSequence seq, final Formatter formatter
}
/**
- * Handles the common {@link Formattable} operations of truncate-pad-append,
- * with no ellipsis on precision overflow.
+ * Handles the common {@link Formattable} operations of truncate-pad-append, with no ellipsis on precision overflow.
*
- * @param seq the string to handle, not null
- * @param formatter the destination formatter, not null
- * @param flags the flags for formatting, see {@code Formattable}
- * @param width the width of the output, see {@code Formattable}
- * @param precision the precision of the output, see {@code Formattable}
- * @param padChar the pad character to use
- * @return The {@code formatter} instance, not null
+ * @param seq the string to handle, not null.
+ * @param formatter the destination formatter, not null.
+ * @param flags the flags for formatting, see {@code Formattable}.
+ * @param width the width of the output, see {@code Formattable}.
+ * @param precision the precision of the output, see {@code Formattable}.
+ * @param padChar the pad character to use.
+ * @return The {@code formatter} instance, not null.
*/
public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
final int precision, final char padChar) {
@@ -76,17 +75,15 @@ public static Formatter append(final CharSequence seq, final Formatter formatter
/**
* Handles the common {@link Formattable} operations of truncate-pad-append.
*
- * @param seq the string to handle, not null
- * @param formatter the destination formatter, not null
- * @param flags the flags for formatting, see {@code Formattable}
- * @param width the width of the output, see {@code Formattable}
- * @param precision the precision of the output, see {@code Formattable}
- * @param padChar the pad character to use
- * @param truncateEllipsis the ellipsis to use when precision dictates truncation, null or
- * empty causes a hard truncation
- * @return The {@code formatter} instance, not null
- * @throws IllegalArgumentException if {@code ellipsis.length() > precision},
- * given that {@code ellipsis} is not null and {@code precision >= 0}
+ * @param seq the string to handle, not null.
+ * @param formatter the destination formatter, not null.
+ * @param flags the flags for formatting, see {@code Formattable}.
+ * @param width the width of the output, see {@code Formattable}.
+ * @param precision the precision of the output, see {@code Formattable}.
+ * @param padChar the pad character to use.
+ * @param truncateEllipsis the ellipsis to use when precision dictates truncation, null or empty causes a hard truncation.
+ * @return The {@code formatter} instance, not null.
+ * @throws IllegalArgumentException if {@code ellipsis.length() > precision}, given that {@code ellipsis} is not null and {@code precision >= 0}.
*/
public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
final int precision, final char padChar, final CharSequence truncateEllipsis) {
@@ -115,43 +112,38 @@ public static Formatter append(final CharSequence seq, final Formatter formatter
}
/**
- * Handles the common {@link Formattable} operations of truncate-pad-append,
- * padding width underflow with spaces.
+ * Handles the common {@link Formattable} operations of truncate-pad-append, padding width underflow with spaces.
*
- * @param seq the string to handle, not null
- * @param formatter the destination formatter, not null
- * @param flags the flags for formatting, see {@code Formattable}
- * @param width the width of the output, see {@code Formattable}
- * @param precision the precision of the output, see {@code Formattable}
- * @param ellipsis the ellipsis to use when precision dictates truncation, null or
- * empty causes a hard truncation
+ * @param seq the string to handle, not null.
+ * @param formatter the destination formatter, not null.
+ * @param flags the flags for formatting, see {@code Formattable}.
+ * @param width the width of the output, see {@code Formattable}.
+ * @param precision the precision of the output, see {@code Formattable}.
+ * @param ellipsis the ellipsis to use when precision dictates truncation, null or empty causes a hard truncation..
* @return The {@code formatter} instance, not null
- * @throws IllegalArgumentException if {@code ellipsis.length() > precision},
- * given that {@code ellipsis} is not null and {@code precision >= 0}
+ * @throws IllegalArgumentException if {@code ellipsis.length() > precision}, given that {@code ellipsis} is not null and {@code precision >= 0}.
*/
- public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
- final int precision, final CharSequence ellipsis) {
+ public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width, final int precision,
+ final CharSequence ellipsis) {
return append(seq, formatter, flags, width, precision, ' ', ellipsis);
}
/**
- * Gets the default formatted representation of the specified
- * {@code Formattable}.
+ * Gets the default formatted representation of the specified {@code Formattable}.
*
- * @param formattable the instance to convert to a string, not null
- * @return The resulting string, not null
+ * @param formattable the instance to convert to a string, not null.
+ * @return The resulting string, not null.
*/
public static String toString(final Formattable formattable) {
return String.format(SIMPLEST_FORMAT, formattable);
}
/**
- * {@code FormattableUtils} instances should NOT be constructed in
- * standard programming. Instead, the methods of the class should be invoked
- * statically.
+ * {@code FormattableUtils} instances should NOT be constructed in standard programming. Instead, the methods of the class should be invoked statically.
*
- *
This constructor is public to permit tools that require a JavaBean
- * instance to operate.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance to operate.
+ *
*/
public FormattableUtils() {
}
diff --git a/src/main/java/org/apache/commons/text/RandomStringGenerator.java b/src/main/java/org/apache/commons/text/RandomStringGenerator.java
index 9668a6e2a0..5b17555b73 100644
--- a/src/main/java/org/apache/commons/text/RandomStringGenerator.java
+++ b/src/main/java/org/apache/commons/text/RandomStringGenerator.java
@@ -29,15 +29,12 @@
import org.apache.commons.lang3.Validate;
/**
- * Generates random Unicode strings containing the specified number of code points.
- * Instances are created using a builder class, which allows the
- * callers to define the properties of the generator. See the documentation for the
- * {@link Builder} class to see available properties.
+ * Generates random Unicode strings containing the specified number of code points. Instances are created using a builder class, which allows the callers to
+ * define the properties of the generator. See the documentation for the {@link Builder} class to see available properties.
*
*
* // Generates a 20 code point string, using only the letters a-z
- * RandomStringGenerator generator = RandomStringGenerator.builder()
- * .withinRange('a', 'z').build();
+ * RandomStringGenerator generator = RandomStringGenerator.builder().withinRange('a', 'z').build();
* String randomLetters = generator.generate(20);
*
*
@@ -46,16 +43,15 @@
* // Generates a 20 code point string, using only the letters a-z
* RandomStringGenerator generator = RandomStringGenerator.builder()
* .withinRange('a', 'z')
- * .usingRandom(rng::nextInt) // uses Java 8 syntax
+ * .usingRandom(rng::nextInt)
* .build();
* String randomLetters = generator.generate(20);
*
*
- * {@code RandomStringGenerator} instances are thread-safe when using the
- * default random number generator (RNG). If a custom RNG is set by calling the method
- * {@link Builder#usingRandom(TextRandomProvider) Builder.usingRandom(TextRandomProvider)}, thread-safety
- * must be ensured externally.
+ * {@code RandomStringGenerator} instances are thread-safe when using the default random number generator (RNG). If a custom RNG is set by calling the method
+ * {@link Builder#usingRandom(TextRandomProvider) Builder.usingRandom(TextRandomProvider)}, thread-safety must be ensured externally.
*
+ *
* @since 1.1
*/
public final class RandomStringGenerator {
@@ -63,24 +59,29 @@ public final class RandomStringGenerator {
/**
* A builder for generating {@code RandomStringGenerator} instances.
*
- *
The behavior of a generator is controlled by properties set by this
- * builder. Each property has a default value, which can be overridden by
- * calling the methods defined in this class, prior to calling {@link #build()}.
- *
- *
All the property setting methods return the {@code Builder} instance to allow for method chaining.
- *
- *
The minimum and maximum code point values are defined using {@link #withinRange(int, int)}. The
- * default values are {@code 0} and {@link Character#MAX_CODE_POINT} respectively.
- *
- *
The source of randomness can be set using {@link #usingRandom(TextRandomProvider)},
- * otherwise {@link ThreadLocalRandom} is used.
- *
- *
The type of code points returned can be filtered using {@link #filteredBy(CharacterPredicate...)},
- * which defines a collection of tests that are applied to the randomly generated code points.
- * The code points will only be included in the result if they pass at least one of the tests.
- * Some commonly used predicates are provided by the {@link CharacterPredicates} enum.
+ *
+ * The behavior of a generator is controlled by properties set by this builder. Each property has a default value, which can be overridden by calling the
+ * methods defined in this class, prior to calling {@link #build()}.
+ *
+ *
+ * All the property setting methods return the {@code Builder} instance to allow for method chaining.
+ *
+ *
+ * The minimum and maximum code point values are defined using {@link #withinRange(int, int)}. The default values are {@code 0} and
+ * {@link Character#MAX_CODE_POINT} respectively.
+ *
+ *
+ * The source of randomness can be set using {@link #usingRandom(TextRandomProvider)}, otherwise {@link ThreadLocalRandom} is used.
+ *
+ *
+ * The type of code points returned can be filtered using {@link #filteredBy(CharacterPredicate...)}, which defines a collection of tests that are applied
+ * to the randomly generated code points. The code points will only be included in the result if they pass at least one of the tests. Some commonly used
+ * predicates are provided by the {@link CharacterPredicates} enum.
+ *
+ *
+ * This class is not thread safe.
+ *
*
- *
This class is not thread safe.
* @since 1.1
*/
public static class Builder implements org.apache.commons.text.Builder {
@@ -124,7 +125,12 @@ public static class Builder implements org.apache.commons.text.Builder characterList;
+ private Set characterSet = new HashSet<>();
+
+ /**
+ * Whether calls accumulates the source of provided characters. The default is {@code false}.
+ */
+ private boolean accumulate;
/**
* Creates a new instance.
@@ -146,18 +152,15 @@ public RandomStringGenerator build() {
}
/**
- * Limits the characters in the generated string to those that match at
- * least one of the predicates supplied.
+ * Limits the characters in the generated string to those that match at least one of the predicates supplied.
*
*
- * Passing {@code null} or an empty array to this method will revert to the
- * default behavior of allowing any character. Multiple calls to this
- * method will replace the previously stored predicates.
+ * Passing {@code null} or an empty array to this method will revert to the default behavior of allowing any character. Multiple calls to this method
+ * will replace the previously stored predicates.
*
*
- * @param predicates
- * the predicates, may be {@code null} or empty
- * @return {@code this}, to allow method chaining
+ * @param predicates the predicates, may be {@code null} or empty.
+ * @return {@code this} instance.
*/
public Builder filteredBy(final CharacterPredicate... predicates) {
if (ArrayUtils.isEmpty(predicates)) {
@@ -176,7 +179,7 @@ public Builder filteredBy(final CharacterPredicate... predicates) {
/**
* Builds a new {@code RandomStringGenerator}.
*
- * @return A new {@code RandomStringGenerator}
+ * @return A new {@code RandomStringGenerator}.
* @since 1.12.0
*/
@Override
@@ -184,41 +187,66 @@ public RandomStringGenerator get() {
return new RandomStringGenerator(this);
}
+ private void initCharList() {
+ if (!accumulate) {
+ characterSet = new HashSet<>();
+ }
+ }
+
/**
- * Limits the characters in the generated string to those who match at
- * supplied list of Character.
+ * Limits the characters in the generated string to those who match at supplied list of Character.
*
*
- * Passing {@code null} or an empty array to this method will revert to the
- * default behavior of allowing any character. Multiple calls to this
- * method will replace the previously stored Character.
+ * Passing {@code null} or an empty array to this method will revert to the default behavior of allowing any character. Multiple calls to this method
+ * will replace the previously stored Character.
*
*
- * @param chars set of predefined Characters for random string generation
- * the Character can be, may be {@code null} or empty
- * @return {@code this}, to allow method chaining
+ * @param chars set of predefined Characters for random string generation the Character can be, may be {@code null} or empty.
+ * @return {@code this} instance.
* @since 1.2
*/
public Builder selectFrom(final char... chars) {
- characterList = new ArrayList<>();
+ initCharList();
if (chars != null) {
for (final char c : chars) {
- characterList.add(c);
+ characterSet.add(c);
}
}
return this;
}
/**
- * Overrides the default source of randomness. It is highly
- * recommended that a random number generator library like
- * Apache Commons RNG
- * be used to provide the random number generation.
+ * Sets whether calls accumulates the source of provided characters. The default is {@code false}.
+ *
+ *
+ *
+ * @param accumulate whether calls accumulates the source of provided characters. The default is {@code false}.
+ * @return {@code this} instance.
+ * @since 1.14.0
+ */
+ public Builder setAccumulate(final boolean accumulate) {
+ this.accumulate = accumulate;
+ return this;
+ }
+
+ /**
+ * Overrides the default source of randomness. It is highly recommended that a random number generator library like
+ * Apache Commons RNG be used to provide the random number generation.
*
*
- * {@link TextRandomProvider} is a
- * functional interface and need not be explicitly implemented:
+ * {@link TextRandomProvider} is a functional interface and need not be explicitly implemented:
*
- * Passing {@code null} to this method will revert to the default source of
- * randomness.
+ * Passing {@code null} to this method will revert to the default source of randomness.
*
*
- * @param random
- * the source of randomness, may be {@code null}
- * @return {@code this}, to allow method chaining
+ * @param random the source of randomness, may be {@code null}.
+ * @return {@code this} instance.
* @since 1.14.0
*/
public Builder usingRandom(final IntUnaryOperator random) {
@@ -245,15 +271,13 @@ public Builder usingRandom(final IntUnaryOperator random) {
}
/**
- * Overrides the default source of randomness. It is highly
- * recommended that a random number generator library like
- * Apache Commons RNG
- * be used to provide the random number generation.
+ * Overrides the default source of randomness. It is highly recommended that a random number generator library like
+ * Apache Commons RNG be used to provide the random number generation.
*
*
- * {@link TextRandomProvider} is a
- * functional interface and need not be explicitly implemented:
+ * {@link TextRandomProvider} is a functional interface and need not be explicitly implemented:
*
- * Passing {@code null} to this method will revert to the default source of
- * randomness.
+ * Passing {@code null} to this method will revert to the default source of randomness.
*
*
- * @param random
- * the source of randomness, may be {@code null}
- * @return {@code this}, to allow method chaining
+ * @param random the source of randomness, may be {@code null}.
+ * @return {@code this} instance.
*/
public Builder usingRandom(final TextRandomProvider random) {
this.random = random;
@@ -279,23 +301,23 @@ public Builder usingRandom(final TextRandomProvider random) {
}
/**
- * Sets the array of minimum and maximum char allowed in the
- * generated string.
+ * Sets the array of minimum and maximum char allowed in the generated string.
*
* For example:
+ *
*
*
* @param pairs array of characters array, expected is to pass min, max pairs through this arg.
- * @return {@code this}, to allow method chaining.
+ * @return {@code this} instance.
*/
public Builder withinRange(final char[]... pairs) {
- characterList = new ArrayList<>();
+ initCharList();
if (pairs != null) {
for (final char[] pair : pairs) {
Validate.isTrue(pair.length == 2, "Each pair must contain minimum and maximum code point");
@@ -303,39 +325,30 @@ public Builder withinRange(final char[]... pairs) {
final int maximumCodePoint = pair[1];
Validate.isTrue(minimumCodePoint <= maximumCodePoint, "Minimum code point %d is larger than maximum code point %d", minimumCodePoint,
maximumCodePoint);
-
for (int index = minimumCodePoint; index <= maximumCodePoint; index++) {
- characterList.add((char) index);
+ characterSet.add((char) index);
}
}
}
return this;
-
}
+
/**
- * Sets the minimum and maximum code points allowed in the
- * generated string.
+ * Sets the minimum and maximum code points allowed in the generated string.
*
- * @param minimumCodePoint
- * the smallest code point allowed (inclusive)
- * @param maximumCodePoint
- * the largest code point allowed (inclusive)
- * @return {@code this}, to allow method chaining
- * @throws IllegalArgumentException
- * if {@code maximumCodePoint >}
- * {@link Character#MAX_CODE_POINT}
- * @throws IllegalArgumentException
- * if {@code minimumCodePoint < 0}
- * @throws IllegalArgumentException
- * if {@code minimumCodePoint > maximumCodePoint}
+ * @param minimumCodePoint the smallest code point allowed (inclusive).
+ * @param maximumCodePoint the largest code point allowed (inclusive).
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if {@code maximumCodePoint >} {@link Character#MAX_CODE_POINT}.
+ * @throws IllegalArgumentException if {@code minimumCodePoint < 0}.
+ * @throws IllegalArgumentException if {@code minimumCodePoint > maximumCodePoint}.
*/
public Builder withinRange(final int minimumCodePoint, final int maximumCodePoint) {
- Validate.isTrue(minimumCodePoint <= maximumCodePoint,
- "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
+ Validate.isTrue(minimumCodePoint <= maximumCodePoint, "Minimum code point %d is larger than maximum code point %d", minimumCodePoint,
+ maximumCodePoint);
Validate.isTrue(minimumCodePoint >= 0, "Minimum code point %d is negative", minimumCodePoint);
- Validate.isTrue(maximumCodePoint <= Character.MAX_CODE_POINT,
- "Value %d is larger than Character.MAX_CODE_POINT.", maximumCodePoint);
+ Validate.isTrue(maximumCodePoint <= Character.MAX_CODE_POINT, "Value %d is larger than Character.MAX_CODE_POINT.", maximumCodePoint);
this.minimumCodePoint = minimumCodePoint;
this.maximumCodePoint = maximumCodePoint;
return this;
@@ -344,6 +357,7 @@ public Builder withinRange(final int minimumCodePoint, final int maximumCodePoin
/**
* Constructs a new builder.
+ *
* @return a new builder.
* @since 1.11.0
*/
@@ -379,46 +393,35 @@ public static Builder builder() {
/**
* Constructs the generator.
*
- * @param minimumCodePoint
- * smallest allowed code point (inclusive)
- * @param maximumCodePoint
- * largest allowed code point (inclusive)
- * @param inclusivePredicates
- * filters for code points
- * @param random
- * source of randomness
- * @param characterList list of predefined set of characters.
+ * @param minimumCodePoint smallest allowed code point (inclusive).
+ * @param maximumCodePoint largest allowed code point (inclusive).
+ * @param inclusivePredicates filters for code points.
+ * @param random source of randomness.
+ * @param characterSet list of predefined set of characters.
*/
private RandomStringGenerator(final Builder builder) {
this.minimumCodePoint = builder.minimumCodePoint;
this.maximumCodePoint = builder.maximumCodePoint;
this.inclusivePredicates = builder.inclusivePredicates;
this.random = builder.random;
- this.characterList = builder.characterList;
+ this.characterList = new ArrayList<>(builder.characterSet);
}
/**
* Generates a random string, containing the specified number of code points.
*
*
- * Code points are randomly selected between the minimum and maximum values defined
- * in the generator.
- * Surrogate and private use characters are not returned, although the
- * resulting string may contain pairs of surrogates that together encode a
- * supplementary character.
+ * Code points are randomly selected between the minimum and maximum values defined in the generator. Surrogate and private use characters are not returned,
+ * although the resulting string may contain pairs of surrogates that together encode a supplementary character.
*
*
- * Note: the number of {@code char} code units generated will exceed
- * {@code length} if the string contains supplementary characters. See the
- * {@link Character} documentation to understand how Java stores Unicode
- * values.
+ * Note: the number of {@code char} code units generated will exceed {@code length} if the string contains supplementary characters. See the
+ * {@link Character} documentation to understand how Java stores Unicode values.
*
*
- * @param length
- * the number of code points to generate
- * @return The generated string
- * @throws IllegalArgumentException
- * if {@code length < 0}
+ * @param length the number of code points to generate.
+ * @return The generated string.
+ * @throws IllegalArgumentException if {@code length < 0}.
*/
public String generate(final int length) {
if (length == 0) {
@@ -460,34 +463,27 @@ public String generate(final int length) {
}
/**
- * Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive)
- * number of code points.
+ * Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive) number of code points.
*
- * @param minLengthInclusive
- * the minimum (inclusive) number of code points to generate
- * @param maxLengthInclusive
- * the maximum (inclusive) number of code points to generate
- * @return The generated string
- * @throws IllegalArgumentException
- * if {@code minLengthInclusive < 0}, or {@code maxLengthInclusive < minLengthInclusive}
+ * @param minLengthInclusive the minimum (inclusive) number of code points to generate.
+ * @param maxLengthInclusive the maximum (inclusive) number of code points to generate.
+ * @return The generated string.
+ * @throws IllegalArgumentException if {@code minLengthInclusive < 0}, or {@code maxLengthInclusive < minLengthInclusive}.
* @see RandomStringGenerator#generate(int)
* @since 1.2
*/
public String generate(final int minLengthInclusive, final int maxLengthInclusive) {
Validate.isTrue(minLengthInclusive >= 0, "Minimum length %d is smaller than zero.", minLengthInclusive);
- Validate.isTrue(minLengthInclusive <= maxLengthInclusive,
- "Maximum length %d is smaller than minimum length %d.", maxLengthInclusive, minLengthInclusive);
+ Validate.isTrue(minLengthInclusive <= maxLengthInclusive, "Maximum length %d is smaller than minimum length %d.", maxLengthInclusive,
+ minLengthInclusive);
return generate(generateRandomNumber(minLengthInclusive, maxLengthInclusive));
}
/**
- * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
- * or the user-supplied source of randomness.
+ * Generates a random number within a range, using a {@link ThreadLocalRandom} instance or the user-supplied source of randomness.
*
- * @param minInclusive
- * the minimum value allowed
- * @param maxInclusive
- * the maximum value allowed
+ * @param minInclusive the minimum value allowed.
+ * @param maxInclusive the maximum value allowed.
* @return The random number.
*/
private int generateRandomNumber(final int minInclusive, final int maxInclusive) {
@@ -498,8 +494,7 @@ private int generateRandomNumber(final int minInclusive, final int maxInclusive)
}
/**
- * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
- * or the user-supplied source of randomness.
+ * Generates a random number within a range, using a {@link ThreadLocalRandom} instance or the user-supplied source of randomness.
*
* @param characterList predefined char list.
* @return The random number.
diff --git a/src/main/java/org/apache/commons/text/StrBuilder.java b/src/main/java/org/apache/commons/text/StrBuilder.java
index 25759a7e9c..f1df60a2a2 100644
--- a/src/main/java/org/apache/commons/text/StrBuilder.java
+++ b/src/main/java/org/apache/commons/text/StrBuilder.java
@@ -283,7 +283,7 @@ public StrBuilder() {
/**
* Constructs an empty builder the specified initial capacity.
*
- * @param initialCapacity the initial capacity, zero or less will be converted to 32
+ * @param initialCapacity the initial capacity, zero or less will be converted to 32.
*/
public StrBuilder(int initialCapacity) {
if (initialCapacity <= 0) {
@@ -295,7 +295,7 @@ public StrBuilder(int initialCapacity) {
/**
* Constructs a builder from the string, allocating 32 extra characters for growth.
*
- * @param str the string to copy, null treated as blank string
+ * @param str the string to copy, null treated as blank string.
*/
public StrBuilder(final String str) {
if (str == null) {
@@ -309,7 +309,7 @@ public StrBuilder(final String str) {
/**
* Appends a boolean value to the string builder.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
*/
public StrBuilder append(final boolean value) {
@@ -332,7 +332,7 @@ public StrBuilder append(final boolean value) {
/**
* Appends a char value to the string builder.
*
- * @param ch the value to append
+ * @param ch the value to append.
* @return {@code this} instance.
*/
@Override
@@ -346,7 +346,7 @@ public StrBuilder append(final char ch) {
/**
* Appends a char array to the string builder. Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
+ * @param chars the char array to append.
* @return {@code this} instance.
*/
public StrBuilder append(final char[] chars) {
@@ -366,9 +366,9 @@ public StrBuilder append(final char[] chars) {
/**
* Appends a char array to the string builder. Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param chars the char array to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
*/
public StrBuilder append(final char[] chars, final int startIndex, final int length) {
@@ -376,7 +376,7 @@ public StrBuilder append(final char[] chars, final int startIndex, final int len
return appendNull();
}
if (startIndex < 0 || startIndex > chars.length) {
- throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length);
+ throw new StringIndexOutOfBoundsException("Invalid startIndex: " + startIndex);
}
if (length < 0 || startIndex + length > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid length: " + length);
@@ -393,7 +393,7 @@ public StrBuilder append(final char[] chars, final int startIndex, final int len
/**
* Appends the contents of a char buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param buf the char buffer to append
+ * @param buf the char buffer to append.
* @return {@code this} instance.
*/
public StrBuilder append(final CharBuffer buf) {
@@ -415,9 +415,9 @@ public StrBuilder append(final CharBuffer buf) {
/**
* Appends the contents of a char buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param buf the char buffer to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param buf the char buffer to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
*/
public StrBuilder append(final CharBuffer buf, final int startIndex, final int length) {
@@ -445,7 +445,7 @@ public StrBuilder append(final CharBuffer buf, final int startIndex, final int l
/**
* Appends a CharSequence to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param seq the CharSequence to append
+ * @param seq the CharSequence to append.
* @return {@code this} instance.
*/
@Override
@@ -471,9 +471,9 @@ public StrBuilder append(final CharSequence seq) {
/**
* Appends part of a CharSequence to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param seq the CharSequence to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param seq the CharSequence to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
*/
@Override
@@ -487,7 +487,7 @@ public StrBuilder append(final CharSequence seq, final int startIndex, final int
/**
* Appends a double value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
*/
public StrBuilder append(final double value) {
@@ -497,7 +497,7 @@ public StrBuilder append(final double value) {
/**
* Appends a float value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
*/
public StrBuilder append(final float value) {
@@ -507,7 +507,7 @@ public StrBuilder append(final float value) {
/**
* Appends an int value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
*/
public StrBuilder append(final int value) {
@@ -517,7 +517,7 @@ public StrBuilder append(final int value) {
/**
* Appends a long value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
*/
public StrBuilder append(final long value) {
@@ -527,7 +527,7 @@ public StrBuilder append(final long value) {
/**
* Appends an object to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param obj the object to append
+ * @param obj the object to append.
* @return {@code this} instance.
*/
public StrBuilder append(final Object obj) {
@@ -543,7 +543,7 @@ public StrBuilder append(final Object obj) {
/**
* Appends another string builder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string builder to append
+ * @param str the string builder to append.
* @return {@code this} instance.
*/
public StrBuilder append(final StrBuilder str) {
@@ -563,9 +563,9 @@ public StrBuilder append(final StrBuilder str) {
/**
* Appends part of a string builder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
*/
public StrBuilder append(final StrBuilder str, final int startIndex, final int length) {
@@ -590,7 +590,7 @@ public StrBuilder append(final StrBuilder str, final int startIndex, final int l
/**
* Appends a string to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
+ * @param str the string to append.
* @return {@code this} instance.
*/
public StrBuilder append(final String str) {
@@ -610,9 +610,9 @@ public StrBuilder append(final String str) {
/**
* Appends part of a string to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
*/
public StrBuilder append(final String str, final int startIndex, final int length) {
@@ -637,9 +637,9 @@ public StrBuilder append(final String str, final int startIndex, final int lengt
/**
* Calls {@link String#format(String, Object...)} and appends the result.
*
- * @param format the format string
- * @param objs the objects to use in the format string
- * @return {@code this} to enable chaining
+ * @param format the format string.
+ * @param objs the objects to use in the format string.
+ * @return {@code this} to enable chaining.
* @see String#format(String, Object...)
*/
public StrBuilder append(final String format, final Object... objs) {
@@ -649,7 +649,7 @@ public StrBuilder append(final String format, final Object... objs) {
/**
* Appends a string buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string buffer to append
+ * @param str the string buffer to append.
* @return {@code this} instance.
*/
public StrBuilder append(final StringBuffer str) {
@@ -669,9 +669,9 @@ public StrBuilder append(final StringBuffer str) {
/**
* Appends part of a string buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
*/
public StrBuilder append(final StringBuffer str, final int startIndex, final int length) {
@@ -696,7 +696,7 @@ public StrBuilder append(final StringBuffer str, final int startIndex, final int
/**
* Appends a StringBuilder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the StringBuilder to append
+ * @param str the StringBuilder to append.
* @return {@code this} instance.
*/
public StrBuilder append(final StringBuilder str) {
@@ -716,9 +716,9 @@ public StrBuilder append(final StringBuilder str) {
/**
* Appends part of a StringBuilder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the StringBuilder to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the StringBuilder to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
*/
public StrBuilder append(final StringBuilder str, final int startIndex, final int length) {
@@ -744,7 +744,7 @@ public StrBuilder append(final StringBuilder str, final int startIndex, final in
* Appends each item in an iterable to the builder without any separators. Appending a null iterable will have no effect. Each object is appended using
* {@link #append(Object)}.
*
- * @param iterable the iterable to append
+ * @param iterable the iterable to append.
* @return {@code this} instance.
*/
public StrBuilder appendAll(final Iterable> iterable) {
@@ -758,7 +758,7 @@ public StrBuilder appendAll(final Iterable> iterable) {
* Appends each item in an iterator to the builder without any separators. Appending a null iterator will have no effect. Each object is appended using
* {@link #append(Object)}.
*
- * @param it the iterator to append
+ * @param it the iterator to append.
* @return {@code this} instance.
*/
public StrBuilder appendAll(final Iterator> it) {
@@ -774,8 +774,8 @@ public StrBuilder appendAll(final Iterator> it) {
* Appends each item in an array to the builder without any separators. Appending a null array will have no effect. Each object is appended using
* {@link #append(Object)}.
*
- * @param the element type
- * @param array the array to append
+ * @param the element type.
+ * @param array the array to append.
* @return {@code this} instance.
*/
public StrBuilder appendAll(@SuppressWarnings("unchecked") final T... array) {
@@ -795,9 +795,9 @@ public StrBuilder appendAll(@SuppressWarnings("unchecked") final T... array)
* Appends an object to the builder padding on the left to a fixed width. The {@code String.valueOf} of the {@code int} value is used. If the formatted
* value is larger than the length, the left hand side is lost.
*
- * @param value the value to append
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
+ * @param value the value to append.
+ * @param width the fixed field width, zero or negative has no effect.
+ * @param padChar the pad character to use.
* @return {@code this} instance.
*/
public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) {
@@ -838,9 +838,9 @@ public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, fin
* Appends an object to the builder padding on the right to a fixed length. The {@code String.valueOf} of the {@code int} value is used. If the object is
* larger than the length, the right hand side is lost.
*
- * @param value the value to append
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
+ * @param value the value to append.
+ * @param width the fixed field width, zero or negative has no effect.
+ * @param padChar the pad character to use.
* @return {@code this} instance.
*/
public StrBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) {
@@ -851,9 +851,9 @@ public StrBuilder appendFixedWidthPadRight(final int value, final int width, fin
* Appends an object to the builder padding on the right to a fixed length. The {@code toString} of the object is used. If the object is larger than the
* length, the right hand side is lost. If the object is null, null text value is used.
*
- * @param obj the object to append, null uses null text
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
+ * @param obj the object to append, null uses null text.
+ * @param width the fixed field width, zero or negative has no effect.
+ * @param padChar the pad character to use.
* @return {@code this} instance.
*/
public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) {
@@ -879,7 +879,7 @@ public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, fi
/**
* Appends a boolean value followed by a {@link #appendNewLine() new line} to the string builder.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -890,7 +890,7 @@ public StrBuilder appendln(final boolean value) {
/**
* Appends a char value followed by a {@link #appendNewLine() new line} to the string builder.
*
- * @param ch the value to append
+ * @param ch the value to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -901,7 +901,7 @@ public StrBuilder appendln(final char ch) {
/**
* Appends a char array followed by a {@link #appendNewLine() new line} to the string builder. Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
+ * @param chars the char array to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -912,9 +912,9 @@ public StrBuilder appendln(final char[] chars) {
/**
* Appends a char array followed by a {@link #appendNewLine() new line} to the string builder. Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param chars the char array to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -925,7 +925,7 @@ public StrBuilder appendln(final char[] chars, final int startIndex, final int l
/**
* Appends a double value followed by a {@link #appendNewLine() new line} to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -936,7 +936,7 @@ public StrBuilder appendln(final double value) {
/**
* Appends a float value followed by a {@link #appendNewLine() new line} to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -947,7 +947,7 @@ public StrBuilder appendln(final float value) {
/**
* Appends an int value followed by a {@link #appendNewLine() new line} to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -958,7 +958,7 @@ public StrBuilder appendln(final int value) {
/**
* Appends a long value followed by a {@link #appendNewLine() new line} to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
+ * @param value the value to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -969,7 +969,7 @@ public StrBuilder appendln(final long value) {
/**
* Appends an object followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param obj the object to append
+ * @param obj the object to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -980,7 +980,7 @@ public StrBuilder appendln(final Object obj) {
/**
* Appends another string builder followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string builder to append
+ * @param str the string builder to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -991,9 +991,9 @@ public StrBuilder appendln(final StrBuilder str) {
/**
* Appends part of a string builder followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -1004,7 +1004,7 @@ public StrBuilder appendln(final StrBuilder str, final int startIndex, final int
/**
* Appends a string followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
+ * @param str the string to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -1015,9 +1015,9 @@ public StrBuilder appendln(final String str) {
/**
* Appends part of a string followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -1028,9 +1028,9 @@ public StrBuilder appendln(final String str, final int startIndex, final int len
/**
* Calls {@link String#format(String, Object...)} and appends the result.
*
- * @param format the format string
- * @param objs the objects to use in the format string
- * @return {@code this} to enable chaining
+ * @param format the format string.
+ * @param objs the objects to use in the format string.
+ * @return {@code this} to enable chaining.
* @see String#format(String, Object...)
* @see #appendNewLine()
*/
@@ -1041,7 +1041,7 @@ public StrBuilder appendln(final String format, final Object... objs) {
/**
* Appends a string buffer followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string buffer to append
+ * @param str the string buffer to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -1052,9 +1052,9 @@ public StrBuilder appendln(final StringBuffer str) {
/**
* Appends part of a string buffer followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -1065,7 +1065,7 @@ public StrBuilder appendln(final StringBuffer str, final int startIndex, final i
/**
* Appends a string builder followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string builder to append
+ * @param str the string builder to append.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -1076,9 +1076,9 @@ public StrBuilder appendln(final StringBuilder str) {
/**
* Appends part of a string builder followed by a {@link #appendNewLine() new line} to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string builder to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param str the string builder to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
* @return {@code this} instance.
* @see #appendNewLine()
*/
@@ -1123,8 +1123,8 @@ public StrBuilder appendNull() {
/**
* Appends the pad character to the builder the specified number of times.
*
- * @param length the length to append, negative means no append
- * @param padChar the character to append
+ * @param length the length to append, negative means no append.
+ * @param padChar the character to append.
* @return {@code this} instance.
*/
public StrBuilder appendPadding(final int length, final char padChar) {
@@ -1153,7 +1153,7 @@ public StrBuilder appendPadding(final int length, final char padChar) {
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use
+ * @param separator the separator to use.
* @return {@code this} instance.
*/
public StrBuilder appendSeparator(final char separator) {
@@ -1169,8 +1169,8 @@ public StrBuilder appendSeparator(final char separator) {
*
* The separator is appended using {@link #append(char)}.
*
- * @param standard the separator if builder is not empty
- * @param defaultIfEmpty the separator if builder is empty
+ * @param standard the separator if builder is not empty.
+ * @param defaultIfEmpty the separator if builder is empty.
* @return {@code this} instance.
*/
public StrBuilder appendSeparator(final char standard, final char defaultIfEmpty) {
@@ -1198,8 +1198,8 @@ public StrBuilder appendSeparator(final char standard, final char defaultIfEmpty
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use
- * @param loopIndex the loop index
+ * @param separator the separator to use.
+ * @param loopIndex the loop index.
* @return {@code this} instance.
*/
public StrBuilder appendSeparator(final char separator, final int loopIndex) {
@@ -1226,7 +1226,7 @@ public StrBuilder appendSeparator(final char separator, final int loopIndex) {
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use, null means no separator
+ * @param separator the separator to use, null means no separator.
* @return {@code this} instance.
*/
public StrBuilder appendSeparator(final String separator) {
@@ -1250,8 +1250,8 @@ public StrBuilder appendSeparator(final String separator) {
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use, null means no separator
- * @param loopIndex the loop index
+ * @param separator the separator to use, null means no separator.
+ * @param loopIndex the loop index.
* @return {@code this} instance.
*/
public StrBuilder appendSeparator(final String separator, final int loopIndex) {
@@ -1284,8 +1284,8 @@ public StrBuilder appendSeparator(final String separator, final int loopIndex) {
* selectClause.append(whereClause)
*
*
- * @param standard the separator if builder is not empty, null means no separator
- * @param defaultIfEmpty the separator if builder is empty, null means no separator
+ * @param standard the separator if builder is not empty, null means no separator.
+ * @param defaultIfEmpty the separator if builder is empty, null means no separator.
* @return {@code this} instance.
*/
public StrBuilder appendSeparator(final String standard, final String defaultIfEmpty) {
@@ -1302,8 +1302,8 @@ public StrBuilder appendSeparator(final String standard, final String defaultIfE
* This method tries to avoid doing any extra copies of contents.
*
*
- * @param appendable the appendable to append data to
- * @throws IOException if an I/O error occurs
+ * @param appendable the appendable to append data to.
+ * @throws IOException if an I/O error occurs.
* @see #readFrom(Readable)
*/
public void appendTo(final Appendable appendable) throws IOException {
@@ -1324,8 +1324,8 @@ public void appendTo(final Appendable appendable) throws IOException {
* Appends an iterable placing separators between each value, but not before the first or after the last. Appending a null iterable will have no effect.
* Each object is appended using {@link #append(Object)}.
*
- * @param iterable the iterable to append
- * @param separator the separator to use, null means no separator
+ * @param iterable the iterable to append.
+ * @param separator the separator to use, null means no separator.
* @return {@code this} instance.
*/
public StrBuilder appendWithSeparators(final Iterable> iterable, final String separator) {
@@ -1339,8 +1339,8 @@ public StrBuilder appendWithSeparators(final Iterable> iterable, final String
* Appends an iterator placing separators between each value, but not before the first or after the last. Appending a null iterator will have no effect.
* Each object is appended using {@link #append(Object)}.
*
- * @param iterator the iterator to append
- * @param separator the separator to use, null means no separator
+ * @param iterator the iterator to append.
+ * @param separator the separator to use, null means no separator.
* @return {@code this} instance.
*/
public StrBuilder appendWithSeparators(final Iterator> iterator, final String separator) {
@@ -1360,8 +1360,8 @@ public StrBuilder appendWithSeparators(final Iterator> iterator, final String
* Appends an array placing separators between each value, but not before the first or after the last. Appending a null array will have no effect. Each
* object is appended using {@link #append(Object)}.
*
- * @param array the array to append
- * @param separator the separator to use, null means no separator
+ * @param array the array to append.
+ * @param separator the separator to use, null means no separator.
* @return {@code this} instance.
*/
public StrBuilder appendWithSeparators(final Object[] array, final String separator) {
@@ -1393,7 +1393,7 @@ public StrBuilder appendWithSeparators(final Object[] array, final String separa
* The returned reader supports marking, and ignores the flush method.
*
*
- * @return a reader that reads from this builder
+ * @return a reader that reads from this builder.
*/
public Reader asReader() {
return new StrBuilderReader();
@@ -1429,7 +1429,7 @@ public Reader asReader() {
* Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])} with a non-null value will break the link with the builder.
*
*
- * @return a tokenizer that is linked to this builder
+ * @return a tokenizer that is linked to this builder.
*/
public StrTokenizer asTokenizer() {
return new StrBuilderTokenizer();
@@ -1453,7 +1453,7 @@ public StrTokenizer asTokenizer() {
* The returned writer ignores the close and flush methods.
*
*
- * @return a writer that populates this builder
+ * @return a writer that populates this builder.
*/
public Writer asWriter() {
return new StrBuilderWriter();
@@ -1462,7 +1462,7 @@ public Writer asWriter() {
/**
* Converts this instance to a String.
*
- * @return This instance as a String
+ * @return This instance as a String.
* @see #toString()
* @deprecated Use {@link #get()}.
*/
@@ -1484,11 +1484,11 @@ public int capacity() {
/**
* Gets the character at the specified index.
*
- * @see #setCharAt(int, char)
- * @see #deleteCharAt(int)
* @param index the index to retrieve, must be valid
* @return The character at the index
* @throws IndexOutOfBoundsException if the index is invalid
+ * @see #setCharAt(int, char)
+ * @see #deleteCharAt(int)
*/
@Override
public char charAt(final int index) {
@@ -1517,8 +1517,8 @@ public StrBuilder clear() {
/**
* Checks if the string builder contains the specified char.
*
- * @param ch the character to find
- * @return true if the builder contains the character
+ * @param ch the character to find.
+ * @return true if the builder contains the character.
*/
public boolean contains(final char ch) {
final char[] thisBuf = buffer;
@@ -1533,8 +1533,8 @@ public boolean contains(final char ch) {
/**
* Tests if the string builder contains the specified string.
*
- * @param str the string to find
- * @return true if the builder contains the string
+ * @param str the string to find.
+ * @return true if the builder contains the string.
*/
public boolean contains(final String str) {
return indexOf(str, 0) >= 0;
@@ -1546,8 +1546,8 @@ public boolean contains(final String str) {
* Matchers can be used to perform advanced searching behavior. For example you could write a matcher to search for the character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @return true if the matcher finds a match in the builder
+ * @param matcher the matcher to use, null returns -1.
+ * @return true if the matcher finds a match in the builder.
*/
public boolean contains(final StrMatcher matcher) {
return indexOf(matcher, 0) >= 0;
@@ -1556,10 +1556,10 @@ public boolean contains(final StrMatcher matcher) {
/**
* Deletes the characters between the two specified indices.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder delete(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
@@ -1573,7 +1573,7 @@ public StrBuilder delete(final int startIndex, int endIndex) {
/**
* Deletes the character wherever it occurs in the builder.
*
- * @param ch the character to delete
+ * @param ch the character to delete.
* @return {@code this} instance.
*/
public StrBuilder deleteAll(final char ch) {
@@ -1596,7 +1596,7 @@ public StrBuilder deleteAll(final char ch) {
/**
* Deletes the string wherever it occurs in the builder.
*
- * @param str the string to delete, null causes no action
+ * @param str the string to delete, null causes no action.
* @return {@code this} instance.
*/
public StrBuilder deleteAll(final String str) {
@@ -1618,7 +1618,7 @@ public StrBuilder deleteAll(final String str) {
* followed by a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param matcher the matcher to use to find the deletion, null causes no action.
* @return {@code this} instance.
*/
public StrBuilder deleteAll(final StrMatcher matcher) {
@@ -1628,11 +1628,11 @@ public StrBuilder deleteAll(final StrMatcher matcher) {
/**
* Deletes the character at the specified index.
*
+ * @param index the index to delete.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
* @see #charAt(int)
* @see #setCharAt(int, char)
- * @param index the index to delete
- * @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder deleteCharAt(final int index) {
if (index < 0 || index >= size) {
@@ -1645,7 +1645,7 @@ public StrBuilder deleteCharAt(final int index) {
/**
* Deletes the character wherever it occurs in the builder.
*
- * @param ch the character to delete
+ * @param ch the character to delete.
* @return {@code this} instance.
*/
public StrBuilder deleteFirst(final char ch) {
@@ -1661,7 +1661,7 @@ public StrBuilder deleteFirst(final char ch) {
/**
* Deletes the string wherever it occurs in the builder.
*
- * @param str the string to delete, null causes no action
+ * @param str the string to delete, null causes no action.
* @return {@code this} instance.
*/
public StrBuilder deleteFirst(final String str) {
@@ -1682,7 +1682,7 @@ public StrBuilder deleteFirst(final String str) {
* number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param matcher the matcher to use to find the deletion, null causes no action.
* @return {@code this} instance.
*/
public StrBuilder deleteFirst(final StrMatcher matcher) {
@@ -1692,10 +1692,10 @@ public StrBuilder deleteFirst(final StrMatcher matcher) {
/**
* Internal method to delete a range without validation.
*
- * @param startIndex the start index, must be valid
- * @param endIndex the end index (exclusive), must be valid
- * @param len the length, must be valid
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param startIndex the start index, must be valid.
+ * @param endIndex the end index (exclusive), must be valid.
+ * @param len the length, must be valid.
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
private void deleteImpl(final int startIndex, final int endIndex, final int len) {
System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex);
@@ -1708,8 +1708,8 @@ private void deleteImpl(final int startIndex, final int endIndex, final int len)
* Note that this method handles null input quietly, unlike String.
*
*
- * @param str the string to search for, null returns false
- * @return true if the builder ends with the string
+ * @param str the string to search for, null returns false.
+ * @return true if the builder ends with the string.
*/
public boolean endsWith(final String str) {
if (str == null) {
@@ -1734,7 +1734,7 @@ public boolean endsWith(final String str) {
/**
* Tests the capacity and ensures that it is at least the size specified.
*
- * @param capacity the capacity to ensure
+ * @param capacity the capacity to ensure.
* @return {@code this} instance.
*/
public StrBuilder ensureCapacity(final int capacity) {
@@ -1749,8 +1749,8 @@ public StrBuilder ensureCapacity(final int capacity) {
/**
* Tests the contents of this builder against another to see if they contain the same character content.
*
- * @param obj the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param obj the object to check, null returns false.
+ * @return true if the builders contain the same characters in the same order.
*/
@Override
public boolean equals(final Object obj) {
@@ -1760,8 +1760,8 @@ public boolean equals(final Object obj) {
/**
* Tests the contents of this builder against another to see if they contain the same character content.
*
- * @param other the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param other the object to check, null returns false.
+ * @return true if the builders contain the same characters in the same order.
*/
public boolean equals(final StrBuilder other) {
if (this == other) {
@@ -1786,8 +1786,8 @@ public boolean equals(final StrBuilder other) {
/**
* Tests the contents of this builder against another to see if they contain the same character content ignoring case.
*
- * @param other the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param other the object to check, null returns false.
+ * @return true if the builders contain the same characters in the same order.
*/
public boolean equalsIgnoreCase(final StrBuilder other) {
if (this == other) {
@@ -1811,7 +1811,7 @@ public boolean equalsIgnoreCase(final StrBuilder other) {
/**
* Converts this instance to a String.
*
- * @return This instance as a String
+ * @return This instance as a String.
* @see #toString()
* @since 1.12.0
*/
@@ -1823,8 +1823,8 @@ public String get() {
/**
* Copies the character array into the specified array.
*
- * @param destination the destination array, null will cause an array to be created
- * @return The input array, unless that was null or too small
+ * @param destination the destination array, null will cause an array to be created.
+ * @return The input array, unless that was null or too small.
*/
public char[] getChars(char[] destination) {
final int len = length();
@@ -1838,12 +1838,12 @@ public char[] getChars(char[] destination) {
/**
* Copies the character array into the specified array.
*
- * @param startIndex first index to copy, inclusive, must be valid
- * @param endIndex last index, exclusive, must be valid
- * @param destination the destination array, must not be null or too small
- * @param destinationIndex the index to start copying in destination
- * @throws NullPointerException if the array is null
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param startIndex first index to copy, inclusive, must be valid.
+ * @param endIndex last index, exclusive, must be valid.
+ * @param destination the destination array, must not be null or too small.
+ * @param destinationIndex the index to start copying in destination.
+ * @throws NullPointerException if the array is null.
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
public void getChars(final int startIndex, final int endIndex, final char[] destination, final int destinationIndex) {
if (startIndex < 0) {
@@ -1870,7 +1870,7 @@ public String getNewLineText() {
/**
* Gets the text to be appended when null is added.
*
- * @return The null text, null means no append
+ * @return The null text, null means no append.
*/
public String getNullText() {
return nullText;
@@ -1879,7 +1879,7 @@ public String getNullText() {
/**
* Gets a suitable hash code for this builder.
*
- * @return a hash code
+ * @return a hash code.
*/
@Override
public int hashCode() {
@@ -1894,8 +1894,8 @@ public int hashCode() {
/**
* Searches the string builder to find the first reference to the specified char.
*
- * @param ch the character to find
- * @return The first index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @return The first index of the character, or -1 if not found.
*/
public int indexOf(final char ch) {
return indexOf(ch, 0);
@@ -1904,9 +1904,9 @@ public int indexOf(final char ch) {
/**
* Searches the string builder to find the first reference to the specified char.
*
- * @param ch the character to find
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The first index of the character, or -1 if not found.
*/
public int indexOf(final char ch, int startIndex) {
startIndex = Math.max(startIndex, 0);
@@ -1928,8 +1928,8 @@ public int indexOf(final char ch, int startIndex) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @return The first index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @return The first index of the string, or -1 if not found.
*/
public int indexOf(final String str) {
return indexOf(str, 0);
@@ -1941,14 +1941,14 @@ public int indexOf(final String str) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The first index of the string, or -1 if not found.
*/
public int indexOf(final String str, int startIndex) {
- startIndex = Math.max(startIndex, 0);
+ startIndex = Math.max(0, startIndex);
if (str == null || startIndex >= size) {
- return -1;
+ return StringUtils.INDEX_NOT_FOUND;
}
final int strLen = str.length();
if (strLen == 1) {
@@ -1958,19 +1958,20 @@ public int indexOf(final String str, int startIndex) {
return startIndex;
}
if (strLen > size) {
- return -1;
+ return StringUtils.INDEX_NOT_FOUND;
}
final char[] thisBuf = buffer;
- final int len = size - strLen + 1;
- outer: for (int i = startIndex; i < len; i++) {
- for (int j = 0; j < strLen; j++) {
- if (str.charAt(j) != thisBuf[i + j]) {
- continue outer;
- }
+ final int searchLen = size - strLen + 1;
+ for (int i = startIndex; i < searchLen; i++) {
+ boolean found = true;
+ for (int j = 0; j < strLen && found; j++) {
+ found = str.charAt(j) == thisBuf[i + j];
+ }
+ if (found) {
+ return i;
}
- return i;
}
- return -1;
+ return StringUtils.INDEX_NOT_FOUND;
}
/**
@@ -1979,8 +1980,8 @@ public int indexOf(final String str, int startIndex) {
* Matchers can be used to perform advanced searching behavior. For example you could write a matcher to find the character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @return The first index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @return The first index matched, or -1 if not found.
*/
public int indexOf(final StrMatcher matcher) {
return indexOf(matcher, 0);
@@ -1992,9 +1993,9 @@ public int indexOf(final StrMatcher matcher) {
* Matchers can be used to perform advanced searching behavior. For example you could write a matcher to find the character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The first index matched, or -1 if not found.
*/
public int indexOf(final StrMatcher matcher, int startIndex) {
startIndex = Math.max(startIndex, 0);
@@ -2014,10 +2015,10 @@ public int indexOf(final StrMatcher matcher, int startIndex) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(int index, final boolean value) {
validateIndex(index);
@@ -2045,10 +2046,10 @@ public StrBuilder insert(int index, final boolean value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, final char value) {
validateIndex(index);
@@ -2062,10 +2063,10 @@ public StrBuilder insert(final int index, final char value) {
/**
* Inserts the character array into this builder. Inserting null will use the stored null text value.
*
- * @param index the index to add at, must be valid
- * @param chars the char array to insert
+ * @param index the index to add at, must be valid.
+ * @param chars the char array to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, final char[] chars) {
validateIndex(index);
@@ -2085,12 +2086,12 @@ public StrBuilder insert(final int index, final char[] chars) {
/**
* Inserts part of the character array into this builder. Inserting null will use the stored null text value.
*
- * @param index the index to add at, must be valid
- * @param chars the char array to insert
- * @param offset the offset into the character array to start at, must be valid
- * @param length the length of the character array part to copy, must be positive
+ * @param index the index to add at, must be valid.
+ * @param chars the char array to insert.
+ * @param offset the offset into the character array to start at, must be valid.
+ * @param length the length of the character array part to copy, must be positive.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
public StrBuilder insert(final int index, final char[] chars, final int offset, final int length) {
validateIndex(index);
@@ -2115,10 +2116,10 @@ public StrBuilder insert(final int index, final char[] chars, final int offset,
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, final double value) {
return insert(index, String.valueOf(value));
@@ -2127,10 +2128,10 @@ public StrBuilder insert(final int index, final double value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, final float value) {
return insert(index, String.valueOf(value));
@@ -2139,10 +2140,10 @@ public StrBuilder insert(final int index, final float value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, final int value) {
return insert(index, String.valueOf(value));
@@ -2151,10 +2152,10 @@ public StrBuilder insert(final int index, final int value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, final long value) {
return insert(index, String.valueOf(value));
@@ -2163,10 +2164,10 @@ public StrBuilder insert(final int index, final long value) {
/**
* Inserts the string representation of an object into this builder. Inserting null will use the stored null text value.
*
- * @param index the index to add at, must be valid
- * @param obj the object to insert
+ * @param index the index to add at, must be valid.
+ * @param obj the object to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, final Object obj) {
if (obj == null) {
@@ -2178,10 +2179,10 @@ public StrBuilder insert(final int index, final Object obj) {
/**
* Inserts the string into this builder. Inserting null will use the stored null text value.
*
- * @param index the index to add at, must be valid
- * @param str the string to insert
+ * @param index the index to add at, must be valid.
+ * @param str the string to insert.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder insert(final int index, String str) {
validateIndex(index);
@@ -2229,8 +2230,8 @@ public boolean isNotEmpty() {
/**
* Searches the string builder to find the last reference to the specified char.
*
- * @param ch the character to find
- * @return The last index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @return The last index of the character, or -1 if not found.
*/
public int lastIndexOf(final char ch) {
return lastIndexOf(ch, size - 1);
@@ -2239,9 +2240,9 @@ public int lastIndexOf(final char ch) {
/**
* Searches the string builder to find the last reference to the specified char.
*
- * @param ch the character to find
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The last index of the character, or -1 if not found.
*/
public int lastIndexOf(final char ch, int startIndex) {
startIndex = startIndex >= size ? size - 1 : startIndex;
@@ -2262,8 +2263,8 @@ public int lastIndexOf(final char ch, int startIndex) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @return The last index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @return The last index of the string, or -1 if not found.
*/
public int lastIndexOf(final String str) {
return lastIndexOf(str, size - 1);
@@ -2275,34 +2276,35 @@ public int lastIndexOf(final String str) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The last index of the string, or -1 if not found.
*/
public int lastIndexOf(final String str, int startIndex) {
startIndex = startIndex >= size ? size - 1 : startIndex;
if (str == null || startIndex < 0) {
- return -1;
+ return StringUtils.INDEX_NOT_FOUND;
}
final int strLen = str.length();
- if (strLen > 0 && strLen <= size) {
- if (strLen == 1) {
- return lastIndexOf(str.charAt(0), startIndex);
+ if (strLen == 0) {
+ return startIndex;
+ }
+ if (strLen > size) {
+ return StringUtils.INDEX_NOT_FOUND;
+ }
+ if (strLen == 1) {
+ return lastIndexOf(str.charAt(0), startIndex);
+ }
+ for (int i = startIndex - strLen + 1; i >= 0; i--) {
+ boolean found = true;
+ for (int j = 0; j < strLen && found; j++) {
+ found = str.charAt(j) == buffer[i + j];
}
-
- outer: for (int i = startIndex - strLen + 1; i >= 0; i--) {
- for (int j = 0; j < strLen; j++) {
- if (str.charAt(j) != buffer[i + j]) {
- continue outer;
- }
- }
+ if (found) {
return i;
}
-
- } else if (strLen == 0) {
- return startIndex;
}
- return -1;
+ return StringUtils.INDEX_NOT_FOUND;
}
/**
@@ -2311,8 +2313,8 @@ public int lastIndexOf(final String str, int startIndex) {
* Matchers can be used to perform advanced searching behavior. For example you could write a matcher to find the character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @return The last index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @return The last index matched, or -1 if not found.
*/
public int lastIndexOf(final StrMatcher matcher) {
return lastIndexOf(matcher, size);
@@ -2324,9 +2326,9 @@ public int lastIndexOf(final StrMatcher matcher) {
* Matchers can be used to perform advanced searching behavior. For example you could write a matcher to find the character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The last index matched, or -1 if not found.
*/
public int lastIndexOf(final StrMatcher matcher, int startIndex) {
startIndex = startIndex >= size ? size - 1 : startIndex;
@@ -2350,8 +2352,8 @@ public int lastIndexOf(final StrMatcher matcher, int startIndex) {
* the returned string may be shorter than the length requested.
*
*
- * @param length the number of characters to extract, negative returns empty string
- * @return The new string
+ * @param length the number of characters to extract, negative returns empty string.
+ * @return The new string.
*/
public String leftString(final int length) {
if (length <= 0) {
@@ -2381,9 +2383,9 @@ public int length() {
* available in the builder, as much as possible is returned. Thus the returned string may be shorter than the length requested.
*
*
- * @param index the index to start at, negative means zero
- * @param length the number of characters to extract, negative returns empty string
- * @return The new string
+ * @param index the index to start at, negative means zero.
+ * @param length the number of characters to extract, negative returns empty string.
+ * @return The new string.
*/
public String midString(int index, final int length) {
if (index < 0) {
@@ -2415,8 +2417,8 @@ public StrBuilder minimizeCapacity() {
/**
* If possible, reads chars from the provided {@link Readable} directly into underlying character buffer without making extra copies.
*
- * @param readable object to read from
- * @return The number of characters read
+ * @param readable object to read from.
+ * @return The number of characters read.
* @throws IOException if an I/O error occurs.
* @see #appendTo(Appendable)
*/
@@ -2453,11 +2455,11 @@ public int readFrom(final Readable readable) throws IOException {
/**
* Replaces a portion of the string builder with another string. The length of the inserted string does not have to match the removed length.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @param replaceStr the string to replace with, null means delete range
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @param replaceStr the string to replace with, null means delete range.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public StrBuilder replace(final int startIndex, int endIndex, final String replaceStr) {
endIndex = validateRange(startIndex, endIndex);
@@ -2473,13 +2475,13 @@ public StrBuilder replace(final int startIndex, int endIndex, final String repla
* a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the string to replace the match with, null is a delete
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @param replaceCount the number of times to replace, -1 for replace all
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the string to replace the match with, null is a delete.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @param replaceCount the number of times to replace, -1 for replace all.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if start index is invalid
+ * @throws IndexOutOfBoundsException if start index is invalid.
*/
public StrBuilder replace(final StrMatcher matcher, final String replaceStr, final int startIndex, int endIndex, final int replaceCount) {
endIndex = validateRange(startIndex, endIndex);
@@ -2489,8 +2491,8 @@ public StrBuilder replace(final StrMatcher matcher, final String replaceStr, fin
/**
* Replaces the search character with the replace character throughout the builder.
*
- * @param search the search character
- * @param replace the replace character
+ * @param search the search character.
+ * @param replace the replace character.
* @return {@code this} instance.
*/
public StrBuilder replaceAll(final char search, final char replace) {
@@ -2507,8 +2509,8 @@ public StrBuilder replaceAll(final char search, final char replace) {
/**
* Replaces the search string with the replace string throughout the builder.
*
- * @param searchStr the search string, null causes no action to occur
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param searchStr the search string, null causes no action to occur.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
* @return {@code this} instance.
*/
public StrBuilder replaceAll(final String searchStr, final String replaceStr) {
@@ -2531,8 +2533,8 @@ public StrBuilder replaceAll(final String searchStr, final String replaceStr) {
* followed by a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
* @return {@code this} instance.
*/
public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) {
@@ -2542,8 +2544,8 @@ public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr)
/**
* Replaces the first instance of the search character with the replace character in the builder.
*
- * @param search the search character
- * @param replace the replace character
+ * @param search the search character.
+ * @param replace the replace character.
* @return {@code this} instance.
*/
public StrBuilder replaceFirst(final char search, final char replace) {
@@ -2561,8 +2563,8 @@ public StrBuilder replaceFirst(final char search, final char replace) {
/**
* Replaces the first instance of the search string with the replace string.
*
- * @param searchStr the search string, null causes no action to occur
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param searchStr the search string, null causes no action to occur.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
* @return {@code this} instance.
*/
public StrBuilder replaceFirst(final String searchStr, final String replaceStr) {
@@ -2584,8 +2586,8 @@ public StrBuilder replaceFirst(final String searchStr, final String replaceStr)
* number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
* @return {@code this} instance.
*/
public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr) {
@@ -2595,12 +2597,12 @@ public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr
/**
* Internal method to delete a range without validation.
*
- * @param startIndex the start index, must be valid
- * @param endIndex the end index (exclusive), must be valid
- * @param removeLen the length to remove (endIndex - startIndex), must be valid
- * @param insertStr the string to replace with, null means delete range
- * @param insertLen the length of the insert string, must be valid
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param startIndex the start index, must be valid.
+ * @param endIndex the end index (exclusive), must be valid.
+ * @param removeLen the length to remove (endIndex - startIndex), must be valid.
+ * @param insertStr the string to replace with, null means delete range.
+ * @param insertLen the length of the insert string, must be valid.
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
private void replaceImpl(final int startIndex, final int endIndex, final int removeLen, final String insertStr, final int insertLen) {
final int newSize = size - removeLen + insertLen;
@@ -2621,13 +2623,13 @@ private void replaceImpl(final int startIndex, final int endIndex, final int rem
* a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the string to replace the match with, null is a delete
- * @param from the start index, must be valid
- * @param to the end index (exclusive), must be valid
- * @param replaceCount the number of times to replace, -1 for replace all
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the string to replace the match with, null is a delete.
+ * @param from the start index, must be valid.
+ * @param to the end index (exclusive), must be valid.
+ * @param replaceCount the number of times to replace, -1 for replace all.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
private StrBuilder replaceImpl(final StrMatcher matcher, final String replaceStr, final int from, int to, int replaceCount) {
if (matcher == null || size == 0) {
@@ -2676,8 +2678,8 @@ public StrBuilder reverse() {
* the returned string may be shorter than the length requested.
*
*
- * @param length the number of characters to extract, negative returns empty string
- * @return The new string
+ * @param length the number of characters to extract, negative returns empty string.
+ * @return The new string.
*/
public String rightString(final int length) {
if (length <= 0) {
@@ -2692,12 +2694,12 @@ public String rightString(final int length) {
/**
* Sets the character at the specified index.
*
+ * @param index the index to set.
+ * @param ch the new character.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
* @see #charAt(int)
* @see #deleteCharAt(int)
- * @param index the index to set
- * @param ch the new character
- * @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder setCharAt(final int index, final char ch) {
if (index < 0 || index >= length()) {
@@ -2710,9 +2712,9 @@ public StrBuilder setCharAt(final int index, final char ch) {
/**
* Updates the length of the builder by either dropping the last characters or adding filler of Unicode zero.
*
- * @param length the length to set to, must be zero or positive
+ * @param length the length to set to, must be zero or positive.
* @return {@code this} instance.
- * @throws IndexOutOfBoundsException if the length is negative
+ * @throws IndexOutOfBoundsException if the length is negative.
*/
public StrBuilder setLength(final int length) {
if (length < 0) {
@@ -2742,7 +2744,7 @@ public StrBuilder setNewLineText(final String newLine) {
/**
* Sets the text to be appended when null is added.
*
- * @param nullText the null text, null means no append
+ * @param nullText the null text, null means no append.
* @return {@code this} instance.
*/
public StrBuilder setNullText(String nullText) {
@@ -2759,7 +2761,7 @@ public StrBuilder setNullText(String nullText) {
* This method is the same as {@link #length()} and is provided to match the API of Collections.
*
*
- * @return The length
+ * @return The length.
*/
public int size() {
return size;
@@ -2771,8 +2773,8 @@ public int size() {
* Note that this method handles null input quietly, unlike String.
*
*
- * @param str the string to search for, null returns false
- * @return true if the builder starts with the string
+ * @param str the string to search for, null returns false.
+ * @return true if the builder starts with the string.
*/
public boolean startsWith(final String str) {
if (str == null) {
@@ -2813,9 +2815,9 @@ public CharSequence subSequence(final int startIndex, final int endIndex) {
/**
* Extracts a portion of this string builder as a string.
*
- * @param start the start index, inclusive, must be valid
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param start the start index, inclusive, must be valid.
+ * @return The new string.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public String substring(final int start) {
return substring(start, size);
@@ -2827,10 +2829,10 @@ public String substring(final int start) {
* Note: This method treats an endIndex greater than the length of the builder as equal to the length of the builder, and continues without error, unlike
* StringBuffer or String.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @return The new string.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public String substring(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
@@ -2840,7 +2842,7 @@ public String substring(final int startIndex, int endIndex) {
/**
* Copies the builder's character array into a new character array.
*
- * @return a new array that represents the contents of the builder
+ * @return a new array that represents the contents of the builder.
*/
public char[] toCharArray() {
return size == 0 ? ArrayUtils.EMPTY_CHAR_ARRAY : Arrays.copyOf(buffer, size);
@@ -2849,10 +2851,10 @@ public char[] toCharArray() {
/**
* Copies part of the builder's character array into a new character array.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @return a new array that holds part of the contents of the builder
- * @throws IndexOutOfBoundsException if startIndex is invalid, or if endIndex is invalid (but endIndex greater than size is valid)
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @return a new array that holds part of the contents of the builder.
+ * @throws IndexOutOfBoundsException if startIndex is invalid, or if endIndex is invalid (but endIndex greater than size is valid).
*/
public char[] toCharArray(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
@@ -2871,7 +2873,7 @@ public char[] toCharArray(final int startIndex, int endIndex) {
* Note that unlike StringBuffer, the string version returned is independent of the string builder.
*
*
- * @return The builder as a String
+ * @return The builder as a String.
*/
@Override
public String toString() {
@@ -2881,7 +2883,7 @@ public String toString() {
/**
* Gets a StringBuffer version of the string builder, creating a new instance each time the method is called.
*
- * @return The builder as a StringBuffer
+ * @return The builder as a StringBuffer.
*/
public StringBuffer toStringBuffer() {
return new StringBuffer(size).append(buffer, 0, size);
@@ -2890,7 +2892,7 @@ public StringBuffer toStringBuffer() {
/**
* Gets a StringBuilder version of the string builder, creating a new instance each time the method is called.
*
- * @return The builder as a StringBuilder
+ * @return The builder as a StringBuilder.
*/
public StringBuilder toStringBuilder() {
return new StringBuilder(size).append(buffer, 0, size);
@@ -2926,8 +2928,8 @@ public StrBuilder trim() {
/**
* Validates parameters defining a single index in the builder.
*
- * @param index the index, must be valid
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index, must be valid.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
protected void validateIndex(final int index) {
if (index < 0 || index > size) {
@@ -2938,10 +2940,10 @@ protected void validateIndex(final int index) {
/**
* Validates parameters defining a range of the builder.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @return The new string.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
protected int validateRange(final int startIndex, int endIndex) {
if (startIndex < 0) {
diff --git a/src/main/java/org/apache/commons/text/StrLookup.java b/src/main/java/org/apache/commons/text/StrLookup.java
index 113b313e4b..b21778138f 100644
--- a/src/main/java/org/apache/commons/text/StrLookup.java
+++ b/src/main/java/org/apache/commons/text/StrLookup.java
@@ -96,7 +96,7 @@ private static final class ResourceBundleLookup extends StrLookup {
/**
* Creates a new instance backed by a ResourceBundle.
*
- * @param resourceBundle the ResourceBundle of keys to values, may be null
+ * @param resourceBundle the ResourceBundle of keys to values, may be null.
*/
private ResourceBundleLookup(final ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
@@ -162,9 +162,9 @@ public String lookup(final String key) {
* using toString().
*
*
- * @param the type of the values supported by the lookup
- * @param map the map of keys to values, may be null
- * @return a lookup using the map, not null
+ * @param the type of the values supported by the lookup.
+ * @param map the map of keys to values, may be null.
+ * @return a lookup using the map, not null.
*/
public static StrLookup mapLookup(final Map map) {
return new MapStrLookup<>(map);
@@ -173,7 +173,7 @@ public static StrLookup mapLookup(final Map map) {
/**
* Returns a lookup which always returns null.
*
- * @return a lookup that always returns null, not null
+ * @return a lookup that always returns null, not null.
*/
public static StrLookup> noneLookup() {
return NONE_LOOKUP;
@@ -186,8 +186,8 @@ public static StrLookup> noneLookup() {
* to a string using toString().
*
*
- * @param resourceBundle the map of keys to values, may be null
- * @return a lookup using the map, not null
+ * @param resourceBundle the map of keys to values, may be null.
+ * @return a lookup using the map, not null.
* @see StringLookupFactory#resourceBundleStringLookup(String)
*/
public static StrLookup resourceBundleLookup(final ResourceBundle resourceBundle) {
@@ -203,7 +203,7 @@ public static StrLookup resourceBundleLookup(final ResourceBundle resour
* If a null key is used, this lookup will throw a NullPointerException.
*
*
- * @return a lookup using system properties, not null
+ * @return a lookup using system properties, not null.
*/
public static StrLookup systemPropertiesLookup() {
return SYSTEM_PROPERTIES_LOOKUP;
diff --git a/src/main/java/org/apache/commons/text/StrMatcher.java b/src/main/java/org/apache/commons/text/StrMatcher.java
index 98bc545cc6..c9c24bb58d 100644
--- a/src/main/java/org/apache/commons/text/StrMatcher.java
+++ b/src/main/java/org/apache/commons/text/StrMatcher.java
@@ -46,7 +46,7 @@ private static final class CharMatcher extends StrMatcher {
/**
* Constructor that creates a matcher that matches a single character.
*
- * @param ch the character to match
+ * @param ch the character to match.
*/
private CharMatcher(final char ch) {
this.ch = ch;
@@ -55,11 +55,11 @@ private CharMatcher(final char ch) {
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @param bufferStart the first active index in the buffer, valid for buffer.
+ * @param bufferEnd the end index of the active buffer, valid for buffer.
+ * @return The number of matching characters, or zero if there is no match.
*/
@Override
public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
@@ -88,11 +88,11 @@ private CharSetMatcher(final char[] chars) {
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @param bufferStart the first active index in the buffer, valid for buffer.
+ * @param bufferEnd the end index of the active buffer, valid for buffer.
+ * @return The number of matching characters, or zero if there is no match.
*/
@Override
public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
@@ -114,11 +114,11 @@ private NoMatcher() {
/**
* Always returns {@code 0}.
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @param bufferStart the first active index in the buffer, valid for buffer.
+ * @param bufferEnd the end index of the active buffer, valid for buffer.
+ * @return The number of matching characters, or zero if there is no match.
*/
@Override
public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
@@ -146,11 +146,11 @@ private StringMatcher(final String str) {
/**
* Returns the number of matching characters, or zero if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @param bufferStart the first active index in the buffer, valid for buffer.
+ * @param bufferEnd the end index of the active buffer, valid for buffer.
+ * @return The number of matching characters, or zero if there is no match.
*/
@Override
public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
@@ -187,11 +187,11 @@ private TrimMatcher() {
/**
* Returns whether or not the given character matches.
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @param bufferStart the first active index in the buffer, valid for buffer.
+ * @param bufferEnd the end index of the active buffer, valid for buffer.
+ * @return The number of matching characters, or zero if there is no match.
*/
@Override
public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
@@ -248,8 +248,8 @@ public int isMatch(final char[] buffer, final int pos, final int bufferStart, fi
/**
* Creates a matcher from a character.
*
- * @param ch the character to match, must not be null
- * @return a new Matcher for the given char
+ * @param ch the character to match, must not be null.
+ * @return a new Matcher for the given char.
*/
public static StrMatcher charMatcher(final char ch) {
return new CharMatcher(ch);
@@ -258,8 +258,8 @@ public static StrMatcher charMatcher(final char ch) {
/**
* Creates a matcher from a set of characters.
*
- * @param chars the characters to match, null or empty matches nothing
- * @return a new matcher for the given char[]
+ * @param chars the characters to match, null or empty matches nothing.
+ * @return a new matcher for the given char[].
*/
public static StrMatcher charSetMatcher(final char... chars) {
if (ArrayUtils.isEmpty(chars)) {
@@ -274,8 +274,8 @@ public static StrMatcher charSetMatcher(final char... chars) {
/**
* Creates a matcher from a string representing a set of characters.
*
- * @param chars the characters to match, null or empty matches nothing
- * @return a new Matcher for the given characters
+ * @param chars the characters to match, null or empty matches nothing.
+ * @return a new Matcher for the given characters.
*/
public static StrMatcher charSetMatcher(final String chars) {
if (chars == null || chars.isEmpty()) {
@@ -290,7 +290,7 @@ public static StrMatcher charSetMatcher(final String chars) {
/**
* Returns a matcher which matches the comma character.
*
- * @return a matcher for a comma
+ * @return a matcher for a comma.
*/
public static StrMatcher commaMatcher() {
return COMMA_MATCHER;
@@ -299,7 +299,7 @@ public static StrMatcher commaMatcher() {
/**
* Returns a matcher which matches the double quote character.
*
- * @return a matcher for a double quote
+ * @return a matcher for a double quote.
*/
public static StrMatcher doubleQuoteMatcher() {
return DOUBLE_QUOTE_MATCHER;
@@ -308,7 +308,7 @@ public static StrMatcher doubleQuoteMatcher() {
/**
* Matches no characters.
*
- * @return a matcher that matches nothing
+ * @return a matcher that matches nothing.
*/
public static StrMatcher noneMatcher() {
return NONE_MATCHER;
@@ -317,7 +317,7 @@ public static StrMatcher noneMatcher() {
/**
* Returns a matcher which matches the single or double quote character.
*
- * @return a matcher for a single or double quote
+ * @return a matcher for a single or double quote.
*/
public static StrMatcher quoteMatcher() {
return QUOTE_MATCHER;
@@ -326,7 +326,7 @@ public static StrMatcher quoteMatcher() {
/**
* Returns a matcher which matches the single quote character.
*
- * @return a matcher for a single quote
+ * @return a matcher for a single quote.
*/
public static StrMatcher singleQuoteMatcher() {
return SINGLE_QUOTE_MATCHER;
@@ -335,7 +335,7 @@ public static StrMatcher singleQuoteMatcher() {
/**
* Returns a matcher which matches the space character.
*
- * @return a matcher for a space
+ * @return a matcher for a space.
*/
public static StrMatcher spaceMatcher() {
return SPACE_MATCHER;
@@ -345,7 +345,7 @@ public static StrMatcher spaceMatcher() {
* Matches the same characters as StringTokenizer,
* namely space, tab, newline and form feed.
*
- * @return The split matcher
+ * @return The split matcher.
*/
public static StrMatcher splitMatcher() {
return SPLIT_MATCHER;
@@ -367,7 +367,7 @@ public static StrMatcher stringMatcher(final String str) {
/**
* Returns a matcher which matches the tab character.
*
- * @return a matcher for a tab
+ * @return a matcher for a tab.
*/
public static StrMatcher tabMatcher() {
return TAB_MATCHER;
@@ -376,7 +376,7 @@ public static StrMatcher tabMatcher() {
/**
* Matches the String trim() whitespace characters.
*
- * @return The trim matcher
+ * @return The trim matcher.
*/
public static StrMatcher trimMatcher() {
return TRIM_MATCHER;
@@ -406,9 +406,9 @@ protected StrMatcher() {
* The number indicates the number of characters that matched.
*
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @return The number of matching characters, or zero if there is no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @return The number of matching characters, or zero if there is no match.
*/
public int isMatch(final char[] buffer, final int pos) {
return isMatch(buffer, pos, 0, buffer.length);
@@ -437,11 +437,11 @@ public int isMatch(final char[] buffer, final int pos) {
* The number indicates the number of characters that matched.
*
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index (exclusive) of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @param bufferStart the first active index in the buffer, valid for buffer.
+ * @param bufferEnd the end index (exclusive) of the active buffer, valid for buffer.
+ * @return The number of matching characters, or zero if there is no match.
*/
public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd);
diff --git a/src/main/java/org/apache/commons/text/StrSubstitutor.java b/src/main/java/org/apache/commons/text/StrSubstitutor.java
index 88570e8530..8e8c23e2f8 100644
--- a/src/main/java/org/apache/commons/text/StrSubstitutor.java
+++ b/src/main/java/org/apache/commons/text/StrSubstitutor.java
@@ -150,10 +150,10 @@ public class StrSubstitutor {
* Replaces all the occurrences of variables in the given source object with
* their matching values from the map.
*
- * @param the type of the values in the map
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueMap the map with the values, may be null
- * @return The result of the replace operation
+ * @param the type of the values in the map.
+ * @param source the source text containing the variables to substitute, null returns null.
+ * @param valueMap the map with the values, may be null.
+ * @return The result of the replace operation.
*/
public static String replace(final Object source, final Map valueMap) {
return new StrSubstitutor(valueMap).replace(source);
@@ -164,13 +164,13 @@ public static String replace(final Object source, final Map value
* their matching values from the map. This method allows to specify a
* custom variable prefix and suffix
*
- * @param the type of the values in the map
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueMap the map with the values, may be null
- * @param prefix the prefix of variables, not null
- * @param suffix the suffix of variables, not null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param the type of the values in the map.
+ * @param source the source text containing the variables to substitute, null returns null.
+ * @param valueMap the map with the values, may be null.
+ * @param prefix the prefix of variables, not null.
+ * @param suffix the suffix of variables, not null.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public static String replace(final Object source,
final Map valueMap,
@@ -183,24 +183,23 @@ public static String replace(final Object source,
* Replaces all the occurrences of variables in the given source object with their matching
* values from the properties.
*
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueProperties the properties with values, may be null
- * @return The result of the replace operation
+ * @param source the source text containing the variables to substitute, null returns null.
+ * @param valueProperties the properties with values, may be null.
+ * @return The result of the replace operation.
*/
public static String replace(final Object source, final Properties valueProperties) {
if (valueProperties == null) {
return source.toString();
}
- return StrSubstitutor.replace(source,
- valueProperties.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), valueProperties::getProperty)));
+ return replace(source, valueProperties.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), valueProperties::getProperty)));
}
/**
* Replaces all the occurrences of variables in the given source object with
* their matching values from the system properties.
*
- * @param source the source text containing the variables to substitute, null returns null
- * @return The result of the replace operation
+ * @param source the source text containing the variables to substitute, null returns null.
+ * @return The result of the replace operation.
*/
public static String replaceSystemProperties(final Object source) {
return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source);
@@ -258,8 +257,8 @@ public StrSubstitutor() {
* Constructs a new instance and initializes it. Uses defaults for variable
* prefix and suffix and the escaping character.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
*/
public StrSubstitutor(final Map valueMap) {
this(StrLookup.mapLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
@@ -268,11 +267,11 @@ public StrSubstitutor(final Map valueMap) {
/**
* Constructs a new instance and initializes it. Uses a default escaping character.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StrSubstitutor(final Map valueMap, final String prefix, final String suffix) {
this(StrLookup.mapLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE);
@@ -281,12 +280,12 @@ public StrSubstitutor(final Map valueMap, final String prefix, fi
/**
* Constructs a new instance and initializes it.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StrSubstitutor(final Map valueMap, final String prefix, final String suffix,
final char escape) {
@@ -296,13 +295,13 @@ public StrSubstitutor(final Map valueMap, final String prefix, fi
/**
* Constructs a new instance and initializes it.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @param valueDelimiter the variable default value delimiter, may be null.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StrSubstitutor(final Map valueMap, final String prefix, final String suffix,
final char escape, final String valueDelimiter) {
@@ -312,7 +311,7 @@ public StrSubstitutor(final Map valueMap, final String prefix, fi
/**
* Constructs a new instance and initializes it.
*
- * @param variableResolver the variable resolver, may be null
+ * @param variableResolver the variable resolver, may be null.
*/
public StrSubstitutor(final StrLookup> variableResolver) {
this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
@@ -321,11 +320,11 @@ public StrSubstitutor(final StrLookup> variableResolver) {
/**
* Constructs a new instance and initializes it.
*
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param variableResolver the variable resolver, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StrSubstitutor(final StrLookup> variableResolver, final String prefix, final String suffix,
final char escape) {
@@ -339,12 +338,12 @@ public StrSubstitutor(final StrLookup> variableResolver, final String prefix,
/**
* Constructs a new instance and initializes it.
*
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter string, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param variableResolver the variable resolver, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @param valueDelimiter the variable default value delimiter string, may be null.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StrSubstitutor(final StrLookup> variableResolver, final String prefix, final String suffix,
final char escape, final String valueDelimiter) {
@@ -358,11 +357,11 @@ public StrSubstitutor(final StrLookup> variableResolver, final String prefix,
/**
* Constructs a new instance and initializes it.
*
- * @param variableResolver the variable resolver, may be null
- * @param prefixMatcher the prefix for variables, not null
- * @param suffixMatcher the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param variableResolver the variable resolver, may be null.
+ * @param prefixMatcher the prefix for variables, not null.
+ * @param suffixMatcher the suffix for variables, not null.
+ * @param escape the escape character.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StrSubstitutor(
final StrLookup> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
@@ -373,12 +372,12 @@ public StrSubstitutor(
/**
* Constructs a new instance and initializes it.
*
- * @param variableResolver the variable resolver, may be null
- * @param prefixMatcher the prefix for variables, not null
- * @param suffixMatcher the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param variableResolver the variable resolver, may be null.
+ * @param prefixMatcher the prefix for variables, not null.
+ * @param suffixMatcher the suffix for variables, not null.
+ * @param escape the escape character.
+ * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StrSubstitutor(
final StrLookup> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
@@ -393,8 +392,8 @@ public StrSubstitutor(
/**
* Checks if the specified variable is already in the stack (list) of variables.
*
- * @param varName the variable name to check
- * @param priorVariables the list of prior variables
+ * @param varName the variable name to check.
+ * @param priorVariables the list of prior variables.
*/
private void checkCyclicSubstitution(final String varName, final List priorVariables) {
if (!priorVariables.contains(varName)) {
@@ -411,7 +410,7 @@ private void checkCyclicSubstitution(final String varName, final List pr
/**
* Returns the escape character.
*
- * @return The character used for escaping variable references
+ * @return The character used for escaping variable references.
*/
public char getEscapeChar() {
return this.escapeChar;
@@ -420,15 +419,14 @@ public char getEscapeChar() {
/**
* Gets the variable default value delimiter matcher currently in use.
*
- * The variable default value delimiter is the character or characters that delimit the
- * variable name and the variable default value. This delimiter is expressed in terms of a matcher
- * allowing advanced variable default value delimiter matches.
+ * The variable default value delimiter is the character or characters that delimit the variable name and the variable default value. This delimiter is
+ * expressed in terms of a matcher allowing advanced variable default value delimiter matches.
*
*
* If it returns null, then the variable default value resolution is disabled.
*
*
- * @return The variable default value delimiter matcher in use, may be null
+ * @return The variable default value delimiter matcher in use, may be null.
*/
public StrMatcher getValueDelimiterMatcher() {
return valueDelimiterMatcher;
@@ -437,12 +435,11 @@ public StrMatcher getValueDelimiterMatcher() {
/**
* Gets the variable prefix matcher currently in use.
*
- * The variable prefix is the character or characters that identify the
- * start of a variable. This prefix is expressed in terms of a matcher
- * allowing advanced prefix matches.
+ * The variable prefix is the character or characters that identify the start of a variable. This prefix is expressed in terms of a matcher allowing
+ * advanced prefix matches.
*
*
- * @return The prefix matcher in use
+ * @return The prefix matcher in use.
*/
public StrMatcher getVariablePrefixMatcher() {
return prefixMatcher;
@@ -451,7 +448,7 @@ public StrMatcher getVariablePrefixMatcher() {
/**
* Gets the VariableResolver that is used to lookup variables.
*
- * @return The VariableResolver
+ * @return The VariableResolver.
*/
public StrLookup> getVariableResolver() {
return this.variableResolver;
@@ -460,12 +457,11 @@ public StrLookup> getVariableResolver() {
/**
* Gets the variable suffix matcher currently in use.
*
- * The variable suffix is the character or characters that identify the
- * end of a variable. This suffix is expressed in terms of a matcher
- * allowing advanced suffix matches.
+ * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed in terms of a matcher allowing advanced
+ * suffix matches.
*
*
- * @return The suffix matcher in use
+ * @return The suffix matcher in use.
*/
public StrMatcher getVariableSuffixMatcher() {
return suffixMatcher;
@@ -483,12 +479,14 @@ public StrMatcher getVariableSuffixMatcher() {
* StrSubstitutor sub = new StrSubstitutor(valuesMap);
* String resolvedString = sub.replace(templateString);
*
+ *
* yielding:
+ *
*
* Hi Douglas ${surname}
*
*
- * @return The substitution in variable values flag
+ * @return The substitution in variable values flag.
* @since 1.2
*/
public boolean isDisableSubstitutionInValues() {
@@ -498,29 +496,27 @@ public boolean isDisableSubstitutionInValues() {
/**
* Returns a flag whether substitution is done in variable names.
*
- * @return The substitution in variable names flag
+ * @return The substitution in variable names flag.
*/
public boolean isEnableSubstitutionInVariables() {
return enableSubstitutionInVariables;
}
/**
- * Returns the flag controlling whether escapes are preserved during
- * substitution.
+ * Returns the flag controlling whether escapes are preserved during substitution.
*
- * @return The preserve escape flag
+ * @return The preserve escape flag.
*/
public boolean isPreserveEscapes() {
return preserveEscapes;
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source array as a template.
- * The array is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source array as a template. The array is not
+ * altered by this method.
*
- * @param source the character array to replace in, not altered, null returns null
- * @return The result of the replace operation
+ * @param source the character array to replace in, not altered, null returns null.
+ * @return The result of the replace operation.
*/
public String replace(final char[] source) {
if (source == null) {
@@ -532,18 +528,16 @@ public String replace(final char[] source) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source array as a template.
- * The array is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source array as a template. The array is not
+ * altered by this method.
*
- * Only the specified portion of the array will be processed.
- * The rest of the array is not processed, and is not returned.
+ * Only the specified portion of the array will be processed. The rest of the array is not processed, and is not returned.
*
*
- * @param source the character array to replace in, not altered, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
+ * @param source the character array to replace in, not altered, null returns null.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the array to be processed, must be valid.
+ * @return The result of the replace operation.
*/
public String replace(final char[] source, final int offset, final int length) {
if (source == null) {
@@ -555,12 +549,11 @@ public String replace(final char[] source, final int offset, final int length) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source as a template.
- * The source is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source as a template. The source is not altered by
+ * this method.
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @return The result of the replace operation.
*/
public String replace(final CharSequence source) {
if (source == null) {
@@ -570,18 +563,16 @@ public String replace(final CharSequence source) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source as a template.
- * The source is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source as a template. The source is not altered by
+ * this method.
*
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, and is not returned.
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not returned.
*
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the array to be processed, must be valid.
+ * @return The result of the replace operation.
*/
public String replace(final CharSequence source, final int offset, final int length) {
if (source == null) {
@@ -593,12 +584,11 @@ public String replace(final CharSequence source, final int offset, final int len
}
/**
- * Replaces all the occurrences of variables in the given source object with
- * their matching values from the resolver. The input source object is
- * converted to a string using {@code toString} and is not altered.
+ * Replaces all the occurrences of variables in the given source object with their matching values from the resolver. The input source object is converted
+ * to a string using {@code toString} and is not altered.
*
- * @param source the source to replace in, null returns null
- * @return The result of the replace operation
+ * @param source the source to replace in, null returns null.
+ * @return The result of the replace operation.
*/
public String replace(final Object source) {
if (source == null) {
@@ -610,12 +600,11 @@ public String replace(final Object source) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source builder as a template.
- * The builder is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source builder as a template. The builder is not
+ * altered by this method.
*
- * @param source the builder to use as a template, not changed, null returns null
- * @return The result of the replace operation
+ * @param source the builder to use as a template, not changed, null returns null.
+ * @return The result of the replace operation.
*/
public String replace(final StrBuilder source) {
if (source == null) {
@@ -627,18 +616,16 @@ public String replace(final StrBuilder source) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source builder as a template.
- * The builder is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source builder as a template. The builder is not
+ * altered by this method.
*
- * Only the specified portion of the builder will be processed.
- * The rest of the builder is not processed, and is not returned.
+ * Only the specified portion of the builder will be processed. The rest of the builder is not processed, and is not returned.
*
*
- * @param source the builder to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
+ * @param source the builder to use as a template, not changed, null returns null.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the array to be processed, must be valid.
+ * @return The result of the replace operation.
*/
public String replace(final StrBuilder source, final int offset, final int length) {
if (source == null) {
@@ -650,11 +637,10 @@ public String replace(final StrBuilder source, final int offset, final int lengt
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source string as a template.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template.
*
- * @param source the string to replace in, null returns null
- * @return The result of the replace operation
+ * @param source the string to replace in, null returns null.
+ * @return The result of the replace operation.
*/
public String replace(final String source) {
if (source == null) {
@@ -668,17 +654,15 @@ public String replace(final String source) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source string as a template.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template.
*
- * Only the specified portion of the string will be processed.
- * The rest of the string is not processed, and is not returned.
+ * Only the specified portion of the string will be processed. The rest of the string is not processed, and is not returned.
*
*
- * @param source the string to replace in, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
+ * @param source the string to replace in, null returns null.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the array to be processed, must be valid.
+ * @return The result of the replace operation.
*/
public String replace(final String source, final int offset, final int length) {
if (source == null) {
@@ -692,12 +676,11 @@ public String replace(final String source, final int offset, final int length) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source buffer as a template.
- * The buffer is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source buffer as a template. The buffer is not
+ * altered by this method.
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @return The result of the replace operation.
*/
public String replace(final StringBuffer source) {
if (source == null) {
@@ -709,18 +692,16 @@ public String replace(final StringBuffer source) {
}
/**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source buffer as a template.
- * The buffer is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source buffer as a template. The buffer is not
+ * altered by this method.
*
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, and is not returned.
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not returned.
*
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the array to be processed, must be valid.
+ * @return The result of the replace operation.
*/
public String replace(final StringBuffer source, final int offset, final int length) {
if (source == null) {
@@ -732,11 +713,10 @@ public String replace(final StringBuffer source, final int offset, final int len
}
/**
- * Replaces all the occurrences of variables within the given source
- * builder with their matching values from the resolver.
+ * Replaces all the occurrences of variables within the given source builder with their matching values from the resolver.
*
- * @param source the builder to replace in, updated, null returns zero
- * @return true if altered
+ * @param source the builder to replace in, updated, null returns zero.
+ * @return true if altered.
*/
public boolean replaceIn(final StrBuilder source) {
if (source == null) {
@@ -746,17 +726,15 @@ public boolean replaceIn(final StrBuilder source) {
}
/**
- * Replaces all the occurrences of variables within the given source
- * builder with their matching values from the resolver.
+ * Replaces all the occurrences of variables within the given source builder with their matching values from the resolver.
*
- * Only the specified portion of the builder will be processed.
- * The rest of the builder is not processed, but it is not deleted.
+ * Only the specified portion of the builder will be processed. The rest of the builder is not processed, but it is not deleted.
*
*
- * @param source the builder to replace in, null returns zero
- * @param offset the start offset within the array, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @return true if altered
+ * @param source the builder to replace in, null returns zero.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the builder to be processed, must be valid.
+ * @return true if altered.
*/
public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
if (source == null) {
@@ -766,12 +744,11 @@ public boolean replaceIn(final StrBuilder source, final int offset, final int le
}
/**
- * Replaces all the occurrences of variables within the given source buffer
- * with their matching values from the resolver.
- * The buffer is updated with the result.
+ * Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver. The buffer is updated with the
+ * result.
*
- * @param source the buffer to replace in, updated, null returns zero
- * @return true if altered
+ * @param source the buffer to replace in, updated, null returns zero.
+ * @return true if altered.
*/
public boolean replaceIn(final StringBuffer source) {
if (source == null) {
@@ -781,18 +758,16 @@ public boolean replaceIn(final StringBuffer source) {
}
/**
- * Replaces all the occurrences of variables within the given source buffer
- * with their matching values from the resolver.
- * The buffer is updated with the result.
+ * Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver. The buffer is updated with the
+ * result.
*
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, but it is not deleted.
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is not deleted.
*
*
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the array, must be valid
- * @param length the length within the buffer to be processed, must be valid
- * @return true if altered
+ * @param source the buffer to replace in, updated, null returns zero.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the buffer to be processed, must be valid.
+ * @return true if altered.
*/
public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
if (source == null) {
@@ -807,12 +782,11 @@ public boolean replaceIn(final StringBuffer source, final int offset, final int
}
/**
- * Replaces all the occurrences of variables within the given source buffer
- * with their matching values from the resolver.
- * The buffer is updated with the result.
+ * Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver. The buffer is updated with the
+ * result.
*
- * @param source the buffer to replace in, updated, null returns zero
- * @return true if altered
+ * @param source the buffer to replace in, updated, null returns zero.
+ * @return true if altered.
*/
public boolean replaceIn(final StringBuilder source) {
if (source == null) {
@@ -822,18 +796,16 @@ public boolean replaceIn(final StringBuilder source) {
}
/**
- * Replaces all the occurrences of variables within the given source builder
- * with their matching values from the resolver.
- * The builder is updated with the result.
+ * Replaces all the occurrences of variables within the given source builder with their matching values from the resolver. The builder is updated with the
+ * result.
*
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, but it is not deleted.
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is not deleted.
*
*
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the array, must be valid
- * @param length the length within the buffer to be processed, must be valid
- * @return true if altered
+ * @param source the buffer to replace in, updated, null returns zero.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the buffer to be processed, must be valid.
+ * @return true if altered.
*/
public boolean replaceIn(final StringBuilder source, final int offset, final int length) {
if (source == null) {
@@ -850,21 +822,18 @@ public boolean replaceIn(final StringBuilder source, final int offset, final int
/**
* Internal method that resolves the value of a variable.
*
- * Most users of this class do not need to call this method. This method is
- * called automatically by the substitution process.
+ * Most users of this class do not need to call this method. This method is called automatically by the substitution process.
*
*
- * Writers of subclasses can override this method if they need to alter
- * how each substitution occurs. The method is passed the variable's name
- * and must return the corresponding value. This implementation uses the
- * {@link #getVariableResolver()} with the variable's name as the key.
+ * Writers of subclasses can override this method if they need to alter how each substitution occurs. The method is passed the variable's name and must
+ * return the corresponding value. This implementation uses the {@link #getVariableResolver()} with the variable's name as the key.
*
*
- * @param variableName the name of the variable, not null
- * @param buf the buffer where the substitution is occurring, not null
- * @param startPos the start position of the variable including the prefix, valid
- * @param endPos the end position of the variable including the suffix, valid
- * @return The variable's value or null if the variable is unknown
+ * @param variableName the name of the variable, not null.
+ * @param buf the buffer where the substitution is occurring, not null.
+ * @param startPos the start position of the variable including the prefix, valid.
+ * @param endPos the end position of the variable including the suffix, valid.
+ * @return The variable's value or null if the variable is unknown.
*/
protected String resolveVariable(final String variableName,
final StrBuilder buf,
@@ -880,7 +849,7 @@ protected String resolveVariable(final String variableName,
/**
* Sets a flag whether substitution is done in variable values (recursive).
*
- * @param disableSubstitutionInValues true if substitution in variable value are disabled
+ * @param disableSubstitutionInValues true if substitution in variable value are disabled.
* @since 1.2
*/
public void setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
@@ -888,37 +857,28 @@ public void setDisableSubstitutionInValues(final boolean disableSubstitutionInVa
}
/**
- * Sets a flag whether substitution is done in variable names. If set to
- * true, the names of variables can contain other variables which are
- * processed first before the original variable is evaluated, e.g.
- * {@code ${jre-${java.version}}}. The default value is false.
+ * Sets a flag whether substitution is done in variable names. If set to true, the names of variables can contain other variables which are
+ * processed first before the original variable is evaluated, e.g. {@code ${jre-${java.version}}}. The default value is false.
*
- * @param enableSubstitutionInVariables the new value of the flag
+ * @param enableSubstitutionInVariables the new value of the flag.
*/
- public void setEnableSubstitutionInVariables(
- final boolean enableSubstitutionInVariables) {
+ public void setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) {
this.enableSubstitutionInVariables = enableSubstitutionInVariables;
}
/**
- * Sets the escape character.
- * If this character is placed before a variable reference in the source
- * text, this variable will be ignored.
+ * Sets the escape character. If this character is placed before a variable reference in the source text, this variable will be ignored.
*
- * @param escapeCharacter the escape character (0 for disabling escaping)
+ * @param escapeCharacter the escape character (0 for disabling escaping)
*/
public void setEscapeChar(final char escapeCharacter) {
this.escapeChar = escapeCharacter;
}
/**
- * Sets a flag controlling whether escapes are preserved during
- * substitution. If set to true, the escape character is retained
- * during substitution (e.g. {@code $${this-is-escaped}} remains
- * {@code $${this-is-escaped}}). If set to false, the escape
- * character is removed during substitution (e.g.
- * {@code $${this-is-escaped}} becomes
- * {@code ${this-is-escaped}}). The default value is false
+ * Sets a flag controlling whether escapes are preserved during substitution. If set to true, the escape character is retained during
+ * substitution (e.g. {@code $${this-is-escaped}} remains {@code $${this-is-escaped}}). If set to false, the escape character is removed
+ * during substitution (e.g. {@code $${this-is-escaped}} becomes {@code ${this-is-escaped}}). The default value is false
*
* @param preserveEscapes true if escapes are to be preserved
*/
@@ -929,13 +889,12 @@ public void setPreserveEscapes(final boolean preserveEscapes) {
/**
* Sets the variable default value delimiter to use.
*
- * The variable default value delimiter is the character or characters that delimit the
- * variable name and the variable default value. This method allows a single character
- * variable default value delimiter to be easily set.
+ * The variable default value delimiter is the character or characters that delimit the variable name and the variable default value. This method allows a
+ * single character variable default value delimiter to be easily set.
*
*
- * @param valueDelimiter the variable default value delimiter character to use
- * @return this, to enable chaining
+ * @param valueDelimiter the variable default value delimiter character to use.
+ * @return {@code this} instance.
*/
public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter));
@@ -944,17 +903,15 @@ public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
/**
* Sets the variable default value delimiter to use.
*
- * The variable default value delimiter is the character or characters that delimit the
- * variable name and the variable default value. This method allows a string
- * variable default value delimiter to be easily set.
+ * The variable default value delimiter is the character or characters that delimit the variable name and the variable default value. This method allows a
+ * string variable default value delimiter to be easily set.
*
*
- * If the {@code valueDelimiter} is null or empty string, then the variable default
- * value resolution becomes disabled.
+ * If the {@code valueDelimiter} is null or empty string, then the variable default value resolution becomes disabled.
*
*
- * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
- * @return this, to enable chaining
+ * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
+ * @return {@code this} instance.
*/
public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
if (valueDelimiter == null || valueDelimiter.isEmpty()) {
@@ -967,17 +924,15 @@ public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
/**
* Sets the variable default value delimiter matcher to use.
*
- * The variable default value delimiter is the character or characters that delimit the
- * variable name and the variable default value. This delimiter is expressed in terms of a matcher
- * allowing advanced variable default value delimiter matches.
+ * The variable default value delimiter is the character or characters that delimit the variable name and the variable default value. This delimiter is
+ * expressed in terms of a matcher allowing advanced variable default value delimiter matches.
*
*
- * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution
- * becomes disabled.
+ * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution becomes disabled.
*
*
- * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
- * @return this, to enable chaining
+ * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
+ * @return {@code this} instance.
*/
public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) {
this.valueDelimiterMatcher = valueDelimiterMatcher;
@@ -987,13 +942,11 @@ public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMa
/**
* Sets the variable prefix to use.
*
- * The variable prefix is the character or characters that identify the
- * start of a variable. This method allows a single character prefix to
- * be easily set.
+ * The variable prefix is the character or characters that identify the start of a variable. This method allows a single character prefix to be easily set.
*
*
- * @param prefix the prefix character to use
- * @return this, to enable chaining
+ * @param prefix the prefix character to use.
+ * @return {@code this} instance.
*/
public StrSubstitutor setVariablePrefix(final char prefix) {
return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
@@ -1002,13 +955,12 @@ public StrSubstitutor setVariablePrefix(final char prefix) {
/**
* Sets the variable prefix to use.
*
- * The variable prefix is the character or characters that identify the
- * start of a variable. This method allows a string prefix to be easily set.
+ * The variable prefix is the character or characters that identify the start of a variable. This method allows a string prefix to be easily set.
*
*
- * @param prefix the prefix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix is null
+ * @param prefix the prefix for variables, not null.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the prefix is null.
*/
public StrSubstitutor setVariablePrefix(final String prefix) {
Validate.isTrue(prefix != null, "Variable prefix must not be null!");
@@ -1018,14 +970,13 @@ public StrSubstitutor setVariablePrefix(final String prefix) {
/**
* Sets the variable prefix matcher currently in use.
*
- * The variable prefix is the character or characters that identify the
- * start of a variable. This prefix is expressed in terms of a matcher
- * allowing advanced prefix matches.
+ * The variable prefix is the character or characters that identify the start of a variable. This prefix is expressed in terms of a matcher allowing
+ * advanced prefix matches.
*
*
- * @param prefixMatcher the prefix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix matcher is null
+ * @param prefixMatcher the prefix matcher to use, null ignored.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the prefix matcher is null.
*/
public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
@@ -1036,7 +987,7 @@ public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
/**
* Sets the VariableResolver that is used to lookup variables.
*
- * @param variableResolver the VariableResolver
+ * @param variableResolver the VariableResolver.
*/
public void setVariableResolver(final StrLookup> variableResolver) {
this.variableResolver = variableResolver;
@@ -1045,13 +996,11 @@ public void setVariableResolver(final StrLookup> variableResolver) {
/**
* Sets the variable suffix to use.
*
- * The variable suffix is the character or characters that identify the
- * end of a variable. This method allows a single character suffix to
- * be easily set.
+ * The variable suffix is the character or characters that identify the end of a variable. This method allows a single character suffix to be easily set.
*
*
- * @param suffix the suffix character to use
- * @return this, to enable chaining
+ * @param suffix the suffix character to use.
+ * @return {@code this} instance.
*/
public StrSubstitutor setVariableSuffix(final char suffix) {
return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
@@ -1060,13 +1009,12 @@ public StrSubstitutor setVariableSuffix(final char suffix) {
/**
* Sets the variable suffix to use.
*
- * The variable suffix is the character or characters that identify the
- * end of a variable. This method allows a string suffix to be easily set.
+ * The variable suffix is the character or characters that identify the end of a variable. This method allows a string suffix to be easily set.
*
*
- * @param suffix the suffix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix is null
+ * @param suffix the suffix for variables, not null.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the suffix is null.
*/
public StrSubstitutor setVariableSuffix(final String suffix) {
Validate.isTrue(suffix != null, "Variable suffix must not be null!");
@@ -1076,14 +1024,13 @@ public StrSubstitutor setVariableSuffix(final String suffix) {
/**
* Sets the variable suffix matcher currently in use.
*
- * The variable suffix is the character or characters that identify the
- * end of a variable. This suffix is expressed in terms of a matcher
- * allowing advanced suffix matches.
+ * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed in terms of a matcher allowing advanced
+ * suffix matches.
*
*
- * @param suffixMatcher the suffix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix matcher is null
+ * @param suffixMatcher the suffix matcher to use, null ignored.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the suffix matcher is null.
*/
public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
@@ -1094,34 +1041,30 @@ public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
/**
* Internal method that substitutes the variables.
*
- * Most users of this class do not need to call this method. This method will
- * be called automatically by another (public) method.
+ * Most users of this class do not need to call this method. This method will be called automatically by another (public) method.
*
*
- * Writers of subclasses can override this method if they need access to
- * the substitution process at the start or end.
+ * Writers of subclasses can override this method if they need access to the substitution process at the start or end.
*
*
- * @param buf the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @return true if altered
+ * @param buf the string builder to substitute into, not null.
+ * @param offset the start offset within the builder, must be valid.
+ * @param length the length within the builder to be processed, must be valid.
+ * @return true if altered.
*/
protected boolean substitute(final StrBuilder buf, final int offset, final int length) {
return substitute(buf, offset, length, null) > 0;
}
/**
- * Recursive handler for multiple levels of interpolation. This is the main
- * interpolation method, which resolves the values of all variable references
+ * Recursive handler for multiple levels of interpolation. This is the main interpolation method, which resolves the values of all variable references
* contained in the passed in text.
*
- * @param buf the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @param priorVariables the stack keeping track of the replaced variables, may be null
- * @return The length change that occurs, unless priorVariables is null when the int
- * represents a boolean flag as to whether any change occurred.
+ * @param buf the string builder to substitute into, not null.
+ * @param offset the start offset within the builder, must be valid.
+ * @param length the length within the builder to be processed, must be valid.
+ * @param priorVariables the stack keeping track of the replaced variables, may be null.
+ * @return The length change that occurs, unless priorVariables is null when the int represents a boolean flag as to whether any change occurred.
*/
private int substitute(final StrBuilder buf, final int offset, final int length, List priorVariables) {
final StrMatcher pfxMatcher = getVariablePrefixMatcher();
diff --git a/src/main/java/org/apache/commons/text/StrTokenizer.java b/src/main/java/org/apache/commons/text/StrTokenizer.java
index f6946286b8..9d757234e5 100644
--- a/src/main/java/org/apache/commons/text/StrTokenizer.java
+++ b/src/main/java/org/apache/commons/text/StrTokenizer.java
@@ -87,28 +87,26 @@
public class StrTokenizer implements ListIterator, Cloneable {
/** Comma separated values tokenizer internal variable. */
- private static final StrTokenizer CSV_TOKENIZER_PROTOTYPE;
+ // @formatter:off
+ private static final StrTokenizer CSV_TOKENIZER_PROTOTYPE = new StrTokenizer()
+ .setDelimiterMatcher(StrMatcher.commaMatcher())
+ .setQuoteMatcher(StrMatcher.doubleQuoteMatcher())
+ .setIgnoredMatcher(StrMatcher.noneMatcher())
+ .setTrimmerMatcher(StrMatcher.trimMatcher())
+ .setEmptyTokenAsNull(false)
+ .setIgnoreEmptyTokens(false);
+ // @formatter:on
/** Tab separated values tokenizer internal variable. */
- private static final StrTokenizer TSV_TOKENIZER_PROTOTYPE;
-
- static {
- CSV_TOKENIZER_PROTOTYPE = new StrTokenizer();
- CSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.commaMatcher());
- CSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
- CSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher());
- CSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher());
- CSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
- CSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
-
- TSV_TOKENIZER_PROTOTYPE = new StrTokenizer();
- TSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.tabMatcher());
- TSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
- TSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher());
- TSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher());
- TSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
- TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
- }
+ // @formatter:off
+ private static final StrTokenizer TSV_TOKENIZER_PROTOTYPE = new StrTokenizer()
+ .setDelimiterMatcher(StrMatcher.tabMatcher())
+ .setQuoteMatcher(StrMatcher.doubleQuoteMatcher())
+ .setIgnoredMatcher(StrMatcher.noneMatcher())
+ .setTrimmerMatcher(StrMatcher.trimMatcher())
+ .setEmptyTokenAsNull(false)
+ .setIgnoreEmptyTokens(false);
+ // @formatter:on
/**
* Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}.
@@ -120,27 +118,24 @@ private static StrTokenizer getCSVClone() {
}
/**
- * Gets a new tokenizer instance which parses Comma Separated Value strings
- * initializing it with the given input. The default for CSV processing
- * will be trim whitespace from both ends (which can be overridden with
- * the setTrimmer method).
+ * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. The default for CSV processing will be
+ * trim whitespace from both ends (which can be overridden with the setTrimmer method).
*
* You must call a "reset" method to set the string which you want to parse.
*
- * @return a new tokenizer instance which parses Comma Separated Value strings
+ *
+ * @return a new tokenizer instance which parses Comma Separated Value strings.
*/
public static StrTokenizer getCSVInstance() {
return getCSVClone();
}
/**
- * Gets a new tokenizer instance which parses Comma Separated Value strings
- * initializing it with the given input. The default for CSV processing
- * will be trim whitespace from both ends (which can be overridden with
- * the setTrimmer method).
+ * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. The default for CSV processing will be
+ * trim whitespace from both ends (which can be overridden with the setTrimmer method).
*
- * @param input the text to parse
- * @return a new tokenizer instance which parses Comma Separated Value strings
+ * @param input the text to parse.
+ * @return a new tokenizer instance which parses Comma Separated Value strings.
*/
public static StrTokenizer getCSVInstance(final char[] input) {
final StrTokenizer tok = getCSVClone();
@@ -149,19 +144,18 @@ public static StrTokenizer getCSVInstance(final char[] input) {
}
/**
- * Gets a new tokenizer instance which parses Comma Separated Value strings
- * initializing it with the given input. The default for CSV processing
- * will be trim whitespace from both ends (which can be overridden with
- * the setTrimmer method).
+ * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. The default for CSV processing will be
+ * trim whitespace from both ends (which can be overridden with the setTrimmer method).
*
- * @param input the text to parse
- * @return a new tokenizer instance which parses Comma Separated Value strings
+ * @param input the text to parse.
+ * @return a new tokenizer instance which parses Comma Separated Value strings.
*/
public static StrTokenizer getCSVInstance(final String input) {
final StrTokenizer tok = getCSVClone();
tok.reset(input);
return tok;
}
+
/**
* Returns a clone of {@code TSV_TOKENIZER_PROTOTYPE}.
*
@@ -172,12 +166,12 @@ private static StrTokenizer getTSVClone() {
}
/**
- * Gets a new tokenizer instance which parses Tab Separated Value strings.
- * The default for CSV processing will be trim whitespace from both ends
- * (which can be overridden with the setTrimmer method).
+ * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be trim whitespace from both ends (which can
+ * be overridden with the setTrimmer method).
*
* You must call a "reset" method to set the string which you want to parse.
*
+ *
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StrTokenizer getTSVInstance() {
@@ -185,10 +179,10 @@ public static StrTokenizer getTSVInstance() {
}
/**
- * Gets a new tokenizer instance which parses Tab Separated Value strings.
- * The default for CSV processing will be trim whitespace from both ends
- * (which can be overridden with the setTrimmer method).
- * @param input the string to parse
+ * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be trim whitespace from both ends (which can
+ * be overridden with the setTrimmer method).
+ *
+ * @param input the string to parse.
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StrTokenizer getTSVInstance(final char[] input) {
@@ -198,10 +192,10 @@ public static StrTokenizer getTSVInstance(final char[] input) {
}
/**
- * Gets a new tokenizer instance which parses Tab Separated Value strings.
- * The default for CSV processing will be trim whitespace from both ends
- * (which can be overridden with the setTrimmer method).
- * @param input the string to parse
+ * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be trim whitespace from both ends (which can
+ * be overridden with the setTrimmer method).
+ *
+ * @param input the string to parse.
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StrTokenizer getTSVInstance(final String input) {
@@ -238,8 +232,7 @@ public static StrTokenizer getTSVInstance(final String input) {
private boolean ignoreEmptyTokens = true;
/**
- * Constructs a tokenizer splitting on space, tab, newline and form feed
- * as per StringTokenizer, but with no text to tokenize.
+ * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer, but with no text to tokenize.
*
* This constructor is normally used with {@link #reset(String)}.
*
@@ -252,7 +245,7 @@ public StrTokenizer() {
* Constructs a tokenizer splitting on space, tab, newline and form feed
* as per StringTokenizer.
*
- * @param input the string which is to be parsed, not cloned
+ * @param input the string which is to be parsed, not cloned.
*/
public StrTokenizer(final char[] input) {
if (input == null) {
@@ -265,8 +258,8 @@ public StrTokenizer(final char[] input) {
/**
* Constructs a tokenizer splitting on the specified character.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter character
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter character.
*/
public StrTokenizer(final char[] input, final char delim) {
this(input);
@@ -277,9 +270,9 @@ public StrTokenizer(final char[] input, final char delim) {
* Constructs a tokenizer splitting on the specified delimiter character
* and handling quotes using the specified quote character.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter character
- * @param quote the field quoted string character
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter character.
+ * @param quote the field quoted string character.
*/
public StrTokenizer(final char[] input, final char delim, final char quote) {
this(input, delim);
@@ -289,8 +282,8 @@ public StrTokenizer(final char[] input, final char delim, final char quote) {
/**
* Constructs a tokenizer splitting on the specified string.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter string
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter string.
*/
public StrTokenizer(final char[] input, final String delim) {
this(input);
@@ -300,8 +293,8 @@ public StrTokenizer(final char[] input, final String delim) {
/**
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter matcher
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter matcher.
*/
public StrTokenizer(final char[] input, final StrMatcher delim) {
this(input);
@@ -312,9 +305,9 @@ public StrTokenizer(final char[] input, final StrMatcher delim) {
* Constructs a tokenizer splitting using the specified delimiter matcher
* and handling quotes using the specified quote matcher.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter character
- * @param quote the field quoted string character
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter character.
+ * @param quote the field quoted string character.
*/
public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) {
this(input, delim);
@@ -325,7 +318,7 @@ public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher
* Constructs a tokenizer splitting on space, tab, newline and form feed
* as per StringTokenizer.
*
- * @param input the string which is to be parsed
+ * @param input the string which is to be parsed.
*/
public StrTokenizer(final String input) {
if (input != null) {
@@ -338,8 +331,8 @@ public StrTokenizer(final String input) {
/**
* Constructs a tokenizer splitting on the specified delimiter character.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter character
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter character.
*/
public StrTokenizer(final String input, final char delim) {
this(input);
@@ -350,9 +343,9 @@ public StrTokenizer(final String input, final char delim) {
* Constructs a tokenizer splitting on the specified delimiter character
* and handling quotes using the specified quote character.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter character
- * @param quote the field quoted string character
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter character.
+ * @param quote the field quoted string character.
*/
public StrTokenizer(final String input, final char delim, final char quote) {
this(input, delim);
@@ -362,8 +355,8 @@ public StrTokenizer(final String input, final char delim, final char quote) {
/**
* Constructs a tokenizer splitting on the specified delimiter string.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter string
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter string.
*/
public StrTokenizer(final String input, final String delim) {
this(input);
@@ -373,8 +366,8 @@ public StrTokenizer(final String input, final String delim) {
/**
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter matcher
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter matcher.
*/
public StrTokenizer(final String input, final StrMatcher delim) {
this(input);
@@ -385,9 +378,9 @@ public StrTokenizer(final String input, final StrMatcher delim) {
* Constructs a tokenizer splitting using the specified delimiter matcher
* and handling quotes using the specified quote matcher.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter matcher
- * @param quote the field quoted string matcher
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter matcher.
+ * @param quote the field quoted string matcher.
*/
public StrTokenizer(final String input, final StrMatcher delim, final StrMatcher quote) {
this(input, delim);
@@ -396,8 +389,9 @@ public StrTokenizer(final String input, final StrMatcher delim, final StrMatcher
/**
* Unsupported ListIterator operation.
+ *
* @param obj this parameter ignored.
- * @throws UnsupportedOperationException always
+ * @throws UnsupportedOperationException always.
*/
@Override
public void add(final String obj) {
@@ -407,8 +401,8 @@ public void add(final String obj) {
/**
* Adds a token to a list, paying attention to the parameters we've set.
*
- * @param list the list to add to
- * @param tok the token to add
+ * @param list the list to add to.
+ * @param tok the token to add.
*/
private void addToken(final List list, String tok) {
if (tok == null || tok.isEmpty()) {
@@ -439,9 +433,8 @@ private void checkTokenized() {
}
/**
- * Creates a new instance of this Tokenizer. The new instance is reset so
- * that it will be at the start of the token list.
- * If a {@link CloneNotSupportedException} is caught, return {@code null}.
+ * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token list. If a
+ * {@link CloneNotSupportedException} is caught, return {@code null}.
*
* @return a new instance of this Tokenizer which has been reset.
*/
@@ -455,11 +448,10 @@ public Object clone() {
}
/**
- * Creates a new instance of this Tokenizer. The new instance is reset so that
- * it will be at the start of the token list.
+ * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token list.
*
* @return a new instance of this Tokenizer which has been reset.
- * @throws CloneNotSupportedException if there is a problem cloning
+ * @throws CloneNotSupportedException if there is a problem cloning.
*/
Object cloneReset() throws CloneNotSupportedException {
// this method exists to enable 100% test coverage
@@ -474,7 +466,7 @@ Object cloneReset() throws CloneNotSupportedException {
/**
* Gets the String content that the tokenizer is parsing.
*
- * @return The string content being parsed
+ * @return The string content being parsed.
*/
public String getContent() {
if (chars == null) {
@@ -486,7 +478,7 @@ public String getContent() {
/**
* Gets the field delimiter matcher.
*
- * @return The delimiter matcher in use
+ * @return The delimiter matcher in use.
*/
public StrMatcher getDelimiterMatcher() {
return this.delimMatcher;
@@ -495,12 +487,10 @@ public StrMatcher getDelimiterMatcher() {
/**
* Gets the ignored character matcher.
*
- * These characters are ignored when parsing the String, unless they are
- * within a quoted region.
- * The default value is not to ignore anything.
+ * These characters are ignored when parsing the String, unless they are within a quoted region. The default value is not to ignore anything.
*
*
- * @return The ignored matcher in use
+ * @return The ignored matcher in use.
*/
public StrMatcher getIgnoredMatcher() {
return ignoredMatcher;
@@ -509,12 +499,10 @@ public StrMatcher getIgnoredMatcher() {
/**
* Gets the quote matcher currently in use.
*
- * The quote character is used to wrap data between the tokens.
- * This enables delimiters to be entered as data.
- * The default value is '"' (double quote).
+ * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. The default value is '"' (double quote).
*
*
- * @return The quote matcher in use
+ * @return The quote matcher in use.
*/
public StrMatcher getQuoteMatcher() {
return quoteMatcher;
@@ -523,7 +511,7 @@ public StrMatcher getQuoteMatcher() {
/**
* Gets a copy of the full token list as an independent modifiable array.
*
- * @return The tokens as a String array
+ * @return The tokens as a String array.
*/
public String[] getTokenArray() {
checkTokenized();
@@ -533,7 +521,7 @@ public String[] getTokenArray() {
/**
* Gets a copy of the full token list as an independent modifiable list.
*
- * @return The tokens as a String array
+ * @return The tokens as a String array.
*/
public List getTokenList() {
checkTokenized();
@@ -546,12 +534,10 @@ public List getTokenList() {
/**
* Gets the trimmer character matcher.
*
- * These characters are trimmed off on each side of the delimiter
- * until the token or quote is found.
- * The default value is not to trim anything.
+ * These characters are trimmed off on each side of the delimiter until the token or quote is found. The default value is not to trim anything.
*
*
- * @return The trimmer matcher in use
+ * @return The trimmer matcher in use.
*/
public StrMatcher getTrimmerMatcher() {
return trimmerMatcher;
@@ -560,7 +546,7 @@ public StrMatcher getTrimmerMatcher() {
/**
* Checks whether there are any more tokens.
*
- * @return true if there are more tokens
+ * @return true if there are more tokens.
*/
@Override
public boolean hasNext() {
@@ -571,7 +557,7 @@ public boolean hasNext() {
/**
* Checks whether there are any previous tokens that can be iterated to.
*
- * @return true if there are previous tokens
+ * @return true if there are previous tokens.
*/
@Override
public boolean hasPrevious() {
@@ -583,7 +569,7 @@ public boolean hasPrevious() {
* Gets whether the tokenizer currently returns empty tokens as null.
* The default for this property is false.
*
- * @return true if empty tokens are returned as null
+ * @return true if empty tokens are returned as null.
*/
public boolean isEmptyTokenAsNull() {
return this.emptyAsNull;
@@ -593,7 +579,7 @@ public boolean isEmptyTokenAsNull() {
* Gets whether the tokenizer currently ignores empty tokens.
* The default for this property is true.
*
- * @return true if empty tokens are not returned
+ * @return true if empty tokens are not returned.
*/
public boolean isIgnoreEmptyTokens() {
return ignoreEmptyTokens;
@@ -603,12 +589,12 @@ public boolean isIgnoreEmptyTokens() {
* Checks if the characters at the index specified match the quote
* already matched in readNextToken().
*
- * @param srcChars the character array being tokenized
- * @param pos the position to check for a quote
- * @param len the length of the character array being tokenized
- * @param quoteStart the start position of the matched quote, 0 if no quoting
- * @param quoteLen the length of the matched quote, 0 if no quoting
- * @return true if a quote is matched
+ * @param srcChars the character array being tokenized.
+ * @param pos the position to check for a quote.
+ * @param len the length of the character array being tokenized.
+ * @param quoteStart the start position of the matched quote, 0 if no quoting.
+ * @param quoteLen the length of the matched quote, 0 if no quoting.
+ * @return true if a quote is matched.
*/
private boolean isQuote(final char[] srcChars,
final int pos,
@@ -626,8 +612,8 @@ private boolean isQuote(final char[] srcChars,
/**
* Gets the next token.
*
- * @return The next String token
- * @throws NoSuchElementException if there are no more elements
+ * @return The next String token.
+ * @throws NoSuchElementException if there are no more elements.
*/
@Override
public String next() {
@@ -640,7 +626,7 @@ public String next() {
/**
* Gets the index of the next token to return.
*
- * @return The next token index
+ * @return The next token index.
*/
@Override
public int nextIndex() {
@@ -648,11 +634,10 @@ public int nextIndex() {
}
/**
- * Gets the next token from the String.
- * Equivalent to {@link #next()} except it returns null rather than
- * throwing {@link NoSuchElementException} when no tokens remain.
+ * Gets the next token from the String. Equivalent to {@link #next()} except it returns null rather than throwing {@link NoSuchElementException} when no
+ * tokens remain.
*
- * @return The next sequential token, or null when no more tokens are found
+ * @return The next sequential token, or null when no more tokens are found.
*/
public String nextToken() {
if (hasNext()) {
@@ -664,7 +649,7 @@ public String nextToken() {
/**
* Gets the token previous to the last returned token.
*
- * @return The previous token
+ * @return The previous token.
*/
@Override
public String previous() {
@@ -677,7 +662,7 @@ public String previous() {
/**
* Gets the index of the previous token.
*
- * @return The previous token index
+ * @return The previous token index.
*/
@Override
public int previousIndex() {
@@ -687,7 +672,7 @@ public int previousIndex() {
/**
* Gets the previous token from the String.
*
- * @return The previous sequential token, or null when no more tokens are found
+ * @return The previous sequential token, or null when no more tokens are found.
*/
public String previousToken() {
if (hasPrevious()) {
@@ -699,13 +684,12 @@ public String previousToken() {
/**
* Reads character by character through the String to get the next token.
*
- * @param srcChars the character array being tokenized
- * @param start the first character of field
- * @param len the length of the character array being tokenized
- * @param workArea a temporary work area
- * @param tokenList the list of parsed tokens
- * @return The starting position of the next field (the character
- * immediately after the delimiter), or -1 if end of string found
+ * @param srcChars the character array being tokenized.
+ * @param start the first character of field.
+ * @param len the length of the character array being tokenized.
+ * @param workArea a temporary work area.
+ * @param tokenList the list of parsed tokens.
+ * @return The starting position of the next field (the character immediately after the delimiter), or -1 if end of string found.
*/
private int readNextToken(final char[] srcChars,
int start,
@@ -750,16 +734,14 @@ private int readNextToken(final char[] srcChars,
/**
* Reads a possibly quoted string token.
*
- * @param srcChars the character array being tokenized
- * @param start the first character of field
- * @param len the length of the character array being tokenized
- * @param workArea a temporary work area
- * @param tokenList the list of parsed tokens
- * @param quoteStart the start position of the matched quote, 0 if no quoting
- * @param quoteLen the length of the matched quote, 0 if no quoting
- * @return The starting position of the next field (the character
- * immediately after the delimiter, or if end of string found,
- * then the length of string
+ * @param srcChars the character array being tokenized.
+ * @param start the first character of field.
+ * @param len the length of the character array being tokenized.
+ * @param workArea a temporary work area.
+ * @param tokenList the list of parsed tokens.
+ * @param quoteStart the start position of the matched quote, 0 if no quoting.
+ * @param quoteLen the length of the matched quote, 0 if no quoting.
+ * @return The starting position of the next field (the character immediately after the delimiter, or if end of string found, then the length of string.
*/
private int readWithQuotes(final char[] srcChars, final int start, final int len, final StrBuilder workArea,
final List tokenList, final int quoteStart, final int quoteLen) {
@@ -845,7 +827,7 @@ private int readWithQuotes(final char[] srcChars, final int start, final int len
/**
* Unsupported ListIterator operation.
*
- * @throws UnsupportedOperationException always
+ * @throws UnsupportedOperationException always.
*/
@Override
public void remove() {
@@ -856,8 +838,9 @@ public void remove() {
* Resets this tokenizer, forgetting all parsing and iteration already completed.
*
* This method allows the same tokenizer to be reused for the same String.
+ *
*
- * @return this, to enable chaining
+ * @return {@code this} instance.
*/
public StrTokenizer reset() {
tokenPos = 0;
@@ -866,12 +849,10 @@ public StrTokenizer reset() {
}
/**
- * Reset this tokenizer, giving it a new input string to parse.
- * In this manner you can re-use a tokenizer with the same settings
- * on multiple input lines.
+ * Reset this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the same settings on multiple input lines.
*
- * @param input the new character array to tokenize, not cloned, null sets no text to parse
- * @return this, to enable chaining
+ * @param input the new character array to tokenize, not cloned, null sets no text to parse.
+ * @return {@code this} instance.
*/
public StrTokenizer reset(final char[] input) {
reset();
@@ -884,12 +865,10 @@ public StrTokenizer reset(final char[] input) {
}
/**
- * Reset this tokenizer, giving it a new input string to parse.
- * In this manner you can re-use a tokenizer with the same settings
- * on multiple input lines.
+ * Reset this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the same settings on multiple input lines.
*
- * @param input the new string to tokenize, null sets no text to parse
- * @return this, to enable chaining
+ * @param input the new string to tokenize, null sets no text to parse.
+ * @return {@code this} instance.
*/
public StrTokenizer reset(final String input) {
reset();
@@ -903,8 +882,9 @@ public StrTokenizer reset(final String input) {
/**
* Unsupported ListIterator operation.
+ *
* @param obj this parameter ignored.
- * @throws UnsupportedOperationException always
+ * @throws UnsupportedOperationException Always thrown.
*/
@Override
public void set(final String obj) {
@@ -914,8 +894,8 @@ public void set(final String obj) {
/**
* Sets the field delimiter character.
*
- * @param delim the delimiter character to use
- * @return this, to enable chaining
+ * @param delim the delimiter character to use.
+ * @return {@code this} instance.
*/
public StrTokenizer setDelimiterChar(final char delim) {
return setDelimiterMatcher(StrMatcher.charMatcher(delim));
@@ -927,8 +907,8 @@ public StrTokenizer setDelimiterChar(final char delim) {
* The delimiter is used to separate one token from another.
*
*
- * @param delim the delimiter matcher to use
- * @return this, to enable chaining
+ * @param delim the delimiter matcher to use.
+ * @return {@code this} instance.
*/
public StrTokenizer setDelimiterMatcher(final StrMatcher delim) {
if (delim == null) {
@@ -942,19 +922,18 @@ public StrTokenizer setDelimiterMatcher(final StrMatcher delim) {
/**
* Sets the field delimiter string.
*
- * @param delim the delimiter string to use
- * @return this, to enable chaining
+ * @param delim the delimiter string to use.
+ * @return {@code this} instance.
*/
public StrTokenizer setDelimiterString(final String delim) {
return setDelimiterMatcher(StrMatcher.stringMatcher(delim));
}
/**
- * Sets whether the tokenizer should return empty tokens as null.
- * The default for this property is false.
+ * Sets whether the tokenizer should return empty tokens as null. The default for this property is false.
*
- * @param emptyAsNull whether empty tokens are returned as null
- * @return this, to enable chaining
+ * @param emptyAsNull whether empty tokens are returned as null.
+ * @return {@code this} instance.
*/
public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
this.emptyAsNull = emptyAsNull;
@@ -964,12 +943,11 @@ public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
/**
* Sets the character to ignore.
*
- * This character is ignored when parsing the String, unless it is
- * within a quoted region.
+ * This character is ignored when parsing the String, unless it is within a quoted region.
*
*
- * @param ignored the ignored character to use
- * @return this, to enable chaining
+ * @param ignored the ignored character to use.
+ * @return {@code this} instance.
*/
public StrTokenizer setIgnoredChar(final char ignored) {
return setIgnoredMatcher(StrMatcher.charMatcher(ignored));
@@ -978,12 +956,11 @@ public StrTokenizer setIgnoredChar(final char ignored) {
/**
* Sets the matcher for characters to ignore.
*
- * These characters are ignored when parsing the String, unless they are
- * within a quoted region.
+ * These characters are ignored when parsing the String, unless they are within a quoted region.
*
*
- * @param ignored the ignored matcher to use, null ignored
- * @return this, to enable chaining
+ * @param ignored the ignored matcher to use, null ignored.
+ * @return {@code this} instance.
*/
public StrTokenizer setIgnoredMatcher(final StrMatcher ignored) {
if (ignored != null) {
@@ -993,11 +970,10 @@ public StrTokenizer setIgnoredMatcher(final StrMatcher ignored) {
}
/**
- * Sets whether the tokenizer should ignore and not return empty tokens.
- * The default for this property is true.
+ * Sets whether the tokenizer should ignore and not return empty tokens. The default for this property is true.
*
- * @param ignoreEmptyTokens whether empty tokens are not returned
- * @return this, to enable chaining
+ * @param ignoreEmptyTokens whether empty tokens are not returned.
+ * @return {@code this} instance.
*/
public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
this.ignoreEmptyTokens = ignoreEmptyTokens;
@@ -1007,12 +983,11 @@ public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
/**
* Sets the quote character to use.
*
- * The quote character is used to wrap data between the tokens.
- * This enables delimiters to be entered as data.
+ * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
*
*
- * @param quote the quote character to use
- * @return this, to enable chaining
+ * @param quote the quote character to use.
+ * @return {@code this} instance.
*/
public StrTokenizer setQuoteChar(final char quote) {
return setQuoteMatcher(StrMatcher.charMatcher(quote));
@@ -1021,12 +996,11 @@ public StrTokenizer setQuoteChar(final char quote) {
/**
* Sets the quote matcher to use.
*
- * The quote character is used to wrap data between the tokens.
- * This enables delimiters to be entered as data.
+ * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
*
*
- * @param quote the quote matcher to use, null ignored
- * @return this, to enable chaining
+ * @param quote the quote matcher to use, null ignored.
+ * @return {@code this} instance.
*/
public StrTokenizer setQuoteMatcher(final StrMatcher quote) {
if (quote != null) {
@@ -1038,12 +1012,11 @@ public StrTokenizer setQuoteMatcher(final StrMatcher quote) {
/**
* Sets the matcher for characters to trim.
*
- * These characters are trimmed off on each side of the delimiter
- * until the token or quote is found.
+ * These characters are trimmed off on each side of the delimiter until the token or quote is found.
*
*
- * @param trimmer the trimmer matcher to use, null ignored
- * @return this, to enable chaining
+ * @param trimmer the trimmer matcher to use, null ignored
+ * @return {@code this} instance.
*/
public StrTokenizer setTrimmerMatcher(final StrMatcher trimmer) {
if (trimmer != null) {
@@ -1055,7 +1028,7 @@ public StrTokenizer setTrimmerMatcher(final StrMatcher trimmer) {
/**
* Gets the number of tokens found in the String.
*
- * @return The number of matched tokens
+ * @return The number of matched tokens.
*/
public int size() {
checkTokenized();
@@ -1065,25 +1038,21 @@ public int size() {
/**
* Internal method to performs the tokenization.
*
- * Most users of this class do not need to call this method. This method
- * will be called automatically by other (public) methods when required.
+ * Most users of this class do not need to call this method. This method will be called automatically by other (public) methods when required.
*
*
- * This method exists to allow subclasses to add code before or after the
- * tokenization. For example, a subclass could alter the character array,
- * offset or count to be parsed, or call the tokenizer multiple times on
- * multiple strings. It is also be possible to filter the results.
+ * This method exists to allow subclasses to add code before or after the tokenization. For example, a subclass could alter the character array, offset or
+ * count to be parsed, or call the tokenizer multiple times on multiple strings. It is also be possible to filter the results.
*
*
- * {@code StrTokenizer} will always pass a zero offset and a count
- * equal to the length of the array to this method, however a subclass
- * may pass other values, or even an entirely different array.
+ * {@code StrTokenizer} will always pass a zero offset and a count equal to the length of the array to this method, however a subclass may pass other
+ * values, or even an entirely different array.
*
*
- * @param srcChars the character array being tokenized, may be null
- * @param offset the start position within the character array, must be valid
- * @param count the number of characters to tokenize, must be valid
- * @return The modifiable list of String tokens, unmodifiable if null array or zero count
+ * @param srcChars the character array being tokenized, may be null.
+ * @param offset the start position within the character array, must be valid.
+ * @param count the number of characters to tokenize, must be valid.
+ * @return The modifiable list of String tokens, unmodifiable if null array or zero count.
*/
protected List tokenize(final char[] srcChars, final int offset, final int count) {
if (srcChars == null || count == 0) {
@@ -1109,7 +1078,7 @@ protected List tokenize(final char[] srcChars, final int offset, final i
/**
* Gets the String content that the tokenizer is parsing.
*
- * @return The string content being parsed
+ * @return The string content being parsed.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/text/StringEscapeUtils.java b/src/main/java/org/apache/commons/text/StringEscapeUtils.java
index dae5c48ec6..700ca95690 100644
--- a/src/main/java/org/apache/commons/text/StringEscapeUtils.java
+++ b/src/main/java/org/apache/commons/text/StringEscapeUtils.java
@@ -122,6 +122,7 @@ public String toString() {
return sb.toString();
}
}
+
/**
* Translator object for unescaping backslash escaped entries.
*/
@@ -165,9 +166,8 @@ public int translate(final CharSequence input, final int index, final Writer wri
/**
* Translator object for escaping Java.
*
- * While {@link #escapeJava(String)} is the expected method of use, this
- * object allows the Java escaping functionality to be used
- * as the foundation for a custom translator.
+ * While {@link #escapeJava(String)} is the expected method of use, this object allows the Java escaping functionality to be used as the foundation for a
+ * custom translator.
*/
public static final CharSequenceTranslator ESCAPE_JAVA;
static {
@@ -184,9 +184,8 @@ public int translate(final CharSequence input, final int index, final Writer wri
/**
* Translator object for escaping EcmaScript/JavaScript.
*
- * While {@link #escapeEcmaScript(String)} is the expected method of use, this
- * object allows the EcmaScript escaping functionality to be used
- * as the foundation for a custom translator.
+ * While {@link #escapeEcmaScript(String)} is the expected method of use, this object allows the EcmaScript escaping functionality to be used as the
+ * foundation for a custom translator.
*/
public static final CharSequenceTranslator ESCAPE_ECMASCRIPT;
static {
@@ -205,9 +204,8 @@ public int translate(final CharSequence input, final int index, final Writer wri
/**
* Translator object for escaping Json.
*
- * While {@link #escapeJson(String)} is the expected method of use, this
- * object allows the Json escaping functionality to be used
- * as the foundation for a custom translator.
+ * While {@link #escapeJson(String)} is the expected method of use, this object allows the Json escaping functionality to be used as the foundation for a
+ * custom translator.
*/
public static final CharSequenceTranslator ESCAPE_JSON;
static {
@@ -225,9 +223,8 @@ public int translate(final CharSequence input, final int index, final Writer wri
/**
* Translator object for escaping XML 1.0.
*
- * While {@link #escapeXml10(String)} is the expected method of use, this
- * object allows the XML escaping functionality to be used
- * as the foundation for a custom translator.
+ * While {@link #escapeXml10(String)} is the expected method of use, this object allows the XML escaping functionality to be used as the foundation for a
+ * custom translator.
*/
public static final CharSequenceTranslator ESCAPE_XML10;
static {
@@ -327,6 +324,7 @@ public int translate(final CharSequence input, final int index, final Writer wri
new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE),
new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE)
);
+
/**
* Translator object for escaping individual Comma Separated Values.
*
@@ -480,7 +478,8 @@ public int translate(final CharSequence input, final int index, final Writer wri
/**
* Gets a {@link Builder}.
- * @param translator the text translator
+ *
+ * @param translator the text translator.
* @return {@link Builder}
*/
public static StringEscapeUtils.Builder builder(final CharSequenceTranslator translator) {
@@ -488,23 +487,25 @@ public static StringEscapeUtils.Builder builder(final CharSequenceTranslator tra
}
/**
- * Returns a {@code String} value for a CSV column enclosed in double quotes,
- * if required.
- *
- *
If the value contains a comma, newline or double quote, then the
- * String value is returned enclosed in double quotes.
+ * Returns a {@code String} value for a CSV column enclosed in double quotes, if required.
*
- *
Any double quote characters in the value are escaped with another double quote.
+ *
+ * If the value contains a comma, newline or double quote, then the String value is returned enclosed in double quotes.
+ *
*
- *
If the value does not contain a comma, newline or double quote, then the
- * String value is returned unchanged.
+ *
+ * Any double quote characters in the value are escaped with another double quote.
+ *
*
- * @param input the input CSV column String, may be null
- * @return The input String, enclosed in double quotes if the value contains a comma,
- * newline or double quote, {@code null} if null string input
+ * @param input the input CSV column String, may be null.
+ * @return The input String, enclosed in double quotes if the value contains a comma, newline or double quote, {@code null} if null string input.
*/
public static String escapeCsv(final String input) {
return ESCAPE_CSV.translate(input);
@@ -513,32 +514,39 @@ public static String escapeCsv(final String input) {
/**
* Escapes the characters in a {@code String} using EcmaScript String rules.
*
- *
Escapes any values it finds into their EcmaScript String form.
- * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
+ *
+ * Escapes any values it finds into their EcmaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
+ *
*
- *
So a tab becomes the characters {@code '\\'} and
- * {@code 't'}.
+ *
+ * So a tab becomes the characters {@code '\\'} and {@code 't'}.
+ *
*
- *
The only difference between Java strings and EcmaScript strings
- * is that in EcmaScript, a single quote and forward-slash (/) are escaped.
+ *
+ * The only difference between Java strings and EcmaScript strings is that in EcmaScript, a single quote and forward-slash (/) are escaped.
+ *
*
- *
Note that EcmaScript is best known by the JavaScript and ActionScript dialects.
+ *
+ * Note that EcmaScript is best known by the JavaScript and ActionScript dialects.
+ *
+ *
+ *
+ * Example:
+ *
*
- *
Example:
*
* input string: He didn't say, "Stop!"
* output string: He didn\'t say, \"Stop!\"
*
+ *
+ * Security Note. We only provide backslash escaping in this method. For example, {@code '\"'} has the output {@code '\\\"'} which could
+ * result in potential issues in the case where the string being escaped is being used in an HTML tag like {@code }. If you wish
+ * to have more rigorous string escaping, you may consider the ESAPI
+ * Libraries. Further, you can view the ESAPI GitHub Org.
+ *
*
- * Security Note. We only provide backslash escaping in this method. For example, {@code '\"'} has the output
- * {@code '\\\"'} which could result in potential issues in the case where the string being escaped is being used
- * in an HTML tag like {@code }. If you wish to have more rigorous string escaping, you
- * may consider the
- * ESAPI Libraries.
- * Further, you can view the ESAPI GitHub Org.
- *
- * @param input String to escape values in, may be null
- * @return String with escaped values, {@code null} if null string input
+ * @param input String to escape values in, may be null.
+ * @return String with escaped values, {@code null} if null string input.
*/
public static String escapeEcmaScript(final String input) {
return ESCAPE_ECMASCRIPT.translate(input);
@@ -549,14 +557,13 @@ public static String escapeEcmaScript(final String input) {
*
*
Supports only the HTML 3.0 entities.
*
- * @param input the {@code String} to escape, may be null
- * @return a new escaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to escape, may be null.
+ * @return a new escaped {@code String}, {@code null} if null string input.
*/
public static String escapeHtml3(final String input) {
return ESCAPE_HTML3.translate(input);
}
- // HTML and XML
/**
* Escapes the characters in a {@code String} using HTML entities.
*
@@ -573,38 +580,44 @@ public static String escapeHtml3(final String input) {
* Note that the commonly used apostrophe escape character (')
* is not a legal entity and so is not supported).
*
- * @param input the {@code String} to escape, may be null
- * @return a new escaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to escape, may be null.
+ * @return a new escaped {@code String}, {@code null} if null string input.
* @see ISO Entities
- * @see HTML 3.2 Character Entities for ISO Latin-1
- * @see HTML 4.0 Character entity references
- * @see HTML 4.01 Character References
- * @see HTML 4.01 Code positions
+ * @see HTML 3.2 Character Entities for ISO Latin-1
+ * @see HTML 4.0 Character entity references
+ * @see HTML 4.01 Character References
+ * @see HTML 4.01 Code positions
*/
public static String escapeHtml4(final String input) {
return ESCAPE_HTML4.translate(input);
}
- // Java and JavaScript
/**
* Escapes the characters in a {@code String} using Java String rules.
*
- *
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
+ *
+ * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
+ *
*
- *
So a tab becomes the characters {@code '\\'} and
- * {@code 't'}.
+ *
+ * So a tab becomes the characters {@code '\\'} and {@code 't'}.
+ *
*
- *
The only difference between Java strings and JavaScript strings
- * is that in JavaScript, a single quote and forward-slash (/) are escaped.
+ *
+ * The only difference between Java strings and JavaScript strings is that in JavaScript, a single quote and forward-slash (/) are escaped.
+ *
+ *
+ *
+ * Example:
+ *
*
- *
Example:
*
* input string: He didn't say, "Stop!"
* output string: He didn't say, \"Stop!\"
*
*
- * @param input String to escape values in, may be null
- * @return String with escaped values, {@code null} if null string input
+ * @param input String to escape values in, may be null.
+ * @return String with escaped values, {@code null} if null string input.
*/
public static String escapeJava(final String input) {
return ESCAPE_JAVA.translate(input);
@@ -613,25 +626,33 @@ public static String escapeJava(final String input) {
/**
* Escapes the characters in a {@code String} using Json String rules.
*
- *
Escapes any values it finds into their Json String form.
- * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
+ *
+ * Escapes any values it finds into their Json String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
+ *
*
- *
So a tab becomes the characters {@code '\\'} and
- * {@code 't'}.
+ *
+ * So a tab becomes the characters {@code '\\'} and {@code 't'}.
+ *
*
- *
The only difference between Java strings and Json strings
- * is that in Json, forward-slash (/) is escaped.
+ *
+ * The only difference between Java strings and Json strings is that in Json, forward-slash (/) is escaped.
+ *
*
- *
See http://www.ietf.org/rfc/rfc4627.txt for further details.
+ *
+ * See http://www.ietf.org/rfc/rfc4627.txt for further details.
+ *
+ *
+ *
+ * Example:
+ *
*
- *
Example:
*
* input string: He didn't say, "Stop!"
* output string: He didn't say, \"Stop!\"
*
*
- * @param input String to escape values in, may be null
- * @return String with escaped values, {@code null} if null string input
+ * @param input String to escape values in, may be null.
+ * @return String with escaped values, {@code null} if null string input.
*/
public static String escapeJson(final String input) {
return ESCAPE_JSON.translate(input);
@@ -640,28 +661,34 @@ public static String escapeJson(final String input) {
/**
* Escapes the characters in a {@code String} using XML entities.
*
- *
Note that XML 1.0 is a text-only format: it cannot represent control
- * characters or unpaired Unicode surrogate code points, even after escaping.
- * {@code escapeXml10} will remove characters that do not fit in the
- * following ranges:
+ *
+ * Note that XML 1.0 is a text-only format: it cannot represent control characters or unpaired Unicode surrogate code points, even after escaping.
+ * {@code escapeXml10} will remove characters that do not fit in the following ranges:
+ *
Though not strictly necessary, {@code escapeXml10} will escape
- * characters in the following ranges:
+ *
+ * Though not strictly necessary, {@code escapeXml10} will escape characters in the following ranges:
+ *
*
- *
{@code [#x7F-#x84] | [#x86-#x9F]}
+ *
+ * {@code [#x7F-#x84] | [#x86-#x9F]}
+ *
*
- *
The returned string can be inserted into a valid XML 1.0 or XML 1.1
- * document. If you want to allow more non-text characters in an XML 1.1
- * document, use {@link #escapeXml11(String)}.
+ *
+ * The returned string can be inserted into a valid XML 1.0 or XML 1.1 document. If you want to allow more non-text characters in an XML 1.1 document, use
+ * {@link #escapeXml11(String)}.
+ *
*
- * @param input the {@code String} to escape, may be null
- * @return a new escaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to escape, may be null.
+ * @return a new escaped {@code String}, {@code null} if null string input.
* @see #unescapeXml(String)
*/
public static String escapeXml10(final String input) {
@@ -671,26 +698,33 @@ public static String escapeXml10(final String input) {
/**
* Escapes the characters in a {@code String} using XML entities.
*
- *
XML 1.1 can represent certain control characters, but it cannot represent
- * the null byte or unpaired Unicode surrogate code points, even after escaping.
- * {@code escapeXml11} will remove characters that do not fit in the following
- * ranges:
+ *
+ * XML 1.1 can represent certain control characters, but it cannot represent the null byte or unpaired Unicode surrogate code points, even after escaping.
+ * {@code escapeXml11} will remove characters that do not fit in the following ranges:
+ *
The returned string can be inserted into a valid XML 1.1 document. Do not
- * use it for XML 1.0 documents.
+ *
+ * The returned string can be inserted into a valid XML 1.1 document. Do not use it for XML 1.0 documents.
+ *
*
- * @param input the {@code String} to escape, may be null
- * @return a new escaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to escape, may be null.
+ * @return a new escaped {@code String}, {@code null} if null string input.
* @see #unescapeXml(String)
*/
public static String escapeXml11(final String input) {
@@ -700,19 +734,23 @@ public static String escapeXml11(final String input) {
/**
* Escapes the characters in a {@code String} using XSI rules.
*
- *
Beware! In most cases you don't want to escape shell commands but use multi-argument
- * methods provided by {@link ProcessBuilder} or {@link Runtime#exec(String[])}
- * instead.
+ *
+ * Beware! In most cases you don't want to escape shell commands but use multi-argument methods provided by {@link ProcessBuilder} or
+ * {@link Runtime#exec(String[])} instead.
+ *
*
+ * @param input String to escape values in, may be null.
+ * @return String with escaped values, {@code null} if null string input.
* @see Shell Command Language
- * @param input String to escape values in, may be null
- * @return String with escaped values, {@code null} if null string input
*/
public static String escapeXSI(final String input) {
return ESCAPE_XSI.translate(input);
@@ -721,22 +759,22 @@ public static String escapeXSI(final String input) {
/**
* Returns a {@code String} value for an unescaped CSV column.
*
- *
If the value is enclosed in double quotes, and contains a comma, newline
- * or double quote, then quotes are removed.
+ *
+ * If the value is enclosed in double quotes, and contains a comma, newline or double quote, then quotes are removed.
*
*
- *
Any double quote escaped characters (a pair of double quotes) are unescaped
- * to just one double quote.
+ *
+ * Any double quote escaped characters (a pair of double quotes) are unescaped to just one double quote.
+ *
*
- *
If the value is not enclosed in double quotes, or is and does not contain a
- * comma, newline or double quote, then the String value is returned unchanged.
+ *
+ * If the value is not enclosed in double quotes, or is and does not contain a comma, newline or double quote, then the String value is returned unchanged.
+ *
*
- * see Wikipedia and
- * RFC 4180.
+ * see Wikipedia and RFC 4180.
*
- * @param input the input CSV column String, may be null
- * @return The input String, with enclosing double quotes removed and embedded double
- * quotes unescaped, {@code null} if null string input
+ * @param input the input CSV column String, may be null.
+ * @return The input String, with enclosing double quotes removed and embedded double quotes unescaped, {@code null} if null string input.
*/
public static String unescapeCsv(final String input) {
return UNESCAPE_CSV.translate(input);
@@ -745,57 +783,54 @@ public static String unescapeCsv(final String input) {
/**
* Unescapes any EcmaScript literals found in the {@code String}.
*
- *
For example, it will turn a sequence of {@code '\'} and {@code 'n'}
- * into a newline character, unless the {@code '\'} is preceded by another
- * {@code '\'}.
+ *
+ * For example, it will turn a sequence of {@code '\'} and {@code 'n'} into a newline character, unless the {@code '\'} is preceded by another {@code '\'}.
+ *
*
+ * @param input the {@code String} to unescape, may be null.
+ * @return A new unescaped {@code String}, {@code null} if null string input.
* @see #unescapeJava(String)
- * @param input the {@code String} to unescape, may be null
- * @return A new unescaped {@code String}, {@code null} if null string input
*/
public static String unescapeEcmaScript(final String input) {
return UNESCAPE_ECMASCRIPT.translate(input);
}
/**
- * Unescapes a string containing entity escapes to a string
- * containing the actual Unicode characters corresponding to the
- * escapes. Supports only HTML 3.0 entities.
+ * Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes. Supports only HTML 3.0
+ * entities.
*
- * @param input the {@code String} to unescape, may be null
- * @return a new unescaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to unescape, may be null.
+ * @return a new unescaped {@code String}, {@code null} if null string input.
*/
public static String unescapeHtml3(final String input) {
return UNESCAPE_HTML3.translate(input);
}
/**
- * Unescapes a string containing entity escapes to a string
- * containing the actual Unicode characters corresponding to the
- * escapes. Supports HTML 4.0 entities.
+ * Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes. Supports HTML 4.0
+ * entities.
*
- *
For example, the string {@code "<Français>"}
- * will become {@code ""}
+ *
+ * For example, the string {@code "<Français>"} will become {@code ""}
+ *
*
- *
If an entity is unrecognized, it is left alone, and inserted
- * verbatim into the result string. e.g. {@code ">&zzzz;x"} will
- * become {@code ">&zzzz;x"}.
+ *
+ * If an entity is unrecognized, it is left alone, and inserted verbatim into the result string. e.g. {@code ">&zzzz;x"} will become {@code ">&zzzz;x"}.
+ *
*
- * @param input the {@code String} to unescape, may be null
- * @return a new unescaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to unescape, may be null.
+ * @return a new unescaped {@code String}, {@code null} if null string input.
*/
public static String unescapeHtml4(final String input) {
return UNESCAPE_HTML4.translate(input);
}
/**
- * Unescapes any Java literals found in the {@code String}.
- * For example, it will turn a sequence of {@code '\'} and
- * {@code 'n'} into a newline character, unless the {@code '\'}
- * is preceded by another {@code '\'}.
+ * Unescapes any Java literals found in the {@code String}. For example, it will turn a sequence of {@code '\'} and {@code 'n'} into a newline character,
+ * unless the {@code '\'} is preceded by another {@code '\'}.
*
- * @param input the {@code String} to unescape, may be null
- * @return a new unescaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to unescape, may be null.
+ * @return a new unescaped {@code String}, {@code null} if null string input.
*/
public static String unescapeJava(final String input) {
return UNESCAPE_JAVA.translate(input);
@@ -804,31 +839,31 @@ public static String unescapeJava(final String input) {
/**
* Unescapes any Json literals found in the {@code String}.
*
- *
For example, it will turn a sequence of {@code '\'} and {@code 'n'}
- * into a newline character, unless the {@code '\'} is preceded by another
- * {@code '\'}.
+ *
+ * For example, it will turn a sequence of {@code '\'} and {@code 'n'} into a newline character, unless the {@code '\'} is preceded by another {@code '\'}.
+ *
*
+ * @param input the {@code String} to unescape, may be null.
+ * @return A new unescaped {@code String}, {@code null} if null string input.
* @see #unescapeJava(String)
- * @param input the {@code String} to unescape, may be null
- * @return A new unescaped {@code String}, {@code null} if null string input
*/
public static String unescapeJson(final String input) {
return UNESCAPE_JSON.translate(input);
}
/**
- * Unescapes a string containing XML entity escapes to a string
- * containing the actual Unicode characters corresponding to the
- * escapes.
+ * Unescapes a string containing XML entity escapes to a string containing the actual Unicode characters corresponding to the escapes.
*
- *
Supports only the five basic XML entities (gt, lt, quot, amp, apos).
- * Does not support DTDs or external entities.
+ *
+ * Supports only the five basic XML entities (gt, lt, quot, amp, apos). Does not support DTDs or external entities.
+ *
*
- *
Note that numerical \\u Unicode codes are unescaped to their respective
- * Unicode characters. This may change in future releases.
+ *
+ * Note that numerical \\u Unicode codes are unescaped to their respective Unicode characters. This may change in future releases.
+ *
*
- * @param input the {@code String} to unescape, may be null
- * @return a new unescaped {@code String}, {@code null} if null string input
+ * @param input the {@code String} to unescape, may be null.
+ * @return a new unescaped {@code String}, {@code null} if null string input.
* @see #escapeXml10(String)
* @see #escapeXml11(String)
*/
@@ -839,23 +874,28 @@ public static String unescapeXml(final String input) {
/**
* Unescapes the characters in a {@code String} using XSI rules.
*
+ * @param input the {@code String} to unescape, may be null.
+ * @return a new unescaped {@code String}, {@code null} if null string input.
* @see StringEscapeUtils#escapeXSI(String)
- * @param input the {@code String} to unescape, may be null
- * @return a new unescaped {@code String}, {@code null} if null string input
*/
public static String unescapeXSI(final String input) {
return UNESCAPE_XSI.translate(input);
}
/**
- * {@code StringEscapeUtils} instances should NOT be constructed in
- * standard programming.
+ * {@code StringEscapeUtils} instances should NOT be constructed in standard programming.
*
- *
Instead, the class should be used as:
- *
StringEscapeUtils.escapeJava("foo");
+ *
+ * Instead, the class should be used as:
+ *
+ *
+ *
+ * StringEscapeUtils.escapeJava("foo");
+ *
*
- *
This constructor is public to permit tools that require a JavaBean
- * instance to operate.
+ *
+ * This constructor is public to permit tools that require a JavaBean instance to operate.
+ *
*/
public StringEscapeUtils() {
}
diff --git a/src/main/java/org/apache/commons/text/StringSubstitutor.java b/src/main/java/org/apache/commons/text/StringSubstitutor.java
index 601419153d..3667e91529 100644
--- a/src/main/java/org/apache/commons/text/StringSubstitutor.java
+++ b/src/main/java/org/apache/commons/text/StringSubstitutor.java
@@ -434,8 +434,7 @@ public static String replace(final Object source, final Properties valueProperti
if (valueProperties == null) {
return source.toString();
}
- return StringSubstitutor.replace(source,
- valueProperties.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), valueProperties::getProperty)));
+ return replace(source, valueProperties.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), valueProperties::getProperty)));
}
/**
@@ -506,8 +505,8 @@ public StringSubstitutor() {
* Constructs a new initialized instance. Uses defaults for variable prefix and suffix and the escaping
* character.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
*/
public StringSubstitutor(final Map valueMap) {
this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
@@ -516,11 +515,11 @@ public StringSubstitutor(final Map valueMap) {
/**
* Constructs a new initialized instance. Uses a default escaping character.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StringSubstitutor(final Map valueMap, final String prefix, final String suffix) {
this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE);
@@ -529,12 +528,12 @@ public StringSubstitutor(final Map valueMap, final String prefix,
/**
* Constructs a new initialized instance.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StringSubstitutor(final Map valueMap, final String prefix, final String suffix,
final char escape) {
@@ -544,13 +543,13 @@ public StringSubstitutor(final Map valueMap, final String prefix,
/**
* Constructs a new initialized instance.
*
- * @param the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param the type of the values in the map.
+ * @param valueMap the map with the variables' values, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @param valueDelimiter the variable default value delimiter, may be null.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StringSubstitutor(final Map valueMap, final String prefix, final String suffix,
final char escape, final String valueDelimiter) {
@@ -569,11 +568,11 @@ public StringSubstitutor(final StringLookup variableResolver) {
/**
* Constructs a new initialized instance.
*
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param variableResolver the variable resolver, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix,
final char escape) {
@@ -587,12 +586,12 @@ public StringSubstitutor(final StringLookup variableResolver, final String prefi
/**
* Constructs a new initialized instance.
*
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter string, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param variableResolver the variable resolver, may be null.
+ * @param prefix the prefix for variables, not null.
+ * @param suffix the suffix for variables, not null.
+ * @param escape the escape character.
+ * @param valueDelimiter the variable default value delimiter string, may be null.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix,
final char escape, final String valueDelimiter) {
@@ -607,10 +606,10 @@ public StringSubstitutor(final StringLookup variableResolver, final String prefi
* Constructs a new initialized instance.
*
* @param variableResolver the variable resolver, may be null
- * @param prefixMatcher the prefix for variables, not null
- * @param suffixMatcher the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
+ * @param prefixMatcher the prefix for variables, not null.
+ * @param suffixMatcher the suffix for variables, not null.
+ * @param escape the escape character.
+ * @throws IllegalArgumentException if the prefix or suffix is null.
*/
public StringSubstitutor(final StringLookup variableResolver, final StringMatcher prefixMatcher,
final StringMatcher suffixMatcher, final char escape) {
@@ -637,7 +636,7 @@ public StringSubstitutor(final StringLookup variableResolver, final StringMatche
}
/**
- * Creates a new instance based on the given StringSubstitutor.
+ * Creates a new instance based on the given.
*
* @param other The StringSubstitutor used as the source.
* @since 1.9
@@ -672,11 +671,10 @@ private void checkCyclicSubstitution(final String varName, final List pr
throw new IllegalStateException(buf.toString());
}
- // Escape
/**
* Returns the escape character.
*
- * @return The character used for escaping variable references
+ * @return The character used for escaping variable references.
*/
public char getEscapeChar() {
return escapeChar;
@@ -685,7 +683,7 @@ public char getEscapeChar() {
/**
* Gets the StringLookup that is used to lookup variables.
*
- * @return The StringLookup
+ * @return The StringLookup.
*/
public StringLookup getStringLookup() {
return variableResolver;
@@ -701,7 +699,7 @@ public StringLookup getStringLookup() {
*
* If it returns null, then the variable default value resolution is disabled.
*
- * @return The variable default value delimiter matcher in use, may be null
+ * @return The variable default value delimiter matcher in use, may be null.
*/
public StringMatcher getValueDelimiterMatcher() {
return valueDelimiterMatcher;
@@ -752,7 +750,7 @@ public StringMatcher getVariableSuffixMatcher() {
* Hi Douglas ${surname}
*
*
- * @return The substitution in variable values flag
+ * @return The substitution in variable values flag.
*/
public boolean isDisableSubstitutionInValues() {
return disableSubstitutionInValues;
@@ -761,7 +759,7 @@ public boolean isDisableSubstitutionInValues() {
/**
* Returns a flag whether substitution is done in variable names.
*
- * @return The substitution in variable names flag
+ * @return The substitution in variable names flag.
*/
public boolean isEnableSubstitutionInVariables() {
return enableSubstitutionInVariables;
@@ -770,7 +768,7 @@ public boolean isEnableSubstitutionInVariables() {
/**
* Returns a flag whether exception can be thrown upon undefined variable.
*
- * @return The fail on undefined variable flag
+ * @return The fail on undefined variable flag.
*/
public boolean isEnableUndefinedVariableException() {
return failOnUndefinedVariable;
@@ -779,7 +777,7 @@ public boolean isEnableUndefinedVariableException() {
/**
* Returns the flag controlling whether escapes are preserved during substitution.
*
- * @return The preserve escape flag
+ * @return The preserve escape flag.
*/
public boolean isPreserveEscapes() {
return preserveEscapes;
@@ -789,9 +787,9 @@ public boolean isPreserveEscapes() {
* Replaces all the occurrences of variables with their matching values from the resolver using the given source
* array as a template. The array is not altered by this method.
*
- * @param source the character array to replace in, not altered, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the character array to replace in, not altered, null returns null.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final char[] source) {
if (source == null) {
@@ -803,22 +801,20 @@ public String replace(final char[] source) {
}
/**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * array as a template. The array is not altered by this method.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source array as a template. The array is not
+ * altered by this method.
*
- * Only the specified portion of the array will be processed. The rest of the array is not processed, and is not
- * returned.
+ * Only the specified portion of the array will be processed. The rest of the array is not processed, and is not returned.
*
*
- * @param source the character array to replace in, not altered, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- * @throws StringIndexOutOfBoundsException if {@code offset} is not in the
- * range {@code 0 <= offset <= chars.length}
- * @throws StringIndexOutOfBoundsException if {@code length < 0}
- * @throws StringIndexOutOfBoundsException if {@code offset + length > chars.length}
+ * @param source the character array to replace in, not altered, null returns null.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the array to be processed, must be valid.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
+ * @throws StringIndexOutOfBoundsException if {@code offset} is not in the range {@code 0 <= offset <= chars.length}.
+ * @throws StringIndexOutOfBoundsException if {@code length < 0}.
+ * @throws StringIndexOutOfBoundsException if {@code offset + length > chars.length}.
*/
public String replace(final char[] source, final int offset, final int length) {
if (source == null) {
@@ -833,9 +829,9 @@ public String replace(final char[] source, final int offset, final int length) {
* Replaces all the occurrences of variables with their matching values from the resolver using the given source as
* a template. The source is not altered by this method.
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final CharSequence source) {
if (source == null) {
@@ -852,11 +848,11 @@ public String replace(final CharSequence source) {
* returned.
*
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @param offset the start offset within the array, must be valid.
+ * @param length the length within the array to be processed, must be valid.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final CharSequence source, final int offset, final int length) {
if (source == null) {
@@ -871,9 +867,9 @@ public String replace(final CharSequence source, final int offset, final int len
* Replaces all the occurrences of variables in the given source object with their matching values from the
* resolver. The input source object is converted to a string using {@code toString} and is not altered.
*
- * @param source the source to replace in, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
+ * @param source the source to replace in, null returns null.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true.
*/
public String replace(final Object source) {
if (source == null) {
@@ -888,9 +884,9 @@ public String replace(final Object source) {
* Replaces all the occurrences of variables with their matching values from the resolver using the given source
* string as a template.
*
- * @param source the string to replace in, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the string to replace in, null returns null.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final String source) {
if (source == null) {
@@ -904,22 +900,19 @@ public String replace(final String source) {
}
/**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * string as a template.
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template.
*
- * Only the specified portion of the string will be processed. The rest of the string is not processed, and is not
- * returned.
+ * Only the specified portion of the string will be processed. The rest of the string is not processed, and is not returned.
*
*
- * @param source the string to replace in, null returns null
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- * @throws StringIndexOutOfBoundsException if {@code offset} is not in the
- * range {@code 0 <= offset <= source.length()}
- * @throws StringIndexOutOfBoundsException if {@code length < 0}
- * @throws StringIndexOutOfBoundsException if {@code offset + length > source.length()}
+ * @param source the string to replace in, null returns null.
+ * @param offset the start offset within the source, must be valid.
+ * @param length the length within the source to be processed, must be valid.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
+ * @throws StringIndexOutOfBoundsException if {@code offset} is not in the range {@code 0 <= offset <= source.length()}.
+ * @throws StringIndexOutOfBoundsException if {@code length < 0}.
+ * @throws StringIndexOutOfBoundsException if {@code offset + length > source.length()}.
*/
public String replace(final String source, final int offset, final int length) {
if (source == null) {
@@ -936,9 +929,9 @@ public String replace(final String source, final int offset, final int length) {
* Replaces all the occurrences of variables with their matching values from the resolver using the given source
* buffer as a template. The buffer is not altered by this method.
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final StringBuffer source) {
if (source == null) {
@@ -957,11 +950,11 @@ public String replace(final StringBuffer source) {
* returned.
*
*
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the buffer to use as a template, not changed, null returns null.
+ * @param offset the start offset within the source, must be valid.
+ * @param length the length within the source to be processed, must be valid.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final StringBuffer source, final int offset, final int length) {
if (source == null) {
@@ -976,9 +969,9 @@ public String replace(final StringBuffer source, final int offset, final int len
* Replaces all the occurrences of variables with their matching values from the resolver using the given source
* builder as a template. The builder is not altered by this method.
*
- * @param source the builder to use as a template, not changed, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the builder to use as a template, not changed, null returns null.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final TextStringBuilder source) {
if (source == null) {
@@ -997,11 +990,11 @@ public String replace(final TextStringBuilder source) {
* returned.
*
*
- * @param source the builder to use as a template, not changed, null returns null
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the builder to use as a template, not changed, null returns null.
+ * @param offset the start offset within the source, must be valid.
+ * @param length the length within the source to be processed, must be valid.
+ * @return The result of the replace operation.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public String replace(final TextStringBuilder source, final int offset, final int length) {
if (source == null) {
@@ -1016,7 +1009,7 @@ public String replace(final TextStringBuilder source, final int offset, final in
* Replaces all the occurrences of variables within the given source buffer with their matching values from the
* resolver. The buffer is updated with the result.
*
- * @param source the buffer to replace in, updated, null returns zero
+ * @param source the buffer to replace in, updated, null returns zero.
* @return true if altered
*/
public boolean replaceIn(final StringBuffer source) {
@@ -1034,11 +1027,11 @@ public boolean replaceIn(final StringBuffer source) {
* not deleted.
*
*
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the buffer to replace in, updated, null returns zero.
+ * @param offset the start offset within the source, must be valid.
+ * @param length the length within the source to be processed, must be valid.
+ * @return true if altered.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
if (source == null) {
@@ -1056,8 +1049,8 @@ public boolean replaceIn(final StringBuffer source, final int offset, final int
* Replaces all the occurrences of variables within the given source buffer with their matching values from the
* resolver. The buffer is updated with the result.
*
- * @param source the buffer to replace in, updated, null returns zero
- * @return true if altered
+ * @param source the buffer to replace in, updated, null returns zero.
+ * @return true if altered.
*/
public boolean replaceIn(final StringBuilder source) {
if (source == null) {
@@ -1074,11 +1067,11 @@ public boolean replaceIn(final StringBuilder source) {
* not deleted.
*
*
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the buffer to replace in, updated, null returns zero.
+ * @param offset the start offset within the source, must be valid.
+ * @param length the length within the source to be processed, must be valid.
+ * @return true if altered.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public boolean replaceIn(final StringBuilder source, final int offset, final int length) {
if (source == null) {
@@ -1096,9 +1089,9 @@ public boolean replaceIn(final StringBuilder source, final int offset, final int
* Replaces all the occurrences of variables within the given source builder with their matching values from the
* resolver.
*
- * @param source the builder to replace in, updated, null returns zero
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the builder to replace in, updated, null returns zero.
+ * @return true if altered.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public boolean replaceIn(final TextStringBuilder source) {
if (source == null) {
@@ -1115,11 +1108,11 @@ public boolean replaceIn(final TextStringBuilder source) {
* not deleted.
*
*
- * @param source the builder to replace in, null returns zero
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ * @param source the builder to replace in, null returns zero.
+ * @param offset the start offset within the source, must be valid.
+ * @param length the length within the source to be processed, must be valid.
+ * @return true if altered.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception.
*/
public boolean replaceIn(final TextStringBuilder source, final int offset, final int length) {
if (source == null) {
@@ -1140,11 +1133,11 @@ public boolean replaceIn(final TextStringBuilder source, final int offset, final
* {@link #getStringLookup()} with the variable's name as the key.
*
*
- * @param variableName the name of the variable, not null
- * @param buf the buffer where the substitution is occurring, not null
- * @param startPos the start position of the variable including the prefix, valid
- * @param endPos the end position of the variable including the suffix, valid
- * @return The variable's value or null if the variable is unknown
+ * @param variableName the name of the variable, not null.
+ * @param buf the buffer where the substitution is occurring, not null.
+ * @param startPos the start position of the variable including the prefix, valid.
+ * @param endPos the end position of the variable including the suffix, valid.
+ * @return The variable's value or null if the variable is unknown.
*/
protected String resolveVariable(final String variableName, final TextStringBuilder buf, final int startPos,
final int endPos) {
@@ -1158,8 +1151,8 @@ protected String resolveVariable(final String variableName, final TextStringBuil
/**
* Sets a flag whether substitution is done in variable values (recursive).
*
- * @param disableSubstitutionInValues true if substitution in variable value are disabled
- * @return this, to enable chaining
+ * @param disableSubstitutionInValues true if substitution in variable value are disabled.
+ * @return {@code this} instance.
*/
public StringSubstitutor setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
this.disableSubstitutionInValues = disableSubstitutionInValues;
@@ -1171,8 +1164,8 @@ public StringSubstitutor setDisableSubstitutionInValues(final boolean disableSub
* contain other variables which are processed first before the original variable is evaluated, e.g.
* {@code ${jre-${java.version}}}. The default value is false.
*
- * @param enableSubstitutionInVariables the new value of the flag
- * @return this, to enable chaining
+ * @param enableSubstitutionInVariables the new value of the flag.
+ * @return {@code this} instance.
*/
public StringSubstitutor setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) {
this.enableSubstitutionInVariables = enableSubstitutionInVariables;
@@ -1182,8 +1175,8 @@ public StringSubstitutor setEnableSubstitutionInVariables(final boolean enableSu
/**
* Sets a flag whether exception should be thrown if any variable is undefined.
*
- * @param failOnUndefinedVariable true if exception should be thrown on undefined variable
- * @return this, to enable chaining
+ * @param failOnUndefinedVariable true if exception should be thrown on undefined variable.
+ * @return {@code this} instance.
*/
public StringSubstitutor setEnableUndefinedVariableException(final boolean failOnUndefinedVariable) {
this.failOnUndefinedVariable = failOnUndefinedVariable;
@@ -1194,8 +1187,8 @@ public StringSubstitutor setEnableUndefinedVariableException(final boolean failO
* Sets the escape character. If this character is placed before a variable reference in the source text, this
* variable will be ignored.
*
- * @param escapeChar the escape character (0 for disabling escaping)
- * @return this, to enable chaining
+ * @param escapeChar the escape character (0 for disabling escaping).
+ * @return {@code this} instance.
*/
public StringSubstitutor setEscapeChar(final char escapeChar) {
this.escapeChar = escapeChar;
@@ -1208,8 +1201,8 @@ public StringSubstitutor setEscapeChar(final char escapeChar) {
* If set to false, the escape character is removed during substitution (e.g. {@code $${this-is-escaped}}
* becomes {@code ${this-is-escaped}}). The default value is false
*
- * @param preserveEscapes true if escapes are to be preserved
- * @return this, to enable chaining
+ * @param preserveEscapes true if escapes are to be preserved.
+ * @return {@code this} instance.
*/
public StringSubstitutor setPreserveEscapes(final boolean preserveEscapes) {
this.preserveEscapes = preserveEscapes;
@@ -1223,8 +1216,8 @@ public StringSubstitutor setPreserveEscapes(final boolean preserveEscapes) {
* variable default value. This method allows a single character variable default value delimiter to be easily set.
*
*
- * @param valueDelimiter the variable default value delimiter character to use
- * @return this, to enable chaining
+ * @param valueDelimiter the variable default value delimiter character to use.
+ * @return {@code this} instance.
*/
public StringSubstitutor setValueDelimiter(final char valueDelimiter) {
return setValueDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(valueDelimiter));
@@ -1241,8 +1234,8 @@ public StringSubstitutor setValueDelimiter(final char valueDelimiter) {
* disabled.
*
*
- * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
- * @return this, to enable chaining
+ * @param valueDelimiter the variable default value delimiter string to use, may be null or empty.
+ * @return {@code this} instance.
*/
public StringSubstitutor setValueDelimiter(final String valueDelimiter) {
if (valueDelimiter == null || valueDelimiter.isEmpty()) {
@@ -1263,8 +1256,8 @@ public StringSubstitutor setValueDelimiter(final String valueDelimiter) {
* If the {@code valueDelimiterMatcher} is null, then the variable default value resolution becomes disabled.
*
*
- * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
- * @return this, to enable chaining
+ * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null.
+ * @return {@code this} instance.
*/
public StringSubstitutor setValueDelimiterMatcher(final StringMatcher valueDelimiterMatcher) {
this.valueDelimiterMatcher = valueDelimiterMatcher;
@@ -1278,8 +1271,8 @@ public StringSubstitutor setValueDelimiterMatcher(final StringMatcher valueDelim
* single character prefix to be easily set.
*
*
- * @param prefix the prefix character to use
- * @return this, to enable chaining
+ * @param prefix the prefix character to use.
+ * @return {@code this} instance.
*/
public StringSubstitutor setVariablePrefix(final char prefix) {
return setVariablePrefixMatcher(StringMatcherFactory.INSTANCE.charMatcher(prefix));
@@ -1292,9 +1285,9 @@ public StringSubstitutor setVariablePrefix(final char prefix) {
* string prefix to be easily set.
*
*
- * @param prefix the prefix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix is null
+ * @param prefix the prefix for variables, not null.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the prefix is null.
*/
public StringSubstitutor setVariablePrefix(final String prefix) {
Validate.isTrue(prefix != null, "Variable prefix must not be null!");
@@ -1308,9 +1301,9 @@ public StringSubstitutor setVariablePrefix(final String prefix) {
* expressed in terms of a matcher allowing advanced prefix matches.
*
*
- * @param prefixMatcher the prefix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix matcher is null
+ * @param prefixMatcher the prefix matcher to use, null ignored.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the prefix matcher is null.
*/
public StringSubstitutor setVariablePrefixMatcher(final StringMatcher prefixMatcher) {
Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
@@ -1321,8 +1314,8 @@ public StringSubstitutor setVariablePrefixMatcher(final StringMatcher prefixMatc
/**
* Sets the VariableResolver that is used to lookup variables.
*
- * @param variableResolver the VariableResolver
- * @return this, to enable chaining
+ * @param variableResolver the VariableResolver.
+ * @return {@code this} instance.
*/
public StringSubstitutor setVariableResolver(final StringLookup variableResolver) {
this.variableResolver = variableResolver;
@@ -1336,8 +1329,8 @@ public StringSubstitutor setVariableResolver(final StringLookup variableResolver
* single character suffix to be easily set.
*
*
- * @param suffix the suffix character to use
- * @return this, to enable chaining
+ * @param suffix the suffix character to use.
+ * @return {@code this} instance.
*/
public StringSubstitutor setVariableSuffix(final char suffix) {
return setVariableSuffixMatcher(StringMatcherFactory.INSTANCE.charMatcher(suffix));
@@ -1350,9 +1343,9 @@ public StringSubstitutor setVariableSuffix(final char suffix) {
* string suffix to be easily set.
*
*
- * @param suffix the suffix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix is null
+ * @param suffix the suffix for variables, not null.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the suffix is null.
*/
public StringSubstitutor setVariableSuffix(final String suffix) {
Validate.isTrue(suffix != null, "Variable suffix must not be null!");
@@ -1366,9 +1359,9 @@ public StringSubstitutor setVariableSuffix(final String suffix) {
* in terms of a matcher allowing advanced suffix matches.
*
*
- * @param suffixMatcher the suffix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix matcher is null
+ * @param suffixMatcher the suffix matcher to use, null ignored.
+ * @return {@code this} instance.
+ * @throws IllegalArgumentException if the suffix matcher is null.
*/
public StringSubstitutor setVariableSuffixMatcher(final StringMatcher suffixMatcher) {
Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
@@ -1387,10 +1380,10 @@ public StringSubstitutor setVariableSuffixMatcher(final StringMatcher suffixMatc
* end.
*
*
- * @param builder the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @return true if altered
+ * @param builder the string builder to substitute into, not null.
+ * @param offset the start offset within the builder, must be valid.
+ * @param length the length within the builder to be processed, must be valid.
+ * @return true if altered.
*/
protected boolean substitute(final TextStringBuilder builder, final int offset, final int length) {
return substitute(builder, offset, length, null).altered;
@@ -1400,12 +1393,12 @@ protected boolean substitute(final TextStringBuilder builder, final int offset,
* Recursive handler for multiple levels of interpolation. This is the main interpolation method, which resolves the
* values of all variable references contained in the passed in text.
*
- * @param builder the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @param priorVariables the stack keeping track of the replaced variables, may be null
+ * @param builder the string builder to substitute into, not null.
+ * @param offset the start offset within the builder, must be valid.
+ * @param length the length within the builder to be processed, must be valid.
+ * @param priorVariables the stack keeping track of the replaced variables, may be null.
* @return The result.
- * @throws IllegalArgumentException if variable is not found and
isEnableUndefinedVariableException()==true
+ * @throws IllegalArgumentException if variable is not found and isEnableUndefinedVariableException() == true.
* @since 1.9
*/
private Result substitute(final TextStringBuilder builder, final int offset, final int length,
diff --git a/src/main/java/org/apache/commons/text/StringTokenizer.java b/src/main/java/org/apache/commons/text/StringTokenizer.java
index ca1782a9ef..83b1c12fbb 100644
--- a/src/main/java/org/apache/commons/text/StringTokenizer.java
+++ b/src/main/java/org/apache/commons/text/StringTokenizer.java
@@ -94,28 +94,26 @@
public class StringTokenizer implements ListIterator, Cloneable {
/** Comma separated values tokenizer internal variable. */
- private static final StringTokenizer CSV_TOKENIZER_PROTOTYPE;
+ // @formatter:off
+ private static final StringTokenizer CSV_TOKENIZER_PROTOTYPE = new StringTokenizer()
+ .setDelimiterMatcher(StringMatcherFactory.INSTANCE.commaMatcher())
+ .setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher())
+ .setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher())
+ .setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher())
+ .setEmptyTokenAsNull(false)
+ .setIgnoreEmptyTokens(false);
+ // @formatter:on
/** Tab separated values tokenizer internal variable. */
- private static final StringTokenizer TSV_TOKENIZER_PROTOTYPE;
-
- static {
- CSV_TOKENIZER_PROTOTYPE = new StringTokenizer();
- CSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StringMatcherFactory.INSTANCE.commaMatcher());
- CSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher());
- CSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher());
- CSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher());
- CSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
- CSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
-
- TSV_TOKENIZER_PROTOTYPE = new StringTokenizer();
- TSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StringMatcherFactory.INSTANCE.tabMatcher());
- TSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher());
- TSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher());
- TSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher());
- TSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
- TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
- }
+ // @formatter:off
+ private static final StringTokenizer TSV_TOKENIZER_PROTOTYPE = new StringTokenizer()
+ .setDelimiterMatcher(StringMatcherFactory.INSTANCE.tabMatcher())
+ .setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher())
+ .setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher())
+ .setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher())
+ .setEmptyTokenAsNull(false)
+ .setIgnoreEmptyTokens(false);
+ // @formatter:on
/**
* Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}.
@@ -134,33 +132,29 @@ private static StringTokenizer getCSVClone() {
* You must call a "reset" method to set the string which you want to parse.
*
*
- * @return a new tokenizer instance which parses Comma Separated Value strings
+ * @return a new tokenizer instance which parses Comma Separated Value strings.
*/
public static StringTokenizer getCSVInstance() {
return getCSVClone();
}
/**
- * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input.
- * The default for CSV processing will be trim whitespace from both ends (which can be overridden with the
- * setTrimmer method).
+ * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. The default for CSV processing will be
+ * trim whitespace from both ends (which can be overridden with the setTrimmer method).
*
- * @param input
- * the text to parse
- * @return a new tokenizer instance which parses Comma Separated Value strings
+ * @param input the text to parse.
+ * @return a new tokenizer instance which parses Comma Separated Value strings.
*/
public static StringTokenizer getCSVInstance(final char[] input) {
return getCSVClone().reset(input);
}
/**
- * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input.
- * The default for CSV processing will be trim whitespace from both ends (which can be overridden with the
- * setTrimmer method).
+ * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. The default for CSV processing will be
+ * trim whitespace from both ends (which can be overridden with the setTrimmer method).
*
- * @param input
- * the text to parse
- * @return a new tokenizer instance which parses Comma Separated Value strings
+ * @param input the text to parse.
+ * @return a new tokenizer instance which parses Comma Separated Value strings.
*/
public static StringTokenizer getCSVInstance(final String input) {
return getCSVClone().reset(input);
@@ -189,11 +183,10 @@ public static StringTokenizer getTSVInstance() {
}
/**
- * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be
- * trim whitespace from both ends (which can be overridden with the setTrimmer method).
+ * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be trim whitespace from both ends (which can
+ * be overridden with the setTrimmer method).
*
- * @param input
- * the string to parse
+ * @param input the string to parse.
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StringTokenizer getTSVInstance(final char[] input) {
@@ -201,11 +194,10 @@ public static StringTokenizer getTSVInstance(final char[] input) {
}
/**
- * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be
- * trim whitespace from both ends (which can be overridden with the setTrimmer method).
+ * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be trim whitespace from both ends (which can
+ * be overridden with the setTrimmer method).
*
- * @param input
- * the string to parse
+ * @param input the string to parse.
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
public static StringTokenizer getTSVInstance(final String input) {
@@ -240,8 +232,7 @@ public static StringTokenizer getTSVInstance(final String input) {
private boolean ignoreEmptyTokens = true;
/**
- * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer, but with no text to
- * tokenize.
+ * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer, but with no text to tokenize.
*
* This constructor is normally used with {@link #reset(String)}.
*
@@ -253,8 +244,7 @@ public StringTokenizer() {
/**
* Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer.
*
- * @param input
- * the string which is to be parsed, not cloned
+ * @param input the string which is to be parsed, not cloned.
*/
public StringTokenizer(final char[] input) {
this.chars = input != null ? input.clone() : null;
@@ -263,10 +253,8 @@ public StringTokenizer(final char[] input) {
/**
* Constructs a tokenizer splitting on the specified character.
*
- * @param input
- * the string which is to be parsed, not cloned
- * @param delim
- * the field delimiter character
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter character.
*/
public StringTokenizer(final char[] input, final char delim) {
this(input);
@@ -274,15 +262,11 @@ public StringTokenizer(final char[] input, final char delim) {
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified
- * quote character.
+ * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified quote character.
*
- * @param input
- * the string which is to be parsed, not cloned
- * @param delim
- * the field delimiter character
- * @param quote
- * the field quoted string character
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter character.
+ * @param quote the field quoted string character.
*/
public StringTokenizer(final char[] input, final char delim, final char quote) {
this(input, delim);
@@ -292,10 +276,8 @@ public StringTokenizer(final char[] input, final char delim, final char quote) {
/**
* Constructs a tokenizer splitting on the specified string.
*
- * @param input
- * the string which is to be parsed, not cloned
- * @param delim
- * the field delimiter string
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter string.
*/
public StringTokenizer(final char[] input, final String delim) {
this(input);
@@ -305,10 +287,8 @@ public StringTokenizer(final char[] input, final String delim) {
/**
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
- * @param input
- * the string which is to be parsed, not cloned
- * @param delim
- * the field delimiter matcher
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter matcher.
*/
public StringTokenizer(final char[] input, final StringMatcher delim) {
this(input);
@@ -316,15 +296,11 @@ public StringTokenizer(final char[] input, final StringMatcher delim) {
}
/**
- * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified
- * quote matcher.
+ * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified quote matcher.
*
- * @param input
- * the string which is to be parsed, not cloned
- * @param delim
- * the field delimiter character
- * @param quote
- * the field quoted string character
+ * @param input the string which is to be parsed, not cloned.
+ * @param delim the field delimiter character.
+ * @param quote the field quoted string character.
*/
public StringTokenizer(final char[] input, final StringMatcher delim, final StringMatcher quote) {
this(input, delim);
@@ -334,8 +310,7 @@ public StringTokenizer(final char[] input, final StringMatcher delim, final Stri
/**
* Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer.
*
- * @param input
- * the string which is to be parsed
+ * @param input the string which is to be parsed.
*/
public StringTokenizer(final String input) {
this.chars = input != null ? input.toCharArray() : null;
@@ -344,10 +319,8 @@ public StringTokenizer(final String input) {
/**
* Constructs a tokenizer splitting on the specified delimiter character.
*
- * @param input
- * the string which is to be parsed
- * @param delim
- * the field delimiter character
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter character.
*/
public StringTokenizer(final String input, final char delim) {
this(input);
@@ -355,15 +328,11 @@ public StringTokenizer(final String input, final char delim) {
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified
- * quote character.
+ * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified quote character.
*
- * @param input
- * the string which is to be parsed
- * @param delim
- * the field delimiter character
- * @param quote
- * the field quoted string character
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter character.
+ * @param quote the field quoted string character.
*/
public StringTokenizer(final String input, final char delim, final char quote) {
this(input, delim);
@@ -373,10 +342,8 @@ public StringTokenizer(final String input, final char delim, final char quote) {
/**
* Constructs a tokenizer splitting on the specified delimiter string.
*
- * @param input
- * the string which is to be parsed
- * @param delim
- * the field delimiter string
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter string.
*/
public StringTokenizer(final String input, final String delim) {
this(input);
@@ -386,10 +353,8 @@ public StringTokenizer(final String input, final String delim) {
/**
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
- * @param input
- * the string which is to be parsed
- * @param delim
- * the field delimiter matcher
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter matcher.
*/
public StringTokenizer(final String input, final StringMatcher delim) {
this(input);
@@ -397,15 +362,11 @@ public StringTokenizer(final String input, final StringMatcher delim) {
}
/**
- * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified
- * quote matcher.
+ * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified quote matcher.
*
- * @param input
- * the string which is to be parsed
- * @param delim
- * the field delimiter matcher
- * @param quote
- * the field quoted string matcher
+ * @param input the string which is to be parsed.
+ * @param delim the field delimiter matcher.
+ * @param quote the field quoted string matcher.
*/
public StringTokenizer(final String input, final StringMatcher delim, final StringMatcher quote) {
this(input, delim);
@@ -415,10 +376,8 @@ public StringTokenizer(final String input, final StringMatcher delim, final Stri
/**
* Unsupported ListIterator operation.
*
- * @param obj
- * this parameter ignored.
- * @throws UnsupportedOperationException
- * always
+ * @param obj this parameter ignored.
+ * @throws UnsupportedOperationException always.
*/
@Override
public void add(final String obj) {
@@ -428,10 +387,8 @@ public void add(final String obj) {
/**
* Adds a token to a list, paying attention to the parameters we've set.
*
- * @param list
- * the list to add to
- * @param tok
- * the token to add
+ * @param list the list to add to.
+ * @param tok the token to add.
*/
private void addToken(final List list, String tok) {
if (tok == null || tok.isEmpty()) {
@@ -452,7 +409,7 @@ private void checkTokenized() {
if (tokens == null) {
final List split;
if (chars == null) {
- // still call tokenize as subclass may do some work
+ // still call tokenize as subclass may do some work.
split = tokenize(null, 0, 0);
} else {
split = tokenize(chars, 0, chars.length);
@@ -462,8 +419,8 @@ private void checkTokenized() {
}
/**
- * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token
- * list. If a {@link CloneNotSupportedException} is caught, return {@code null}.
+ * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token list. If a
+ * {@link CloneNotSupportedException} is caught, return {@code null}.
*
* @return a new instance of this Tokenizer which has been reset.
*/
@@ -477,12 +434,10 @@ public Object clone() {
}
/**
- * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token
- * list.
+ * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token list.
*
* @return a new instance of this Tokenizer which has been reset.
- * @throws CloneNotSupportedException
- * if there is a problem cloning
+ * @throws CloneNotSupportedException if there is a problem cloning.
*/
Object cloneReset() throws CloneNotSupportedException {
// this method exists to enable 100% test coverage
@@ -497,7 +452,7 @@ Object cloneReset() throws CloneNotSupportedException {
/**
* Gets the String content that the tokenizer is parsing.
*
- * @return The string content being parsed
+ * @return The string content being parsed.
*/
public String getContent() {
if (chars == null) {
@@ -509,7 +464,7 @@ public String getContent() {
/**
* Gets the field delimiter matcher.
*
- * @return The delimiter matcher in use
+ * @return The delimiter matcher in use.
*/
public StringMatcher getDelimiterMatcher() {
return this.delimMatcher;
@@ -518,11 +473,10 @@ public StringMatcher getDelimiterMatcher() {
/**
* Gets the ignored character matcher.
*
- * These characters are ignored when parsing the String, unless they are within a quoted region. The default value
- * is not to ignore anything.
+ * These characters are ignored when parsing the String, unless they are within a quoted region. The default value is not to ignore anything.
*
*
- * @return The ignored matcher in use
+ * @return The ignored matcher in use.
*/
public StringMatcher getIgnoredMatcher() {
return ignoredMatcher;
@@ -531,11 +485,10 @@ public StringMatcher getIgnoredMatcher() {
/**
* Gets the quote matcher currently in use.
*
- * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. The
- * default value is '"' (double quote).
+ * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. The default value is '"' (double quote).
*
*
- * @return The quote matcher in use
+ * @return The quote matcher in use.
*/
public StringMatcher getQuoteMatcher() {
return quoteMatcher;
@@ -544,7 +497,7 @@ public StringMatcher getQuoteMatcher() {
/**
* Gets a copy of the full token list as an independent modifiable array.
*
- * @return The tokens as a String array
+ * @return The tokens as a String array.
*/
public String[] getTokenArray() {
checkTokenized();
@@ -554,7 +507,7 @@ public String[] getTokenArray() {
/**
* Gets a copy of the full token list as an independent modifiable list.
*
- * @return The tokens as a String list
+ * @return The tokens as a String list.
*/
public List getTokenList() {
checkTokenized();
@@ -564,11 +517,10 @@ public List getTokenList() {
/**
* Gets the trimmer character matcher.
*
- * These characters are trimmed off on each side of the delimiter until the token or quote is found. The default
- * value is not to trim anything.
+ * These characters are trimmed off on each side of the delimiter until the token or quote is found. The default value is not to trim anything.
*
*
- * @return The trimmer matcher in use
+ * @return The trimmer matcher in use.
*/
public StringMatcher getTrimmerMatcher() {
return trimmerMatcher;
@@ -577,7 +529,7 @@ public StringMatcher getTrimmerMatcher() {
/**
* Tests whether there are any more tokens.
*
- * @return true if there are more tokens
+ * @return true if there are more tokens.
*/
@Override
public boolean hasNext() {
@@ -588,7 +540,7 @@ public boolean hasNext() {
/**
* Tests whether there are any previous tokens that can be iterated to.
*
- * @return true if there are previous tokens
+ * @return true if there are previous tokens.
*/
@Override
public boolean hasPrevious() {
@@ -599,7 +551,7 @@ public boolean hasPrevious() {
/**
* Tests whether the tokenizer currently returns empty tokens as null. The default for this property is false.
*
- * @return true if empty tokens are returned as null
+ * @return true if empty tokens are returned as null.
*/
public boolean isEmptyTokenAsNull() {
return this.emptyAsNull;
@@ -608,7 +560,7 @@ public boolean isEmptyTokenAsNull() {
/**
* Tests whether the tokenizer currently ignores empty tokens. The default for this property is true.
*
- * @return true if empty tokens are not returned
+ * @return true if empty tokens are not returned.
*/
public boolean isIgnoreEmptyTokens() {
return ignoreEmptyTokens;
@@ -617,20 +569,14 @@ public boolean isIgnoreEmptyTokens() {
/**
* Tests if the characters at the index specified match the quote already matched in readNextToken().
*
- * @param srcChars
- * the character array being tokenized
- * @param pos
- * the position to check for a quote
- * @param len
- * the length of the character array being tokenized
- * @param quoteStart
- * the start position of the matched quote, 0 if no quoting
- * @param quoteLen
- * the length of the matched quote, 0 if no quoting
- * @return true if a quote is matched
- */
- private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart,
- final int quoteLen) {
+ * @param srcChars the character array being tokenized.
+ * @param pos the position to check for a quote.
+ * @param len the length of the character array being tokenized.
+ * @param quoteStart the start position of the matched quote, 0 if no quoting.
+ * @param quoteLen the length of the matched quote, 0 if no quoting.
+ * @return true if a quote is matched.
+ */
+ private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart, final int quoteLen) {
for (int i = 0; i < quoteLen; i++) {
if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) {
return false;
@@ -642,9 +588,8 @@ private boolean isQuote(final char[] srcChars, final int pos, final int len, fin
/**
* Gets the next token.
*
- * @return The next String token
- * @throws NoSuchElementException
- * if there are no more elements
+ * @return The next String token.
+ * @throws NoSuchElementException if there are no more elements.
*/
@Override
public String next() {
@@ -657,7 +602,7 @@ public String next() {
/**
* Gets the index of the next token to return.
*
- * @return The next token index
+ * @return The next token index.
*/
@Override
public int nextIndex() {
@@ -665,10 +610,10 @@ public int nextIndex() {
}
/**
- * Gets the next token from the String. Equivalent to {@link #next()} except it returns null rather than throwing
- * {@link NoSuchElementException} when no tokens remain.
+ * Gets the next token from the String. Equivalent to {@link #next()} except it returns null rather than throwing {@link NoSuchElementException} when no
+ * tokens remain.
*
- * @return The next sequential token, or null when no more tokens are found
+ * @return The next sequential token, or null when no more tokens are found.
*/
public String nextToken() {
if (hasNext()) {
@@ -680,7 +625,7 @@ public String nextToken() {
/**
* Gets the token previous to the last returned token.
*
- * @return The previous token
+ * @return The previous token.
*/
@Override
public String previous() {
@@ -693,7 +638,7 @@ public String previous() {
/**
* Gets the index of the previous token.
*
- * @return The previous token index
+ * @return The previous token index.
*/
@Override
public int previousIndex() {
@@ -703,7 +648,7 @@ public int previousIndex() {
/**
* Gets the previous token from the String.
*
- * @return The previous sequential token, or null when no more tokens are found
+ * @return The previous sequential token, or null when no more tokens are found.
*/
public String previousToken() {
if (hasPrevious()) {
@@ -715,18 +660,12 @@ public String previousToken() {
/**
* Reads character by character through the String to get the next token.
*
- * @param srcChars
- * the character array being tokenized
- * @param start
- * the first character of field
- * @param len
- * the length of the character array being tokenized
- * @param workArea
- * a temporary work area
- * @param tokenList
- * the list of parsed tokens
- * @return The starting position of the next field (the character immediately after the delimiter), or -1 if end of
- * string found
+ * @param srcChars the character array being tokenized.
+ * @param start the first character of field.
+ * @param len the length of the character array being tokenized.
+ * @param workArea a temporary work area.
+ * @param tokenList the list of parsed tokens.
+ * @return The starting position of the next field (the character immediately after the delimiter), or -1 if end of string found.
*/
private int readNextToken(final char[] srcChars, int start, final int len, final TextStringBuilder workArea,
final List tokenList) {
@@ -766,22 +705,14 @@ private int readNextToken(final char[] srcChars, int start, final int len, final
/**
* Reads a possibly quoted string token.
*
- * @param srcChars
- * the character array being tokenized
- * @param start
- * the first character of field
- * @param len
- * the length of the character array being tokenized
- * @param workArea
- * a temporary work area
- * @param tokenList
- * the list of parsed tokens
- * @param quoteStart
- * the start position of the matched quote, 0 if no quoting
- * @param quoteLen
- * the length of the matched quote, 0 if no quoting
- * @return The starting position of the next field (the character immediately after the delimiter, or if end of
- * string found, then the length of string
+ * @param srcChars the character array being tokenized.
+ * @param start the first character of field.
+ * @param len the length of the character array being tokenized.
+ * @param workArea a temporary work area.
+ * @param tokenList the list of parsed tokens.
+ * @param quoteStart the start position of the matched quote, 0 if no quoting.
+ * @param quoteLen the length of the matched quote, 0 if no quoting.
+ * @return The starting position of the next field (the character immediately after the delimiter, or if end of string found, then the length of string.
*/
private int readWithQuotes(final char[] srcChars, final int start, final int len, final TextStringBuilder workArea,
final List tokenList, final int quoteStart, final int quoteLen) {
@@ -866,8 +797,7 @@ private int readWithQuotes(final char[] srcChars, final int start, final int len
/**
* Throws {@link UnsupportedOperationException} for this unsupported ListIterator operation.
*
- * @throws UnsupportedOperationException
- * always
+ * @throws UnsupportedOperationException Always thrown.
*/
@Override
public void remove() {
@@ -880,7 +810,7 @@ public void remove() {
* This method allows the same tokenizer to be reused for the same String.
*
*
- * @return this, to enable chaining
+ * @return {@code this} instance.
*/
public StringTokenizer reset() {
tokenPos = 0;
@@ -889,12 +819,10 @@ public StringTokenizer reset() {
}
/**
- * Resets this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the
- * same settings on multiple input lines.
+ * Resets this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the same settings on multiple input lines.
*
- * @param input
- * the new character array to tokenize, not cloned, null sets no text to parse
- * @return this, to enable chaining
+ * @param input the new character array to tokenize, not cloned, null sets no text to parse.
+ * @return {@code this} instance.
*/
public StringTokenizer reset(final char[] input) {
reset();
@@ -903,12 +831,10 @@ public StringTokenizer reset(final char[] input) {
}
/**
- * Resets this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the
- * same settings on multiple input lines.
+ * Resets this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the same settings on multiple input lines.
*
- * @param input
- * the new string to tokenize, null sets no text to parse
- * @return this, to enable chaining
+ * @param input the new string to tokenize, null sets no text to parse.
+ * @return {@code this} instance.
*/
public StringTokenizer reset(final String input) {
reset();
@@ -919,10 +845,8 @@ public StringTokenizer reset(final String input) {
/**
* Throws {@link UnsupportedOperationException} for this unsupported ListIterator operation.
*
- * @param obj
- * this parameter ignored.
- * @throws UnsupportedOperationException
- * always
+ * @param obj this parameter ignored.
+ * @throws UnsupportedOperationException always.
*/
@Override
public void set(final String obj) {
@@ -932,9 +856,8 @@ public void set(final String obj) {
/**
* Sets the field delimiter character.
*
- * @param delim
- * the delimiter character to use
- * @return this, to enable chaining
+ * @param delim the delimiter character to use.
+ * @return {@code this} instance.
*/
public StringTokenizer setDelimiterChar(final char delim) {
return setDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(delim));
@@ -946,9 +869,8 @@ public StringTokenizer setDelimiterChar(final char delim) {
* The delimiter is used to separate one token from another.
*
*
- * @param delim
- * the delimiter matcher to use
- * @return this, to enable chaining
+ * @param delim the delimiter matcher to use.
+ * @return {@code this} instance.
*/
public StringTokenizer setDelimiterMatcher(final StringMatcher delim) {
this.delimMatcher = delim == null ? StringMatcherFactory.INSTANCE.noneMatcher() : delim;
@@ -958,9 +880,8 @@ public StringTokenizer setDelimiterMatcher(final StringMatcher delim) {
/**
* Sets the field delimiter string.
*
- * @param delim
- * the delimiter string to use
- * @return this, to enable chaining
+ * @param delim the delimiter string to use.
+ * @return {@code this} instance.
*/
public StringTokenizer setDelimiterString(final String delim) {
return setDelimiterMatcher(StringMatcherFactory.INSTANCE.stringMatcher(delim));
@@ -969,9 +890,8 @@ public StringTokenizer setDelimiterString(final String delim) {
/**
* Sets whether the tokenizer should return empty tokens as null. The default for this property is false.
*
- * @param emptyAsNull
- * whether empty tokens are returned as null
- * @return this, to enable chaining
+ * @param emptyAsNull whether empty tokens are returned as null.
+ * @return {@code this} instance.
*/
public StringTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
this.emptyAsNull = emptyAsNull;
@@ -984,9 +904,8 @@ public StringTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
* This character is ignored when parsing the String, unless it is within a quoted region.
*
*
- * @param ignored
- * the ignored character to use
- * @return this, to enable chaining
+ * @param ignored the ignored character to use.
+ * @return {@code this} instance.
*/
public StringTokenizer setIgnoredChar(final char ignored) {
return setIgnoredMatcher(StringMatcherFactory.INSTANCE.charMatcher(ignored));
@@ -998,9 +917,8 @@ public StringTokenizer setIgnoredChar(final char ignored) {
* These characters are ignored when parsing the String, unless they are within a quoted region.
*
*
- * @param ignored
- * the ignored matcher to use, null ignored
- * @return this, to enable chaining
+ * @param ignored the ignored matcher to use, null ignored.
+ * @return {@code this} instance.
*/
public StringTokenizer setIgnoredMatcher(final StringMatcher ignored) {
if (ignored != null) {
@@ -1012,9 +930,8 @@ public StringTokenizer setIgnoredMatcher(final StringMatcher ignored) {
/**
* Sets whether the tokenizer should ignore and not return empty tokens. The default for this property is true.
*
- * @param ignoreEmptyTokens
- * whether empty tokens are not returned
- * @return this, to enable chaining
+ * @param ignoreEmptyTokens whether empty tokens are not returned.
+ * @return {@code this} instance.
*/
public StringTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
this.ignoreEmptyTokens = ignoreEmptyTokens;
@@ -1027,9 +944,8 @@ public StringTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
* The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
*
*
- * @param quote
- * the quote character to use
- * @return this, to enable chaining
+ * @param quote the quote character to use.
+ * @return {@code this} instance.
*/
public StringTokenizer setQuoteChar(final char quote) {
return setQuoteMatcher(StringMatcherFactory.INSTANCE.charMatcher(quote));
@@ -1041,9 +957,8 @@ public StringTokenizer setQuoteChar(final char quote) {
* The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
*
*
- * @param quote
- * the quote matcher to use, null ignored
- * @return this, to enable chaining
+ * @param quote the quote matcher to use, null ignored.
+ * @return {@code this} instance.
*/
public StringTokenizer setQuoteMatcher(final StringMatcher quote) {
if (quote != null) {
@@ -1057,9 +972,8 @@ public StringTokenizer setQuoteMatcher(final StringMatcher quote) {
*
* These characters are trimmed off on each side of the delimiter until the token or quote is found.
*
- * @param trimmer
- * the trimmer matcher to use, null ignored
- * @return this, to enable chaining
+ * @param trimmer the trimmer matcher to use, null ignored.
+ * @return {@code this} instance.
*/
public StringTokenizer setTrimmerMatcher(final StringMatcher trimmer) {
if (trimmer != null) {
@@ -1071,7 +985,7 @@ public StringTokenizer setTrimmerMatcher(final StringMatcher trimmer) {
/**
* Gets the number of tokens found in the String.
*
- * @return The number of matched tokens
+ * @return The number of matched tokens.
*/
public int size() {
checkTokenized();
@@ -1081,26 +995,21 @@ public int size() {
/**
* Internal method to performs the tokenization.
*
- * Most users of this class do not need to call this method. This method will be called automatically by other
- * (public) methods when required.
+ * Most users of this class do not need to call this method. This method will be called automatically by other (public) methods when required.
*
*
- * This method exists to allow subclasses to add code before or after the tokenization. For example, a subclass
- * could alter the character array, offset or count to be parsed, or call the tokenizer multiple times on multiple
- * strings. It is also be possible to filter the results.
+ * This method exists to allow subclasses to add code before or after the tokenization. For example, a subclass could alter the character array, offset or
+ * count to be parsed, or call the tokenizer multiple times on multiple strings. It is also be possible to filter the results.
*
*
- * {@code StrTokenizer} will always pass a zero offset and a count equal to the length of the array to this
- * method, however a subclass may pass other values, or even an entirely different array.
+ * {@code StrTokenizer} will always pass a zero offset and a count equal to the length of the array to this method, however a subclass may pass other
+ * values, or even an entirely different array.
*
*
- * @param srcChars
- * the character array being tokenized, may be null
- * @param offset
- * the start position within the character array, must be valid
- * @param count
- * the number of characters to tokenize, must be valid
- * @return The modifiable list of String tokens, unmodifiable if null array or zero count
+ * @param srcChars the character array being tokenized, may be null.
+ * @param offset the start position within the character array, must be valid.
+ * @param count the number of characters to tokenize, must be valid.
+ * @return The modifiable list of String tokens, unmodifiable if null array or zero count.
*/
protected List tokenize(final char[] srcChars, final int offset, final int count) {
if (srcChars == null || count == 0) {
@@ -1109,12 +1018,10 @@ protected List tokenize(final char[] srcChars, final int offset, final i
final TextStringBuilder buf = new TextStringBuilder();
final List tokenList = new ArrayList<>();
int pos = offset;
-
// loop around the entire buffer
while (pos >= 0 && pos < count) {
// find next token
pos = readNextToken(srcChars, pos, count, buf, tokenList);
-
// handle case where end of string is a delimiter
if (pos >= count) {
addToken(tokenList, StringUtils.EMPTY);
@@ -1126,7 +1033,7 @@ protected List tokenize(final char[] srcChars, final int offset, final i
/**
* Gets the String content that the tokenizer is parsing.
*
- * @return The string content being parsed
+ * @return The string content being parsed.
*/
@Override
public String toString() {
@@ -1135,5 +1042,4 @@ public String toString() {
}
return "StringTokenizer" + getTokenList();
}
-
}
diff --git a/src/main/java/org/apache/commons/text/TextRandomProvider.java b/src/main/java/org/apache/commons/text/TextRandomProvider.java
index 84eb843db3..82477d6b89 100644
--- a/src/main/java/org/apache/commons/text/TextRandomProvider.java
+++ b/src/main/java/org/apache/commons/text/TextRandomProvider.java
@@ -39,6 +39,7 @@
* .build();
* }
*
+ *
* @since 1.1
*/
public interface TextRandomProvider extends IntUnaryOperator {
diff --git a/src/main/java/org/apache/commons/text/TextStringBuilder.java b/src/main/java/org/apache/commons/text/TextStringBuilder.java
index 95616cf02d..2977fa3232 100644
--- a/src/main/java/org/apache/commons/text/TextStringBuilder.java
+++ b/src/main/java/org/apache/commons/text/TextStringBuilder.java
@@ -114,10 +114,7 @@ public boolean markSupported() {
/** {@inheritDoc} */
@Override
public int read() {
- if (!ready()) {
- return -1;
- }
- return charAt(pos++);
+ return ready() ? charAt(pos++) : -1;
}
/** {@inheritDoc} */
@@ -181,10 +178,7 @@ final class TextStringBuilderTokenizer extends StringTokenizer {
@Override
public String getContent() {
final String str = super.getContent();
- if (str == null) {
- return TextStringBuilder.this.toString();
- }
- return str;
+ return str != null ? str : TextStringBuilder.this.toString();
}
/** {@inheritDoc} */
@@ -375,9 +369,9 @@ public TextStringBuilder() {
* Constructs an instance from a reference to a character array.
*
* @param initialBuffer a reference to a character array, must not be null.
- * @param length The length of the subarray to be used; must be non-negative and no larger than
- * {@code initialBuffer.length}. The new builder's size will be set to {@code length}.
- * @throws NullPointerException If {@code initialBuffer} is null.
+ * @param length The length of the subarray to be used; must be non-negative and no larger than {@code initialBuffer.length}. The new builder's size
+ * will be set to {@code length}.
+ * @throws NullPointerException If {@code initialBuffer} is null.
* @throws IllegalArgumentException if {@code length} is bad.
*/
private TextStringBuilder(final char[] initialBuffer, final int length) {
@@ -391,7 +385,7 @@ private TextStringBuilder(final char[] initialBuffer, final int length) {
/**
* Constructs an instance from a character sequence, allocating 32 extra characters for growth.
*
- * @param seq the string to copy, null treated as blank string
+ * @param seq the string to copy, null treated as blank string.
* @since 1.9
*/
public TextStringBuilder(final CharSequence seq) {
@@ -404,7 +398,7 @@ public TextStringBuilder(final CharSequence seq) {
/**
* Constructs an instance with the specified initial capacity.
*
- * @param initialCapacity the initial capacity, zero or less will be converted to 32
+ * @param initialCapacity the initial capacity, zero or less will be converted to 32.
*/
public TextStringBuilder(final int initialCapacity) {
buffer = new char[initialCapacity <= 0 ? CAPACITY : initialCapacity];
@@ -413,7 +407,7 @@ public TextStringBuilder(final int initialCapacity) {
/**
* Constructs an instance from a string, allocating 32 extra characters for growth.
*
- * @param str the string to copy, null treated as blank string
+ * @param str the string to copy, null treated as blank string.
*/
public TextStringBuilder(final String str) {
this(StringUtils.length(str) + CAPACITY);
@@ -425,8 +419,8 @@ public TextStringBuilder(final String str) {
/**
* Appends a boolean value to the string builder.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final boolean value) {
if (value) {
@@ -442,8 +436,8 @@ public TextStringBuilder append(final boolean value) {
/**
* Appends a char value to the string builder.
*
- * @param ch the value to append
- * @return this, to enable chaining
+ * @param ch the value to append.
+ * @return {@code this} instance.
*/
@Override
public TextStringBuilder append(final char ch) {
@@ -456,8 +450,8 @@ public TextStringBuilder append(final char ch) {
/**
* Appends a char array to the string builder. Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
- * @return this, to enable chaining
+ * @param chars the char array to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final char[] chars) {
if (chars == null) {
@@ -476,21 +470,20 @@ public TextStringBuilder append(final char[] chars) {
/**
* Appends a char array to the string builder. Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
- * @throws StringIndexOutOfBoundsException if {@code startIndex} is not in the
- * range {@code 0 <= startIndex <= chars.length}
- * @throws StringIndexOutOfBoundsException if {@code length < 0}
- * @throws StringIndexOutOfBoundsException if {@code startIndex + length > chars.length}
+ * @param chars the char array to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
+ * @throws StringIndexOutOfBoundsException if {@code startIndex} is not in the range {@code 0 <= startIndex <= chars.length}.
+ * @throws StringIndexOutOfBoundsException if {@code length < 0}.
+ * @throws StringIndexOutOfBoundsException if {@code startIndex + length > chars.length}.
*/
public TextStringBuilder append(final char[] chars, final int startIndex, final int length) {
if (chars == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > chars.length) {
- throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length);
+ throw new StringIndexOutOfBoundsException("Invalid startIndex: " + startIndex);
}
if (length < 0 || startIndex + length > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid length: " + length);
@@ -507,8 +500,8 @@ public TextStringBuilder append(final char[] chars, final int startIndex, final
/**
* Appends the contents of a char buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the char buffer to append
- * @return this, to enable chaining
+ * @param str the char buffer to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final CharBuffer str) {
return append(str, 0, StringUtils.length(str));
@@ -517,10 +510,10 @@ public TextStringBuilder append(final CharBuffer str) {
/**
* Appends the contents of a char buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param buf the char buffer to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param buf the char buffer to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final CharBuffer buf, final int startIndex, final int length) {
if (buf == null) {
@@ -547,8 +540,8 @@ public TextStringBuilder append(final CharBuffer buf, final int startIndex, fina
/**
* Appends a CharSequence to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param seq the CharSequence to append
- * @return this, to enable chaining
+ * @param seq the CharSequence to append.
+ * @return {@code this} instance.
*/
@Override
public TextStringBuilder append(final CharSequence seq) {
@@ -573,10 +566,10 @@ public TextStringBuilder append(final CharSequence seq) {
/**
* Appends part of a CharSequence to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param seq the CharSequence to append
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid
- * @return this, to enable chaining
+ * @param seq the CharSequence to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid.
+ * @return {@code this} instance.
*/
@Override
public TextStringBuilder append(final CharSequence seq, final int startIndex, final int endIndex) {
@@ -595,8 +588,8 @@ public TextStringBuilder append(final CharSequence seq, final int startIndex, fi
/**
* Appends a double value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final double value) {
return append(String.valueOf(value));
@@ -605,8 +598,8 @@ public TextStringBuilder append(final double value) {
/**
* Appends a float value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final float value) {
return append(String.valueOf(value));
@@ -615,8 +608,8 @@ public TextStringBuilder append(final float value) {
/**
* Appends an int value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final int value) {
return append(String.valueOf(value));
@@ -625,8 +618,8 @@ public TextStringBuilder append(final int value) {
/**
* Appends a long value to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final long value) {
return append(String.valueOf(value));
@@ -635,8 +628,8 @@ public TextStringBuilder append(final long value) {
/**
* Appends an object to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param obj the object to append
- * @return this, to enable chaining
+ * @param obj the object to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final Object obj) {
if (obj == null) {
@@ -651,8 +644,8 @@ public TextStringBuilder append(final Object obj) {
/**
* Appends a string to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @return this, to enable chaining
+ * @param str the string to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final String str) {
return append(str, 0, StringUtils.length(str));
@@ -661,14 +654,13 @@ public TextStringBuilder append(final String str) {
/**
* Appends part of a string to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
- * @throws StringIndexOutOfBoundsException if {@code startIndex} is not in the
- * range {@code 0 <= startIndex <= str.length()}
- * @throws StringIndexOutOfBoundsException if {@code length < 0}
- * @throws StringIndexOutOfBoundsException if {@code startIndex + length > str.length()}
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
+ * @throws StringIndexOutOfBoundsException if {@code startIndex} is not in the range {@code 0 <= startIndex <= str.length()}.
+ * @throws StringIndexOutOfBoundsException if {@code length < 0}.
+ * @throws StringIndexOutOfBoundsException if {@code startIndex + length > str.length()}.
*/
public TextStringBuilder append(final String str, final int startIndex, final int length) {
if (str == null) {
@@ -692,9 +684,9 @@ public TextStringBuilder append(final String str, final int startIndex, final in
/**
* Calls {@link String#format(String, Object...)} and appends the result.
*
- * @param format the format string
- * @param objs the objects to use in the format string
- * @return {@code this} to enable chaining
+ * @param format the format string.
+ * @param objs the objects to use in the format string.
+ * @return {@code this} to enable chaining.
* @see String#format(String, Object...)
*/
public TextStringBuilder append(final String format, final Object... objs) {
@@ -704,8 +696,8 @@ public TextStringBuilder append(final String format, final Object... objs) {
/**
* Appends a string buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string buffer to append
- * @return this, to enable chaining
+ * @param str the string buffer to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final StringBuffer str) {
return append(str, 0, StringUtils.length(str));
@@ -714,10 +706,10 @@ public TextStringBuilder append(final StringBuffer str) {
/**
* Appends part of a string buffer to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final StringBuffer str, final int startIndex, final int length) {
if (str == null) {
@@ -741,8 +733,8 @@ public TextStringBuilder append(final StringBuffer str, final int startIndex, fi
/**
* Appends a StringBuilder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the StringBuilder to append
- * @return this, to enable chaining
+ * @param str the StringBuilder to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final StringBuilder str) {
return append(str, 0, StringUtils.length(str));
@@ -751,10 +743,10 @@ public TextStringBuilder append(final StringBuilder str) {
/**
* Appends part of a StringBuilder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the StringBuilder to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param str the StringBuilder to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final StringBuilder str, final int startIndex, final int length) {
if (str == null) {
@@ -778,8 +770,8 @@ public TextStringBuilder append(final StringBuilder str, final int startIndex, f
/**
* Appends another string builder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string builder to append
- * @return this, to enable chaining
+ * @param str the string builder to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final TextStringBuilder str) {
return append(str, 0, StringUtils.length(str));
@@ -788,10 +780,10 @@ public TextStringBuilder append(final TextStringBuilder str) {
/**
* Appends part of a string builder to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder append(final TextStringBuilder str, final int startIndex, final int length) {
if (str == null) {
@@ -813,11 +805,11 @@ public TextStringBuilder append(final TextStringBuilder str, final int startInde
}
/**
- * Appends each item in an iterable to the builder without any separators. Appending a null iterable will have no
- * effect. Each object is appended using {@link #append(Object)}.
+ * Appends each item in an iterable to the builder without any separators. Appending a null iterable will have no effect. Each object is appended using
+ * {@link #append(Object)}.
*
- * @param iterable the iterable to append
- * @return this, to enable chaining
+ * @param iterable the iterable to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendAll(final Iterable> iterable) {
if (iterable != null) {
@@ -827,11 +819,11 @@ public TextStringBuilder appendAll(final Iterable> iterable) {
}
/**
- * Appends each item in an iterator to the builder without any separators. Appending a null iterator will have no
- * effect. Each object is appended using {@link #append(Object)}.
+ * Appends each item in an iterator to the builder without any separators. Appending a null iterator will have no effect. Each object is appended using
+ * {@link #append(Object)}.
*
- * @param it the iterator to append
- * @return this, to enable chaining
+ * @param it the iterator to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendAll(final Iterator> it) {
if (it != null) {
@@ -841,12 +833,12 @@ public TextStringBuilder appendAll(final Iterator> it) {
}
/**
- * Appends each item in an array to the builder without any separators. Appending a null array will have no effect.
- * Each object is appended using {@link #append(Object)}.
+ * Appends each item in an array to the builder without any separators. Appending a null array will have no effect. Each object is appended using
+ * {@link #append(Object)}.
*
- * @param the element type
- * @param array the array to append
- * @return this, to enable chaining
+ * @param the element type.
+ * @param array the array to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendAll(@SuppressWarnings("unchecked") final T... array) {
/*
@@ -873,27 +865,26 @@ private void appendFalse(int index) {
}
/**
- * Appends an object to the builder padding on the left to a fixed width. The {@code String.valueOf} of the
- * {@code int} value is used. If the formatted value is larger than the length, the left hand side is lost.
+ * Appends an object to the builder padding on the left to a fixed width. The {@code String.valueOf} of the {@code int} value is used. If the formatted
+ * value is larger than the length, the left hand side is lost.
*
- * @param value the value to append
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @param width the fixed field width, zero or negative has no effect.
+ * @param padChar the pad character to use.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) {
return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
}
/**
- * Appends an object to the builder padding on the left to a fixed width. The {@code toString} of the object is
- * used. If the object is larger than the length, the left hand side is lost. If the object is null, the null text
- * value is used.
+ * Appends an object to the builder padding on the left to a fixed width. The {@code toString} of the object is used. If the object is larger than the
+ * length, the left hand side is lost. If the object is null, the null text value is used.
*
- * @param obj the object to append, null uses null text
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
- * @return this, to enable chaining
+ * @param obj the object to append, null uses null text.
+ * @param width the fixed field width, zero or negative has no effect.
+ * @param padChar the pad character to use.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) {
if (width > 0) {
@@ -917,27 +908,26 @@ public TextStringBuilder appendFixedWidthPadLeft(final Object obj, final int wid
}
/**
- * Appends an object to the builder padding on the right to a fixed length. The {@code String.valueOf} of the
- * {@code int} value is used. If the object is larger than the length, the right hand side is lost.
+ * Appends an object to the builder padding on the right to a fixed length. The {@code String.valueOf} of the {@code int} value is used. If the object is
+ * larger than the length, the right hand side is lost.
*
- * @param value the value to append
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @param width the fixed field width, zero or negative has no effect.
+ * @param padChar the pad character to use.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) {
return appendFixedWidthPadRight(String.valueOf(value), width, padChar);
}
/**
- * Appends an object to the builder padding on the right to a fixed length. The {@code toString} of the object is
- * used. If the object is larger than the length, the right hand side is lost. If the object is null, null text
- * value is used.
+ * Appends an object to the builder padding on the right to a fixed length. The {@code toString} of the object is used. If the object is larger than the
+ * length, the right hand side is lost. If the object is null, null text value is used.
*
- * @param obj the object to append, null uses null text
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
- * @return this, to enable chaining
+ * @param obj the object to append, null uses null text.
+ * @param width the fixed field width, zero or negative has no effect.
+ * @param padChar the pad character to use.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) {
if (width > 0) {
@@ -962,8 +952,8 @@ public TextStringBuilder appendFixedWidthPadRight(final Object obj, final int wi
/**
* Appends a boolean value followed by a new line to the string builder.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final boolean value) {
return append(value).appendNewLine();
@@ -972,8 +962,8 @@ public TextStringBuilder appendln(final boolean value) {
/**
* Appends a char value followed by a new line to the string builder.
*
- * @param ch the value to append
- * @return this, to enable chaining
+ * @param ch the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final char ch) {
return append(ch).appendNewLine();
@@ -983,8 +973,8 @@ public TextStringBuilder appendln(final char ch) {
* Appends a char array followed by a new line to the string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param chars the char array to append
- * @return this, to enable chaining
+ * @param chars the char array to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final char[] chars) {
return append(chars).appendNewLine();
@@ -994,10 +984,10 @@ public TextStringBuilder appendln(final char[] chars) {
* Appends a char array followed by a new line to the string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param chars the char array to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param chars the char array to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final char[] chars, final int startIndex, final int length) {
return append(chars, startIndex, length).appendNewLine();
@@ -1006,8 +996,8 @@ public TextStringBuilder appendln(final char[] chars, final int startIndex, fina
/**
* Appends a double value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final double value) {
return append(value).appendNewLine();
@@ -1016,8 +1006,8 @@ public TextStringBuilder appendln(final double value) {
/**
* Appends a float value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final float value) {
return append(value).appendNewLine();
@@ -1026,8 +1016,8 @@ public TextStringBuilder appendln(final float value) {
/**
* Appends an int value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final int value) {
return append(value).appendNewLine();
@@ -1036,8 +1026,8 @@ public TextStringBuilder appendln(final int value) {
/**
* Appends a long value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param value the value to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final long value) {
return append(value).appendNewLine();
@@ -1046,8 +1036,8 @@ public TextStringBuilder appendln(final long value) {
/**
* Appends an object followed by a new line to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param obj the object to append
- * @return this, to enable chaining
+ * @param obj the object to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final Object obj) {
return append(obj).appendNewLine();
@@ -1056,8 +1046,8 @@ public TextStringBuilder appendln(final Object obj) {
/**
* Appends a string followed by a new line to this string builder. Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @return this, to enable chaining
+ * @param str the string to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final String str) {
return append(str).appendNewLine();
@@ -1067,10 +1057,10 @@ public TextStringBuilder appendln(final String str) {
* Appends part of a string followed by a new line to this string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final String str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
@@ -1079,9 +1069,9 @@ public TextStringBuilder appendln(final String str, final int startIndex, final
/**
* Calls {@link String#format(String, Object...)} and appends the result.
*
- * @param format the format string
- * @param objs the objects to use in the format string
- * @return {@code this} to enable chaining
+ * @param format the format string.
+ * @param objs the objects to use in the format string.
+ * @return {@code this} to enable chaining.
* @see String#format(String, Object...)
*/
public TextStringBuilder appendln(final String format, final Object... objs) {
@@ -1092,8 +1082,8 @@ public TextStringBuilder appendln(final String format, final Object... objs) {
* Appends a string buffer followed by a new line to this string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param str the string buffer to append
- * @return this, to enable chaining
+ * @param str the string buffer to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final StringBuffer str) {
return append(str).appendNewLine();
@@ -1103,10 +1093,10 @@ public TextStringBuilder appendln(final StringBuffer str) {
* Appends part of a string buffer followed by a new line to this string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final StringBuffer str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
@@ -1116,8 +1106,8 @@ public TextStringBuilder appendln(final StringBuffer str, final int startIndex,
* Appends a string builder followed by a new line to this string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param str the string builder to append
- * @return this, to enable chaining
+ * @param str the string builder to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final StringBuilder str) {
return append(str).appendNewLine();
@@ -1127,10 +1117,10 @@ public TextStringBuilder appendln(final StringBuilder str) {
* Appends part of a string builder followed by a new line to this string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param str the string builder to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param str the string builder to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
@@ -1140,8 +1130,8 @@ public TextStringBuilder appendln(final StringBuilder str, final int startIndex,
* Appends another string builder followed by a new line to this string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param str the string builder to append
- * @return this, to enable chaining
+ * @param str the string builder to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final TextStringBuilder str) {
return append(str).appendNewLine();
@@ -1151,10 +1141,10 @@ public TextStringBuilder appendln(final TextStringBuilder str) {
* Appends part of a string builder followed by a new line to this string builder. Appending null will call
* {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
+ * @param str the string to append.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param length the length to append, must be valid.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendln(final TextStringBuilder str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
@@ -1170,36 +1160,29 @@ public TextStringBuilder appendln(final TextStringBuilder str, final int startIn
* endings even when on Windows.
*
*
- * @return this
+ * @return {@code this} instance.
* @see #getNewLineText()
* @see #setNewLineText(String)
*/
public TextStringBuilder appendNewLine() {
- if (newLine == null) {
- append(System.lineSeparator());
- return this;
- }
- return append(newLine);
+ return append(newLine == null ? System.lineSeparator() : newLine);
}
/**
* Appends the text representing {@code null} to this string builder.
*
- * @return this, to enable chaining
+ * @return {@code this} instance.
*/
public TextStringBuilder appendNull() {
- if (nullText == null) {
- return this;
- }
- return append(nullText);
+ return nullText != null ? append(nullText) : this;
}
/**
* Appends the pad character to the builder the specified number of times.
*
- * @param length the length to append, negative means no append
- * @param padChar the character to append
- * @return this, to enable chaining
+ * @param length the length to append, negative means no append.
+ * @param padChar the character to append.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendPadding(final int length, final char padChar) {
if (length >= 0) {
@@ -1228,33 +1211,26 @@ public TextStringBuilder appendPadding(final int length, final char padChar) {
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use
- * @return this, to enable chaining
+ * @param separator the separator to use.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendSeparator(final char separator) {
- if (isNotEmpty()) {
- append(separator);
- }
- return this;
+ return isEmpty() ? this : append(separator);
}
/**
- * Appends one of both separators to the builder If the builder is currently empty it will append the
- * defaultIfEmpty-separator Otherwise it will append the standard-separator
- *
+ * Appends one of both separators to the builder If the builder is currently empty it will append the defaultIfEmpty-separator Otherwise it will append the
+ * standard-separator
+ *
* The separator is appended using {@link #append(char)}.
+ *
*
- * @param standard the separator if builder is not empty
- * @param defaultIfEmpty the separator if builder is empty
- * @return this, to enable chaining
+ * @param standard the separator if builder is not empty.
+ * @param defaultIfEmpty the separator if builder is empty.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendSeparator(final char standard, final char defaultIfEmpty) {
- if (isEmpty()) {
- append(defaultIfEmpty);
- } else {
- append(standard);
- }
- return this;
+ return append(isEmpty() ? defaultIfEmpty : standard);
}
/**
@@ -1275,15 +1251,12 @@ public TextStringBuilder appendSeparator(final char standard, final char default
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use
- * @param loopIndex the loop index
- * @return this, to enable chaining
+ * @param separator the separator to use.
+ * @param loopIndex the loop index.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendSeparator(final char separator, final int loopIndex) {
- if (loopIndex > 0) {
- append(separator);
- }
- return this;
+ return loopIndex > 0 ? append(separator) : this;
}
/**
@@ -1304,8 +1277,8 @@ public TextStringBuilder appendSeparator(final char separator, final int loopInd
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use, null means no separator
- * @return this, to enable chaining
+ * @param separator the separator to use, null means no separator.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendSeparator(final String separator) {
return appendSeparator(separator, null);
@@ -1329,15 +1302,12 @@ public TextStringBuilder appendSeparator(final String separator) {
* Note that for this simple example, you should use {@link #appendWithSeparators(Iterable, String)}.
*
*
- * @param separator the separator to use, null means no separator
- * @param loopIndex the loop index
- * @return this, to enable chaining
+ * @param separator the separator to use, null means no separator.
+ * @param loopIndex the loop index.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendSeparator(final String separator, final int loopIndex) {
- if (separator != null && loopIndex > 0) {
- append(separator);
- }
- return this;
+ return separator != null && loopIndex > 0 ? append(separator) : this;
}
/**
@@ -1363,16 +1333,13 @@ public TextStringBuilder appendSeparator(final String separator, final int loopI
* selectClause.append(whereClause)
*
*
- * @param standard the separator if builder is not empty, null means no separator
- * @param defaultIfEmpty the separator if builder is empty, null means no separator
- * @return this, to enable chaining
+ * @param standard the separator if builder is not empty, null means no separator.
+ * @param defaultIfEmpty the separator if builder is empty, null means no separator.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendSeparator(final String standard, final String defaultIfEmpty) {
final String str = isEmpty() ? defaultIfEmpty : standard;
- if (str != null) {
- append(str);
- }
- return this;
+ return str != null ? append(str) : this;
}
/**
@@ -1381,7 +1348,7 @@ public TextStringBuilder appendSeparator(final String standard, final String def
* This method tries to avoid doing any extra copies of contents.
*
*
- * @param appendable the appendable to append data to
+ * @param appendable the appendable to append data to.
* @throws IOException if an I/O error occurs.
* @see #readFrom(Readable)
*/
@@ -1412,9 +1379,9 @@ private void appendTrue(int index) {
* Appends an iterable placing separators between each value, but not before the first or after the last. Appending
* a null iterable will have no effect. Each object is appended using {@link #append(Object)}.
*
- * @param iterable the iterable to append
- * @param separator the separator to use, null means no separator
- * @return this, to enable chaining
+ * @param iterable the iterable to append.
+ * @param separator the separator to use, null means no separator.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendWithSeparators(final Iterable> iterable, final String separator) {
if (iterable != null) {
@@ -1427,9 +1394,9 @@ public TextStringBuilder appendWithSeparators(final Iterable> iterable, final
* Appends an iterator placing separators between each value, but not before the first or after the last. Appending
* a null iterator will have no effect. Each object is appended using {@link #append(Object)}.
*
- * @param it the iterator to append
- * @param separator the separator to use, null means no separator
- * @return this, to enable chaining
+ * @param it the iterator to append.
+ * @param separator the separator to use, null means no separator.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendWithSeparators(final Iterator> it, final String separator) {
if (it != null) {
@@ -1448,17 +1415,16 @@ public TextStringBuilder appendWithSeparators(final Iterator> it, final String
* Appends an array placing separators between each value, but not before the first or after the last. Appending a
* null array will have no effect. Each object is appended using {@link #append(Object)}.
*
- * @param array the array to append
- * @param separator the separator to use, null means no separator
- * @return this, to enable chaining
+ * @param array the array to append.
+ * @param separator the separator to use, null means no separator.
+ * @return {@code this} instance.
*/
public TextStringBuilder appendWithSeparators(final Object[] array, final String separator) {
if (array != null && array.length > 0) {
final String sep = Objects.toString(separator, StringUtils.EMPTY);
append(array[0]);
for (int i = 1; i < array.length; i++) {
- append(sep);
- append(array[i]);
+ append(sep).append(array[i]);
}
}
return this;
@@ -1481,7 +1447,7 @@ public TextStringBuilder appendWithSeparators(final Object[] array, final String
* The returned reader supports marking, and ignores the flush method.
*
*
- * @return a reader that reads from this builder
+ * @return a reader that reads from this builder.
*/
public Reader asReader() {
return new TextStringBuilderReader();
@@ -1520,7 +1486,7 @@ public Reader asReader() {
* break the link with the builder.
*
*
- * @return a tokenizer that is linked to this builder
+ * @return a tokenizer that is linked to this builder.
*/
public StringTokenizer asTokenizer() {
return new TextStringBuilderTokenizer();
@@ -1544,7 +1510,7 @@ public StringTokenizer asTokenizer() {
* The returned writer ignores the close and flush methods.
*
*
- * @return a writer that populates this builder
+ * @return a writer that populates this builder.
*/
public Writer asWriter() {
return new TextStringBuilderWriter();
@@ -1553,7 +1519,7 @@ public Writer asWriter() {
/**
* Converts this instance to a String.
*
- * @return This instance as a String
+ * @return This instance as a String.
* @see #toString()
* @deprecated Use {@link #get()}.
*/
@@ -1566,7 +1532,7 @@ public String build() {
/**
* Gets the current size of the internal character array buffer.
*
- * @return The capacity
+ * @return The capacity.
*/
public int capacity() {
return buffer.length;
@@ -1575,11 +1541,11 @@ public int capacity() {
/**
* Gets the character at the specified index.
*
+ * @param index the index to retrieve, must be valid.
+ * @return The character at the index.
+ * @throws IndexOutOfBoundsException if the index is invalid.
* @see #setCharAt(int, char)
* @see #deleteCharAt(int)
- * @param index the index to retrieve, must be valid
- * @return The character at the index
- * @throws IndexOutOfBoundsException if the index is invalid
*/
@Override
public char charAt(final int index) {
@@ -1598,7 +1564,7 @@ public char charAt(final int index) {
* Collections.
*
*
- * @return this, to enable chaining
+ * @return {@code this} instance.
*/
public TextStringBuilder clear() {
size = 0;
@@ -1608,8 +1574,8 @@ public TextStringBuilder clear() {
/**
* Tests if the string builder contains the specified char.
*
- * @param ch the character to find
- * @return true if the builder contains the character
+ * @param ch the character to find.
+ * @return true if the builder contains the character.
*/
public boolean contains(final char ch) {
final char[] thisBuf = buffer;
@@ -1624,8 +1590,8 @@ public boolean contains(final char ch) {
/**
* Tests if the string builder contains the specified string.
*
- * @param str the string to find
- * @return true if the builder contains the string
+ * @param str the string to find.
+ * @return true if the builder contains the string.
*/
public boolean contains(final String str) {
return indexOf(str, 0) >= 0;
@@ -1638,8 +1604,8 @@ public boolean contains(final String str) {
* the character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @return true if the matcher finds a match in the builder
+ * @param matcher the matcher to use, null returns -1.
+ * @return true if the matcher finds a match in the builder.
*/
public boolean contains(final StringMatcher matcher) {
return indexOf(matcher, 0) >= 0;
@@ -1648,10 +1614,10 @@ public boolean contains(final StringMatcher matcher) {
/**
* Deletes the characters between the two specified indices.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder delete(final int startIndex, final int endIndex) {
final int actualEndIndex = validateRange(startIndex, endIndex);
@@ -1665,8 +1631,8 @@ public TextStringBuilder delete(final int startIndex, final int endIndex) {
/**
* Deletes the character wherever it occurs in the builder.
*
- * @param ch the character to delete
- * @return this, to enable chaining
+ * @param ch the character to delete.
+ * @return {@code this} instance.
*/
public TextStringBuilder deleteAll(final char ch) {
for (int i = 0; i < size; i++) {
@@ -1688,8 +1654,8 @@ public TextStringBuilder deleteAll(final char ch) {
/**
* Deletes the string wherever it occurs in the builder.
*
- * @param str the string to delete, null causes no action
- * @return this, to enable chaining
+ * @param str the string to delete, null causes no action.
+ * @return {@code this} instance.
*/
public TextStringBuilder deleteAll(final String str) {
final int len = str == null ? 0 : str.length();
@@ -1710,8 +1676,8 @@ public TextStringBuilder deleteAll(final String str) {
* occurrences where the character 'a' is followed by a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @return this, to enable chaining
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @return {@code this} instance.
*/
public TextStringBuilder deleteAll(final StringMatcher matcher) {
return replace(matcher, null, 0, size, -1);
@@ -1720,11 +1686,11 @@ public TextStringBuilder deleteAll(final StringMatcher matcher) {
/**
* Deletes the character at the specified index.
*
+ * @param index the index to delete.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
* @see #charAt(int)
* @see #setCharAt(int, char)
- * @param index the index to delete
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
*/
public TextStringBuilder deleteCharAt(final int index) {
validateIndex(index);
@@ -1735,8 +1701,8 @@ public TextStringBuilder deleteCharAt(final int index) {
/**
* Deletes the character wherever it occurs in the builder.
*
- * @param ch the character to delete
- * @return this, to enable chaining
+ * @param ch the character to delete.
+ * @return {@code this} instance.
*/
public TextStringBuilder deleteFirst(final char ch) {
for (int i = 0; i < size; i++) {
@@ -1751,8 +1717,8 @@ public TextStringBuilder deleteFirst(final char ch) {
/**
* Deletes the string wherever it occurs in the builder.
*
- * @param str the string to delete, null causes no action
- * @return this, to enable chaining
+ * @param str the string to delete, null causes no action.
+ * @return {@code this} instance.
*/
public TextStringBuilder deleteFirst(final String str) {
final int len = str == null ? 0 : str.length();
@@ -1772,8 +1738,8 @@ public TextStringBuilder deleteFirst(final String str) {
* the character 'a' is followed by a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @return this, to enable chaining
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @return {@code this} instance.
*/
public TextStringBuilder deleteFirst(final StringMatcher matcher) {
return replace(matcher, null, 0, size, 1);
@@ -1782,10 +1748,10 @@ public TextStringBuilder deleteFirst(final StringMatcher matcher) {
/**
* Internal method to delete a range without validation.
*
- * @param startIndex the start index, must be valid
- * @param endIndex the end index (exclusive), must be valid
- * @param len the length, must be valid
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param startIndex the start index, must be valid.
+ * @param endIndex the end index (exclusive), must be valid.
+ * @param len the length, must be valid.
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
private void deleteImpl(final int startIndex, final int endIndex, final int len) {
System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex);
@@ -1795,12 +1761,12 @@ private void deleteImpl(final int startIndex, final int endIndex, final int len)
/**
* Gets the character at the specified index before deleting it.
*
- * @see #charAt(int)
- * @see #deleteCharAt(int)
* @param index the index to retrieve, must be valid
* @return The character at the index
* @throws IndexOutOfBoundsException if the index is invalid
* @since 1.9
+ * @see #charAt(int)
+ * @see #deleteCharAt(int)
*/
public char drainChar(final int index) {
validateIndex(index);
@@ -1837,8 +1803,8 @@ public int drainChars(final int startIndex, final int endIndex, final char[] tar
* Note that this method handles null input quietly, unlike String.
*
*
- * @param str the string to search for, null returns false
- * @return true if the builder ends with the string
+ * @param str the string to search for, null returns false.
+ * @return true if the builder ends with the string.
*/
public boolean endsWith(final String str) {
if (str == null) {
@@ -1869,9 +1835,9 @@ public boolean endsWith(final String str) {
* The method ignores a negative {@code capacity} argument.
*
*
- * @param capacity the capacity to ensure
- * @return this, to enable chaining
- * @throws OutOfMemoryError if the capacity cannot be allocated
+ * @param capacity the capacity to ensure.
+ * @return {@code this} instance.
+ * @throws OutOfMemoryError if the capacity cannot be allocated.
*/
public TextStringBuilder ensureCapacity(final int capacity) {
if (capacity > 0) {
@@ -1889,8 +1855,8 @@ public TextStringBuilder ensureCapacity(final int capacity) {
* for an array, or cannot be allocated.
*
*
- * @param capacity the capacity to ensure
- * @throws OutOfMemoryError if the capacity cannot be allocated
+ * @param capacity the capacity to ensure.
+ * @throws OutOfMemoryError if the capacity cannot be allocated.
*/
private void ensureCapacityInternal(final int capacity) {
// Check for overflow of the current buffer.
@@ -1904,8 +1870,8 @@ private void ensureCapacityInternal(final int capacity) {
/**
* Tests the contents of this builder against another to see if they contain the same character content.
*
- * @param obj the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param obj the object to check, null returns false.
+ * @return true if the builders contain the same characters in the same order.
*/
@Override
public boolean equals(final Object obj) {
@@ -1915,8 +1881,8 @@ public boolean equals(final Object obj) {
/**
* Tests the contents of this builder against another to see if they contain the same character content.
*
- * @param other the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param other the object to check, null returns false.
+ * @return true if the builders contain the same characters in the same order.
*/
public boolean equals(final TextStringBuilder other) {
if (this == other) {
@@ -1944,8 +1910,8 @@ public boolean equals(final TextStringBuilder other) {
* Tests the contents of this builder against another to see if they contain the same character content ignoring
* case.
*
- * @param other the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param other the object to check, null returns false.
+ * @return true if the builders contain the same characters in the same order.
*/
public boolean equalsIgnoreCase(final TextStringBuilder other) {
if (this == other) {
@@ -1969,7 +1935,7 @@ public boolean equalsIgnoreCase(final TextStringBuilder other) {
/**
* Converts this instance to a String.
*
- * @return This instance as a String
+ * @return This instance as a String.
* @see #toString()
* @since 1.12.0
*/
@@ -1988,8 +1954,8 @@ char[] getBuffer() {
/**
* Copies this character array into the specified array.
*
- * @param target the target array, null will cause an array to be created
- * @return The input array, unless that was null or too small
+ * @param target the target array, null will cause an array to be created.
+ * @return The input array, unless that was null or too small.
*/
public char[] getChars(char[] target) {
final int len = length();
@@ -2035,7 +2001,7 @@ public String getNewLineText() {
/**
* Gets the text to be appended when null is added.
*
- * @return The null text, null means no append
+ * @return The null text, null means no append.
*/
public String getNullText() {
return nullText;
@@ -2044,7 +2010,7 @@ public String getNullText() {
/**
* Gets a suitable hash code for this builder.
*
- * @return a hash code
+ * @return a hash code.
*/
@Override
public int hashCode() {
@@ -2060,8 +2026,8 @@ public int hashCode() {
/**
* Searches the string builder to find the first reference to the specified char.
*
- * @param ch the character to find
- * @return The first index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @return The first index of the character, or -1 if not found.
*/
public int indexOf(final char ch) {
return indexOf(ch, 0);
@@ -2070,9 +2036,9 @@ public int indexOf(final char ch) {
/**
* Searches the string builder to find the first reference to the specified char.
*
- * @param ch the character to find
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The first index of the character, or -1 if not found.
*/
public int indexOf(final char ch, int startIndex) {
startIndex = Math.max(0, startIndex);
@@ -2094,8 +2060,8 @@ public int indexOf(final char ch, int startIndex) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @return The first index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @return The first index of the string, or -1 if not found.
*/
public int indexOf(final String str) {
return indexOf(str, 0);
@@ -2108,9 +2074,9 @@ public int indexOf(final String str) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The first index of the string, or -1 if not found.
*/
public int indexOf(final String str, int startIndex) {
startIndex = Math.max(0, startIndex);
@@ -2128,14 +2094,15 @@ public int indexOf(final String str, int startIndex) {
return StringUtils.INDEX_NOT_FOUND;
}
final char[] thisBuf = buffer;
- final int len = size - strLen + 1;
- outer: for (int i = startIndex; i < len; i++) {
- for (int j = 0; j < strLen; j++) {
- if (str.charAt(j) != thisBuf[i + j]) {
- continue outer;
- }
+ final int searchLen = size - strLen + 1;
+ for (int i = startIndex; i < searchLen; i++) {
+ boolean found = true;
+ for (int j = 0; j < strLen && found; j++) {
+ found = str.charAt(j) == thisBuf[i + j];
+ }
+ if (found) {
+ return i;
}
- return i;
}
return StringUtils.INDEX_NOT_FOUND;
}
@@ -2147,8 +2114,8 @@ public int indexOf(final String str, int startIndex) {
* character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @return The first index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @return The first index matched, or -1 if not found.
*/
public int indexOf(final StringMatcher matcher) {
return indexOf(matcher, 0);
@@ -2161,9 +2128,9 @@ public int indexOf(final StringMatcher matcher) {
* character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The first index matched, or -1 if not found.
*/
public int indexOf(final StringMatcher matcher, int startIndex) {
startIndex = Math.max(0, startIndex);
@@ -2183,13 +2150,13 @@ public int indexOf(final StringMatcher matcher, int startIndex) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final boolean value) {
- validateIndex(index);
+ validateRange(index, size);
if (value) {
ensureCapacityInternal(size + TRUE_STRING_SIZE);
System.arraycopy(buffer, index, buffer, index + TRUE_STRING_SIZE, size - index);
@@ -2205,13 +2172,13 @@ public TextStringBuilder insert(final int index, final boolean value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final char value) {
- validateIndex(index);
+ validateRange(index, size);
ensureCapacityInternal(size + 1);
System.arraycopy(buffer, index, buffer, index + 1, size - index);
buffer[index] = value;
@@ -2222,13 +2189,13 @@ public TextStringBuilder insert(final int index, final char value) {
/**
* Inserts the character array into this builder. Inserting null will use the stored null text value.
*
- * @param index the index to add at, must be valid
- * @param chars the char array to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param chars the char array to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final char[] chars) {
- validateIndex(index);
+ validateRange(index, size);
if (chars == null) {
return insert(index, nullText);
}
@@ -2245,15 +2212,15 @@ public TextStringBuilder insert(final int index, final char[] chars) {
/**
* Inserts part of the character array into this builder. Inserting null will use the stored null text value.
*
- * @param index the index to add at, must be valid
- * @param chars the char array to insert
- * @param offset the offset into the character array to start at, must be valid
- * @param length the length of the character array part to copy, must be positive
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param index the index to add at, must be valid.
+ * @param chars the char array to insert.
+ * @param offset the offset into the character array to start at, must be valid.
+ * @param length the length of the character array part to copy, must be positive.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
public TextStringBuilder insert(final int index, final char[] chars, final int offset, final int length) {
- validateIndex(index);
+ validateRange(index, size);
if (chars == null) {
return insert(index, nullText);
}
@@ -2275,10 +2242,10 @@ public TextStringBuilder insert(final int index, final char[] chars, final int o
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final double value) {
return insert(index, String.valueOf(value));
@@ -2287,10 +2254,10 @@ public TextStringBuilder insert(final int index, final double value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final float value) {
return insert(index, String.valueOf(value));
@@ -2299,10 +2266,10 @@ public TextStringBuilder insert(final int index, final float value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final int value) {
return insert(index, String.valueOf(value));
@@ -2311,10 +2278,10 @@ public TextStringBuilder insert(final int index, final int value) {
/**
* Inserts the value into this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param value the value to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final long value) {
return insert(index, String.valueOf(value));
@@ -2324,28 +2291,25 @@ public TextStringBuilder insert(final int index, final long value) {
* Inserts the string representation of an object into this builder. Inserting null will use the stored null text
* value.
*
- * @param index the index to add at, must be valid
- * @param obj the object to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param obj the object to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, final Object obj) {
- if (obj == null) {
- return insert(index, nullText);
- }
- return insert(index, obj.toString());
+ return insert(index, Objects.toString(obj, nullText));
}
/**
* Inserts the string into this builder. Inserting null will use the stored null text value.
*
- * @param index the index to add at, must be valid
- * @param str the string to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param index the index to add at, must be valid.
+ * @param str the string to insert.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder insert(final int index, String str) {
- validateIndex(index);
+ validateRange(index, size);
if (str == null) {
str = nullText;
}
@@ -2400,8 +2364,8 @@ public boolean isReallocated() {
/**
* Searches the string builder to find the last reference to the specified char.
*
- * @param ch the character to find
- * @return The last index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @return The last index of the character, or -1 if not found.
*/
public int lastIndexOf(final char ch) {
return lastIndexOf(ch, size - 1);
@@ -2410,9 +2374,9 @@ public int lastIndexOf(final char ch) {
/**
* Searches the string builder to find the last reference to the specified char.
*
- * @param ch the character to find
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index of the character, or -1 if not found
+ * @param ch the character to find.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The last index of the character, or -1 if not found.
*/
public int lastIndexOf(final char ch, int startIndex) {
startIndex = startIndex >= size ? size - 1 : startIndex;
@@ -2433,8 +2397,8 @@ public int lastIndexOf(final char ch, int startIndex) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @return The last index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @return The last index of the string, or -1 if not found.
*/
public int lastIndexOf(final String str) {
return lastIndexOf(str, size - 1);
@@ -2447,9 +2411,9 @@ public int lastIndexOf(final String str) {
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
*
- * @param str the string to find, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index of the string, or -1 if not found
+ * @param str the string to find, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The last index of the string, or -1 if not found.
*/
public int lastIndexOf(final String str, int startIndex) {
startIndex = startIndex >= size ? size - 1 : startIndex;
@@ -2457,22 +2421,23 @@ public int lastIndexOf(final String str, int startIndex) {
return StringUtils.INDEX_NOT_FOUND;
}
final int strLen = str.length();
- if (strLen > 0 && strLen <= size) {
- if (strLen == 1) {
- return lastIndexOf(str.charAt(0), startIndex);
+ if (strLen == 0) {
+ return startIndex;
+ }
+ if (strLen > size) {
+ return StringUtils.INDEX_NOT_FOUND;
+ }
+ if (strLen == 1) {
+ return lastIndexOf(str.charAt(0), startIndex);
+ }
+ for (int i = startIndex - strLen + 1; i >= 0; i--) {
+ boolean found = true;
+ for (int j = 0; j < strLen && found; j++) {
+ found = str.charAt(j) == buffer[i + j];
}
-
- outer: for (int i = startIndex - strLen + 1; i >= 0; i--) {
- for (int j = 0; j < strLen; j++) {
- if (str.charAt(j) != buffer[i + j]) {
- continue outer;
- }
- }
+ if (found) {
return i;
}
-
- } else if (strLen == 0) {
- return startIndex;
}
return StringUtils.INDEX_NOT_FOUND;
}
@@ -2484,8 +2449,8 @@ public int lastIndexOf(final String str, int startIndex) {
* character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @return The last index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @return The last index matched, or -1 if not found.
*/
public int lastIndexOf(final StringMatcher matcher) {
return lastIndexOf(matcher, size);
@@ -2498,9 +2463,9 @@ public int lastIndexOf(final StringMatcher matcher) {
* character 'a' followed by a number.
*
*
- * @param matcher the matcher to use, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index matched, or -1 if not found
+ * @param matcher the matcher to use, null returns -1.
+ * @param startIndex the index to start at, invalid index rounded to edge.
+ * @return The last index matched, or -1 if not found.
*/
public int lastIndexOf(final StringMatcher matcher, int startIndex) {
startIndex = startIndex >= size ? size - 1 : startIndex;
@@ -2524,8 +2489,8 @@ public int lastIndexOf(final StringMatcher matcher, int startIndex) {
* available, the whole builder is returned. Thus the returned string may be shorter than the length requested.
*
*
- * @param length the number of characters to extract, negative returns empty string
- * @return The new string
+ * @param length the number of characters to extract, negative returns empty string.
+ * @return The new string.
*/
public String leftString(final int length) {
if (length <= 0) {
@@ -2556,9 +2521,9 @@ public int length() {
* much as possible is returned. Thus the returned string may be shorter than the length requested.
*
*
- * @param index the index to start at, negative means zero
- * @param length the number of characters to extract, negative returns empty string
- * @return The new string
+ * @param index the index to start at, negative means zero.
+ * @param length the number of characters to extract, negative returns empty string.
+ * @return The new string.
*/
public String midString(int index, final int length) {
if (index < 0) {
@@ -2576,7 +2541,7 @@ public String midString(int index, final int length) {
/**
* Minimizes the capacity to the actual length of the string.
*
- * @return this, to enable chaining
+ * @return {@code this} instance.
*/
public TextStringBuilder minimizeCapacity() {
if (buffer.length > size) {
@@ -2607,8 +2572,8 @@ public int readFrom(final CharBuffer charBuffer) {
* If possible, reads all chars from the provided {@link Readable} directly into underlying character buffer without
* making extra copies.
*
- * @param readable object to read from
- * @return The number of characters read
+ * @param readable object to read from.
+ * @return The number of characters read.
* @throws IOException if an I/O error occurs.
* @see #appendTo(Appendable)
*/
@@ -2658,13 +2623,11 @@ public int readFrom(final Reader reader) throws IOException {
}
/**
- * If possible, reads {@code count} chars from the provided {@link Reader} directly into underlying character buffer
- * without making extra copies.
+ * If possible, reads {@code count} chars from the provided {@link Reader} directly into underlying character buffer without making extra copies.
*
* @param reader Reader to read.
- * @param count The maximum characters to read, a value <= 0 returns 0.
- * @return The number of characters read. If less than {@code count}, then we've reached the end-of-stream, or -1 if
- * we reached the end of stream.
+ * @param count The maximum characters to read, a value <= 0 returns 0.
+ * @return The number of characters read. If less than {@code count}, then we've reached the end-of-stream, or -1 if we reached the end of stream.
* @throws IOException if an I/O error occurs.
* @see #appendTo(Appendable)
* @since 1.9
@@ -2691,7 +2654,7 @@ public int readFrom(final Reader reader, final int count) throws IOException {
/**
* Reallocates the buffer to the new length.
*
- * @param newLength the length of the copy to be returned
+ * @param newLength the length of the copy to be returned.
*/
private void reallocate(final int newLength) {
this.buffer = Arrays.copyOf(buffer, newLength);
@@ -2699,14 +2662,13 @@ private void reallocate(final int newLength) {
}
/**
- * Replaces a portion of the string builder with another string. The length of the inserted string does not have to
- * match the removed length.
+ * Replaces a portion of the string builder with another string. The length of the inserted string does not have to match the removed length.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @param replaceStr the string to replace with, null means delete range
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @param replaceStr the string to replace with, null means delete range.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public TextStringBuilder replace(final int startIndex, int endIndex, final String replaceStr) {
endIndex = validateRange(startIndex, endIndex);
@@ -2718,17 +2680,17 @@ public TextStringBuilder replace(final int startIndex, int endIndex, final Strin
/**
* Advanced search and replaces within the builder using a matcher.
*
- * Matchers can be used to perform advanced behavior. For example you could write a matcher to delete all
- * occurrences where the character 'a' is followed by a number.
+ * Matchers can be used to perform advanced behavior. For example you could write a matcher to delete all occurrences where the character 'a' is followed by
+ * a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the string to replace the match with, null is a delete
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @param replaceCount the number of times to replace, -1 for replace all
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if start index is invalid
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the string to replace the match with, null is a delete.
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @param replaceCount the number of times to replace, -1 for replace all.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if start index is invalid.
*/
public TextStringBuilder replace(final StringMatcher matcher, final String replaceStr, final int startIndex,
int endIndex, final int replaceCount) {
@@ -2739,9 +2701,9 @@ public TextStringBuilder replace(final StringMatcher matcher, final String repla
/**
* Replaces the search character with the replace character throughout the builder.
*
- * @param search the search character
- * @param replace the replace character
- * @return this, to enable chaining
+ * @param search the search character.
+ * @param replace the replace character.
+ * @return {@code this} instance.
*/
public TextStringBuilder replaceAll(final char search, final char replace) {
if (search != replace) {
@@ -2757,9 +2719,9 @@ public TextStringBuilder replaceAll(final char search, final char replace) {
/**
* Replaces the search string with the replace string throughout the builder.
*
- * @param searchStr the search string, null causes no action to occur
- * @param replaceStr the replace string, null is equivalent to an empty string
- * @return this, to enable chaining
+ * @param searchStr the search string, null causes no action to occur.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
+ * @return {@code this} instance.
*/
public TextStringBuilder replaceAll(final String searchStr, final String replaceStr) {
final int searchLen = searchStr == null ? 0 : searchStr.length();
@@ -2781,9 +2743,9 @@ public TextStringBuilder replaceAll(final String searchStr, final String replace
* occurrences where the character 'a' is followed by a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the replace string, null is equivalent to an empty string
- * @return this, to enable chaining
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
+ * @return {@code this} instance.
*/
public TextStringBuilder replaceAll(final StringMatcher matcher, final String replaceStr) {
return replace(matcher, replaceStr, 0, size, -1);
@@ -2792,9 +2754,9 @@ public TextStringBuilder replaceAll(final StringMatcher matcher, final String re
/**
* Replaces the first instance of the search character with the replace character in the builder.
*
- * @param search the search character
- * @param replace the replace character
- * @return this, to enable chaining
+ * @param search the search character.
+ * @param replace the replace character.
+ * @return {@code this} instance.
*/
public TextStringBuilder replaceFirst(final char search, final char replace) {
if (search != replace) {
@@ -2811,9 +2773,9 @@ public TextStringBuilder replaceFirst(final char search, final char replace) {
/**
* Replaces the first instance of the search string with the replace string.
*
- * @param searchStr the search string, null causes no action to occur
- * @param replaceStr the replace string, null is equivalent to an empty string
- * @return this, to enable chaining
+ * @param searchStr the search string, null causes no action to occur.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
+ * @return {@code this} instance.
*/
public TextStringBuilder replaceFirst(final String searchStr, final String replaceStr) {
final int searchLen = searchStr == null ? 0 : searchStr.length();
@@ -2834,9 +2796,9 @@ public TextStringBuilder replaceFirst(final String searchStr, final String repla
* the character 'a' is followed by a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the replace string, null is equivalent to an empty string
- * @return this, to enable chaining
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the replace string, null is equivalent to an empty string.
+ * @return {@code this} instance.
*/
public TextStringBuilder replaceFirst(final StringMatcher matcher, final String replaceStr) {
return replace(matcher, replaceStr, 0, size, 1);
@@ -2845,12 +2807,12 @@ public TextStringBuilder replaceFirst(final StringMatcher matcher, final String
/**
* Internal method to delete a range without validation.
*
- * @param startIndex the start index, must be valid
- * @param endIndex the end index (exclusive), must be valid
- * @param removeLen the length to remove (endIndex - startIndex), must be valid
- * @param insertStr the string to replace with, null means delete range
- * @param insertLen the length of the insert string, must be valid
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param startIndex the start index, must be valid.
+ * @param endIndex the end index (exclusive), must be valid.
+ * @param removeLen the length to remove (endIndex - startIndex), must be valid.
+ * @param insertStr the string to replace with, null means delete range.
+ * @param insertLen the length of the insert string, must be valid.
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
private void replaceImpl(final int startIndex, final int endIndex, final int removeLen, final String insertStr,
final int insertLen) {
@@ -2872,13 +2834,13 @@ private void replaceImpl(final int startIndex, final int endIndex, final int rem
* occurrences where the character 'a' is followed by a number.
*
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the string to replace the match with, null is a delete
- * @param from the start index, must be valid
- * @param to the end index (exclusive), must be valid
- * @param replaceCount the number of times to replace, -1 for replace all
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param matcher the matcher to use to find the deletion, null causes no action.
+ * @param replaceStr the string to replace the match with, null is a delete.
+ * @param from the start index, must be valid.
+ * @param to the end index (exclusive), must be valid.
+ * @param replaceCount the number of times to replace, -1 for replace all.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if any index is invalid.
*/
private TextStringBuilder replaceImpl(final StringMatcher matcher, final String replaceStr, final int from, int to,
int replaceCount) {
@@ -2904,8 +2866,8 @@ private TextStringBuilder replaceImpl(final StringMatcher matcher, final String
/**
* Resizes the buffer to at least the size specified.
*
- * @param minCapacity the minimum required capacity
- * @throws OutOfMemoryError if the {@code minCapacity} is negative
+ * @param minCapacity the minimum required capacity.
+ * @throws OutOfMemoryError if the {@code minCapacity} is negative.
*/
private void resizeBuffer(final int minCapacity) {
// Overflow-conscious code treats the min and new capacity as unsigned.
@@ -2923,13 +2885,12 @@ private void resizeBuffer(final int minCapacity) {
/**
* Reverses the string builder placing each character in the opposite index.
*
- * @return this, to enable chaining
+ * @return {@code this} instance.
*/
public TextStringBuilder reverse() {
if (size == 0) {
return this;
}
-
final int half = size / 2;
final char[] buf = buffer;
for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++, rightIdx--) {
@@ -2947,8 +2908,8 @@ public TextStringBuilder reverse() {
* available, the whole builder is returned. Thus the returned string may be shorter than the length requested.
*
*
- * @param length the number of characters to extract, negative returns empty string
- * @return The new string
+ * @param length the number of characters to extract, negative returns empty string.
+ * @return The new string.
*/
public String rightString(final int length) {
if (length <= 0) {
@@ -2963,27 +2924,25 @@ public String rightString(final int length) {
/**
* Clears and sets this builder to the given value.
*
- * @see #charAt(int)
- * @see #deleteCharAt(int)
* @param str the new value.
- * @return this, to enable chaining
+ * @return {@code this} instance.
* @since 1.9
+ * @see #charAt(int)
+ * @see #deleteCharAt(int)
*/
public TextStringBuilder set(final CharSequence str) {
- clear();
- append(str);
- return this;
+ return clear().append(str);
}
/**
* Sets the character at the specified index.
*
- * @see #charAt(int)
- * @see #deleteCharAt(int)
* @param index the index to set
* @param ch the new character
- * @return this, to enable chaining
+ * @return {@code this} instance.
* @throws IndexOutOfBoundsException if the index is invalid
+ * @see #charAt(int)
+ * @see #deleteCharAt(int)
*/
public TextStringBuilder setCharAt(final int index, final char ch) {
validateIndex(index);
@@ -2994,9 +2953,9 @@ public TextStringBuilder setCharAt(final int index, final char ch) {
/**
* Updates the length of the builder by either dropping the last characters or adding filler of Unicode zero.
*
- * @param length the length to set to, must be zero or positive
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the length is negative
+ * @param length the length to set to, must be zero or positive.
+ * @return {@code this} instance.
+ * @throws IndexOutOfBoundsException if the length is negative.
*/
public TextStringBuilder setLength(final int length) {
if (length < 0) {
@@ -3017,7 +2976,7 @@ public TextStringBuilder setLength(final int length) {
* Sets the text to be appended when {@link #appendNewLine() new line} is called.
*
* @param newLine the new line text, {@code null} means use the system default from {@link System#lineSeparator()}.
- * @return this instance.
+ * @return {@code this} instance.
*/
public TextStringBuilder setNewLineText(final String newLine) {
this.newLine = newLine;
@@ -3027,8 +2986,8 @@ public TextStringBuilder setNewLineText(final String newLine) {
/**
* Sets the text to be appended when null is added.
*
- * @param nullText the null text, null means no append
- * @return this, to enable chaining
+ * @param nullText the null text, null means no append.
+ * @return {@code this} instance.
*/
public TextStringBuilder setNullText(String nullText) {
if (nullText != null && nullText.isEmpty()) {
@@ -3044,7 +3003,7 @@ public TextStringBuilder setNullText(String nullText) {
* This method is the same as {@link #length()} and is provided to match the API of Collections.
*
*
- * @return The length
+ * @return The length.
*/
public int size() {
return size;
@@ -3056,8 +3015,8 @@ public int size() {
* Note that this method handles null input quietly, unlike String.
*
*
- * @param str the string to search for, null returns false
- * @return true if the builder starts with the string
+ * @param str the string to search for, null returns false.
+ * @return true if the builder starts with the string.
*/
public boolean startsWith(final String str) {
if (str == null) {
@@ -3098,9 +3057,9 @@ public CharSequence subSequence(final int startIndex, final int endIndex) {
/**
* Extracts a portion of this string builder as a string.
*
- * @param start the start index, inclusive, must be valid
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param start the start index, inclusive, must be valid.
+ * @return The new string.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public String substring(final int start) {
return substring(start, size);
@@ -3113,10 +3072,10 @@ public String substring(final int start) {
* builder, and continues without error, unlike StringBuffer or String.
*
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @return The new string.
+ * @throws IndexOutOfBoundsException if the index is invalid.
*/
public String substring(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
@@ -3126,7 +3085,7 @@ public String substring(final int startIndex, int endIndex) {
/**
* Copies the builder's character array into a new character array.
*
- * @return a new array that represents the contents of the builder
+ * @return a new array that represents the contents of the builder.
*/
public char[] toCharArray() {
return size == 0 ? ArrayUtils.EMPTY_CHAR_ARRAY : Arrays.copyOf(buffer, size);
@@ -3135,11 +3094,10 @@ public char[] toCharArray() {
/**
* Copies part of the builder's character array into a new character array.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
- * @return a new array that holds part of the contents of the builder
- * @throws IndexOutOfBoundsException if startIndex is invalid, or if endIndex is invalid (but endIndex greater than
- * size is valid)
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
+ * @return a new array that holds part of the contents of the builder.
+ * @throws IndexOutOfBoundsException if startIndex is invalid, or if endIndex is invalid (but endIndex greater than size is valid).
*/
public char[] toCharArray(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
@@ -3153,7 +3111,7 @@ public char[] toCharArray(final int startIndex, int endIndex) {
* Note that unlike StringBuffer, the string version returned is independent of the string builder.
*
*
- * @return The builder as a String
+ * @return The builder as a String.
*/
@Override
public String toString() {
@@ -3163,7 +3121,7 @@ public String toString() {
/**
* Gets a StringBuffer version of the string builder, creating a new instance each time the method is called.
*
- * @return The builder as a StringBuffer
+ * @return The builder as a StringBuffer.
*/
public StringBuffer toStringBuffer() {
return new StringBuffer(size).append(buffer, 0, size);
@@ -3172,7 +3130,7 @@ public StringBuffer toStringBuffer() {
/**
* Gets a StringBuilder version of the string builder, creating a new instance each time the method is called.
*
- * @return The builder as a StringBuilder
+ * @return The builder as a StringBuilder.
*/
public StringBuilder toStringBuilder() {
return new StringBuilder(size).append(buffer, 0, size);
@@ -3181,7 +3139,7 @@ public StringBuilder toStringBuilder() {
/**
* Trims the builder by removing characters less than or equal to a space from the beginning and end.
*
- * @return this, to enable chaining
+ * @return {@code this} instance.
*/
public TextStringBuilder trim() {
if (size == 0) {
@@ -3206,10 +3164,10 @@ public TextStringBuilder trim() {
}
/**
- * Validates that an index is in the range {@code 0 <= index <= size}.
+ * Validates that an index is in the range {@code 0 <= index < size}.
*
* @param index the index to test.
- * @throws IndexOutOfBoundsException Thrown when the index is not the range {@code 0 <= index <= size}.
+ * @throws IndexOutOfBoundsException Thrown when the index is not the range {@code 0 <= index < size}.
*/
protected void validateIndex(final int index) {
if (index < 0 || index >= size) {
@@ -3220,10 +3178,10 @@ protected void validateIndex(final int index) {
/**
* Validates parameters defining a range of the builder.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string
+ * @param startIndex the start index, inclusive, must be valid.
+ * @param endIndex the end index, exclusive, must be valid except that if too large it is treated as end of string.
* @return A valid end index.
- * @throws StringIndexOutOfBoundsException if the index is invalid
+ * @throws StringIndexOutOfBoundsException if the index is invalid.
*/
protected int validateRange(final int startIndex, int endIndex) {
if (startIndex < 0) {
diff --git a/src/main/java/org/apache/commons/text/WordUtils.java b/src/main/java/org/apache/commons/text/WordUtils.java
index ea84d548b7..720ca5f98c 100644
--- a/src/main/java/org/apache/commons/text/WordUtils.java
+++ b/src/main/java/org/apache/commons/text/WordUtils.java
@@ -24,6 +24,7 @@
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.Strings;
import org.apache.commons.lang3.Validate;
/**
@@ -73,8 +74,8 @@ public class WordUtils {
* WordUtils.abbreviate("Now is the time for all good men", 20, -1, "")); = "Now is the time for all"
* WordUtils.abbreviate("Now is the time for all good men", 50, -1, "")); = "Now is the time for all good men"
* WordUtils.abbreviate("Now is the time for all good men", 1000, -1, "")); = "Now is the time for all good men"
- * WordUtils.abbreviate("Now is the time for all good men", 9, -10, null)); = IllegalArgumentException
- * WordUtils.abbreviate("Now is the time for all good men", 10, 5, null)); = IllegalArgumentException
+ * WordUtils.abbreviate("Now is the time for all good men", 9, -10, null)); = Throws {@link IllegalArgumentException}
+ * WordUtils.abbreviate("Now is the time for all good men", 10, 5, null)); = Throws {@link IllegalArgumentException}
*
*/
public static String abbreviate(final String str, int lower, int upper, final String appendToEnd) {
@@ -97,7 +98,7 @@ public static String abbreviate(final String str, int lower, int upper, final St
}
final StringBuilder result = new StringBuilder();
- final int index = StringUtils.indexOf(str, " ", lower);
+ final int index = Strings.CS.indexOf(str, " ", lower);
if (index == -1) {
result.append(str, 0, upper);
// only if abbreviation has occurred do we append the appendToEnd value
@@ -129,8 +130,8 @@ public static String abbreviate(final String str, int lower, int upper, final St
* WordUtils.capitalize("i am FINE") = "I Am FINE"
*
*
- * @param str the String to capitalize, may be null
- * @return capitalized String, {@code null} if null String input
+ * @param str the String to capitalize, may be null.
+ * @return capitalized String, {@code null} if null String input.
* @see #uncapitalize(String)
* @see #capitalizeFully(String)
*/
@@ -161,9 +162,9 @@ public static String capitalize(final String str) {
* WordUtils.capitalize("i am fine", new char[]{}) = "I am fine"
*
*
- * @param str the String to capitalize, may be null
- * @param delimiters set of characters to determine capitalization, null means whitespace
- * @return capitalized String, {@code null} if null String input
+ * @param str the String to capitalize, may be null.
+ * @param delimiters set of characters to determine capitalization, null means whitespace.
+ * @return capitalized String, {@code null} if null String input.
* @see #uncapitalize(String)
* @see #capitalizeFully(String)
*/
@@ -213,8 +214,8 @@ public static String capitalize(final String str, final char... delimiters) {
* WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
*
*
- * @param str the String to capitalize, may be null
- * @return capitalized String, {@code null} if null String input
+ * @param str the String to capitalize, may be null.
+ * @return capitalized String, {@code null} if null String input.
*/
public static String capitalizeFully(final String str) {
return capitalizeFully(str, null);
@@ -241,9 +242,9 @@ public static String capitalizeFully(final String str) {
* WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
*
*
- * @param str the String to capitalize, may be null
- * @param delimiters set of characters to determine capitalization, null means whitespace
- * @return capitalized String, {@code null} if null String input
+ * @param str the String to capitalize, may be null.
+ * @param delimiters set of characters to determine capitalization, null means whitespace.
+ * @return capitalized String, {@code null} if null String input.
*/
public static String capitalizeFully(String str, final char... delimiters) {
if (StringUtils.isEmpty(str)) {
@@ -270,9 +271,9 @@ public static String capitalizeFully(String str, final char... delimiters) {
* WordUtils.containsAllWords("abc def", "def", "abc") = true
*
*
- * @param word The CharSequence to check, may be null
- * @param words The array of String words to search for, may be null
- * @return {@code true} if all search words are found, {@code false} otherwise
+ * @param word The CharSequence to check, may be null.
+ * @param words The array of String words to search for, may be null.
+ * @return {@code true} if all search words are found, {@code false} otherwise.
*/
public static boolean containsAllWords(final CharSequence word, final CharSequence... words) {
if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) {
@@ -295,7 +296,7 @@ public static boolean containsAllWords(final CharSequence word, final CharSequen
* The function provides O(1) lookup time.
* Whitespace is defined by {@link Character#isWhitespace(char)} and is used as the defaultvalue if delimiters is null.
*
- * @param delimiters set of characters to determine delimiters, null means whitespace
+ * @param delimiters set of characters to determine delimiters, null means whitespace.
* @return Predicate taking a code point value as an argument and returning true if a delimiter.
*/
private static Predicate generateIsDelimiterFunction(final char[] delimiters) {
@@ -329,8 +330,8 @@ private static Predicate generateIsDelimiterFunction(final char[] delim
* WordUtils.initials("Ben J.Lee") = "BJ"
*
*
- * @param str the String to get initials from, may be null
- * @return String of initial letters, {@code null} if null String input
+ * @param str the String to get initials from, may be null.
+ * @return String of initial letters, {@code null} if null String input.
* @see #initials(String,char[])
*/
public static String initials(final String str) {
@@ -357,9 +358,9 @@ public static String initials(final String str) {
* WordUtils.initials(*, new char[0]) = ""
*
*
- * @param str the String to get initials from, may be null
- * @param delimiters set of characters to determine words, null means whitespace
- * @return String of initial characters, {@code null} if null String input
+ * @param str the String to get initials from, may be null.
+ * @param delimiters set of characters to determine words, null means whitespace.
+ * @return String of initial characters, {@code null} if null String input.
* @see #initials(String)
*/
public static String initials(final String str, final char... delimiters) {
@@ -392,10 +393,10 @@ public static String initials(final String str, final char... delimiters) {
/**
* Is the character a delimiter.
*
- * @param ch the character to check
- * @param delimiters the delimiters
- * @return true if it is a delimiter
- * @deprecated as of 1.2 and will be removed in 2.0
+ * @param ch the character to check.
+ * @param delimiters the delimiters.
+ * @return true if it is a delimiter.
+ * @deprecated as of 1.2 and will be removed in 2.0.
*/
@Deprecated
public static boolean isDelimiter(final char ch, final char[] delimiters) {
@@ -413,10 +414,10 @@ public static boolean isDelimiter(final char ch, final char[] delimiters) {
/**
* Is the codePoint a delimiter.
*
- * @param codePoint the codePint to check
- * @param delimiters the delimiters
- * @return true if it is a delimiter
- * @deprecated as of 1.2 and will be removed in 2.0
+ * @param codePoint the codePint to check.
+ * @param delimiters the delimiters.
+ * @return true if it is a delimiter.
+ * @deprecated as of 1.2 and will be removed in 2.0.
*/
@Deprecated
public static boolean isDelimiter(final int codePoint, final char[] delimiters) {
@@ -451,8 +452,8 @@ public static boolean isDelimiter(final int codePoint, final char[] delimiters)
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
*
*
- * @param str the String to swap case, may be null
- * @return The changed String, {@code null} if null String input
+ * @param str the String to swap case, may be null.
+ * @return The changed String, {@code null} if null String input.
*/
public static String swapCase(final String str) {
if (StringUtils.isEmpty(str)) {
@@ -498,8 +499,8 @@ public static String swapCase(final String str) {
* WordUtils.uncapitalize("I Am FINE") = "i am fINE"
*
*
- * @param str the String to uncapitalize, may be null
- * @return uncapitalized String, {@code null} if null String input
+ * @param str the String to uncapitalize, may be null.
+ * @return uncapitalized String, {@code null} if null String input.
* @see #capitalize(String)
*/
public static String uncapitalize(final String str) {
@@ -526,9 +527,9 @@ public static String uncapitalize(final String str) {
* WordUtils.uncapitalize("I am fine", new char[]{}) = "i am fine"
*
*
- * @param str the String to uncapitalize, may be null
- * @param delimiters set of characters to determine uncapitalization, null means whitespace
- * @return uncapitalized String, {@code null} if null String input
+ * @param str the String to uncapitalize, may be null.
+ * @param delimiters set of characters to determine uncapitalization, null means whitespace.
+ * @return uncapitalized String, {@code null} if null String input.
* @see #capitalize(String)
*/
public static String uncapitalize(final String str, final char... delimiters) {
@@ -606,9 +607,9 @@ public static String uncapitalize(final String str, final char... delimiters) {
*
* (assuming that '\n' is the systems line separator)
*
- * @param str the String to be word wrapped, may be null
- * @param wrapLength the column to wrap the words at, less than 1 is treated as 1
- * @return a line with newlines inserted, {@code null} if null input
+ * @param str the String to be word wrapped, may be null.
+ * @param wrapLength the column to wrap the words at, less than 1 is treated as 1.
+ * @return a line with newlines inserted, {@code null} if null input.
*/
public static String wrap(final String str, final int wrapLength) {
return wrap(str, wrapLength, null, false);
@@ -682,12 +683,11 @@ public static String wrap(final String str, final int wrapLength) {
*
*
*
- * @param str the String to be word wrapped, may be null
- * @param wrapLength the column to wrap the words at, less than 1 is treated as 1
- * @param newLineStr the string to insert for a new line,
- * {@code null} uses the system property line separator
- * @param wrapLongWords true if long words (such as URLs) should be wrapped
- * @return a line with newlines inserted, {@code null} if null input
+ * @param str the String to be word wrapped, may be null.
+ * @param wrapLength the column to wrap the words at, less than 1 is treated as 1.
+ * @param newLineStr the string to insert for a new line, {@code null} uses the system property line separator.
+ * @param wrapLongWords true if long words (such as URLs) should be wrapped.
+ * @return a line with newlines inserted, {@code null} if null input.
*/
public static String wrap(final String str,
final int wrapLength,
@@ -779,14 +779,13 @@ public static String wrap(final String str,
*
"flammable\ninflammable"
*
*
- * @param str the String to be word wrapped, may be null
- * @param wrapLength the column to wrap the words at, less than 1 is treated as 1
- * @param newLineStr the string to insert for a new line,
- * {@code null} uses the system property line separator
- * @param wrapLongWords true if long words (such as URLs) should be wrapped
- * @param wrapOn regex expression to be used as a breakable characters,
- * if blank string is provided a space character will be used
- * @return a line with newlines inserted, {@code null} if null input
+ *
+ * @param str the String to be word wrapped, may be null.
+ * @param wrapLength the column to wrap the words at, less than 1 is treated as 1.
+ * @param newLineStr the string to insert for a new line, {@code null} uses the system property line separator.
+ * @param wrapLongWords true if long words (such as URLs) should be wrapped.
+ * @param wrapOn regex expression to be used as a breakable characters, if blank string is provided a space character will be used.
+ * @return a line with newlines inserted, {@code null} if null input.
*/
public static String wrap(final String str,
int wrapLength,
diff --git a/src/main/java/org/apache/commons/text/diff/CommandVisitor.java b/src/main/java/org/apache/commons/text/diff/CommandVisitor.java
index 187c9f4161..4dba623e09 100644
--- a/src/main/java/org/apache/commons/text/diff/CommandVisitor.java
+++ b/src/main/java/org/apache/commons/text/diff/CommandVisitor.java
@@ -17,8 +17,7 @@
package org.apache.commons.text.diff;
/**
- * This interface should be implemented by user object to walk
- * through {@link EditScript EditScript} objects.
+ * Walks through {@link EditScript EditScript} objects.
*
* Users should implement this interface in order to walk through
* the {@link EditScript EditScript} object created by the comparison
@@ -126,21 +125,21 @@ public interface CommandVisitor {
/**
* Method called when a delete command is encountered.
*
- * @param object object to delete (this object comes from the first sequence)
+ * @param object object to delete (this object comes from the first sequence).
*/
void visitDeleteCommand(T object);
/**
* Method called when an insert command is encountered.
*
- * @param object object to insert (this object comes from the second sequence)
+ * @param object object to insert (this object comes from the second sequence).
*/
void visitInsertCommand(T object);
/**
* Method called when a keep command is encountered.
*
- * @param object object to keep (this object comes from the first sequence)
+ * @param object object to keep (this object comes from the first sequence).
*/
void visitKeepCommand(T object);
diff --git a/src/main/java/org/apache/commons/text/diff/DeleteCommand.java b/src/main/java/org/apache/commons/text/diff/DeleteCommand.java
index 66c1bb035f..e0f14a0432 100644
--- a/src/main/java/org/apache/commons/text/diff/DeleteCommand.java
+++ b/src/main/java/org/apache/commons/text/diff/DeleteCommand.java
@@ -36,7 +36,7 @@ public class DeleteCommand extends EditCommand {
/**
* Constructs a new instance of {@link DeleteCommand}.
*
- * @param object the object of the first sequence that should be deleted
+ * @param object the object of the first sequence that should be deleted.
*/
public DeleteCommand(final T object) {
super(object);
@@ -46,7 +46,7 @@ public DeleteCommand(final T object) {
* Accepts a visitor. When a {@code DeleteCommand} accepts a visitor, it calls
* its {@link CommandVisitor#visitDeleteCommand visitDeleteCommand} method.
*
- * @param visitor the visitor to be accepted
+ * @param visitor the visitor to be accepted.
*/
@Override
public void accept(final CommandVisitor visitor) {
diff --git a/src/main/java/org/apache/commons/text/diff/EditCommand.java b/src/main/java/org/apache/commons/text/diff/EditCommand.java
index 2ba8d7fd68..30cb38c4c2 100644
--- a/src/main/java/org/apache/commons/text/diff/EditCommand.java
+++ b/src/main/java/org/apache/commons/text/diff/EditCommand.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.diff;
/**
- * Abstract base class for all commands used to transform an objects sequence
+ * Abstract class for all commands used to transform an objects sequence
* into another one.
*
* When two objects sequences are compared through the
@@ -58,8 +58,7 @@ public abstract class EditCommand {
/**
* Constructs a new instance of EditCommand.
*
- * @param object reference to the object associated with this command, this
- * refers to an element of one of the sequences being compared
+ * @param object reference to the object associated with this command, this refers to an element of one of the sequences being compared.
*/
protected EditCommand(final T object) {
this.object = object;
@@ -68,18 +67,17 @@ protected EditCommand(final T object) {
/**
* Accepts a visitor.
*
- * This method is invoked for each commands belonging to
- * an {@link EditScript EditScript}, in order to implement the visitor design pattern
+ * This method is invoked for each commands belonging to an {@link EditScript EditScript}, in order to implement the visitor design pattern
*
*
- * @param visitor the visitor to be accepted
+ * @param visitor the visitor to be accepted.
*/
public abstract void accept(CommandVisitor visitor);
/**
* Gets the object associated with this command.
*
- * @return The object on which the command is applied
+ * @return The object on which the command is applied.
*/
protected T getObject() {
return object;
diff --git a/src/main/java/org/apache/commons/text/diff/EditScript.java b/src/main/java/org/apache/commons/text/diff/EditScript.java
index 6b68424bf7..1170c89e54 100644
--- a/src/main/java/org/apache/commons/text/diff/EditScript.java
+++ b/src/main/java/org/apache/commons/text/diff/EditScript.java
@@ -20,7 +20,7 @@
import java.util.List;
/**
- * This class gathers all the {@link EditCommand commands} needed to transform
+ * Gathers all the {@link EditCommand commands} needed to transform
* one objects sequence into another objects sequence.
*
* An edit script is the most general view of the differences between two
@@ -67,7 +67,7 @@ public EditScript() {
/**
* Appends a delete command to the script.
*
- * @param command command to add
+ * @param command command to add.
*/
public void append(final DeleteCommand command) {
commands.add(command);
@@ -77,7 +77,7 @@ public void append(final DeleteCommand command) {
/**
* Appends an insert command to the script.
*
- * @param command command to add
+ * @param command command to add.
*/
public void append(final InsertCommand command) {
commands.add(command);
@@ -87,7 +87,7 @@ public void append(final InsertCommand command) {
/**
* Appends a keep command to the script.
*
- * @param command command to add
+ * @param command command to add.
*/
public void append(final KeepCommand command) {
commands.add(command);
@@ -99,7 +99,7 @@ public void append(final KeepCommand command) {
* longest common subsequence is the number of {@link KeepCommand keep
* commands} in the script.
*
- * @return length of the Longest Common Subsequence
+ * @return length of the Longest Common Subsequence.
*/
public int getLCSLength() {
return lcsLength;
@@ -110,7 +110,7 @@ public int getLCSLength() {
* modification is the number of {@link DeleteCommand delete} and
* {@link InsertCommand insert} commands in the script.
*
- * @return number of effective modifications
+ * @return number of effective modifications.
*/
public int getModifications() {
return modifications;
@@ -123,7 +123,7 @@ public int getModifications() {
* commands in order and call the appropriate method as each command is
* encountered.
*
- * @param visitor the visitor that will visit all commands in turn
+ * @param visitor the visitor that will visit all commands in turn.
*/
public void visit(final CommandVisitor visitor) {
commands.forEach(command -> command.accept(visitor));
diff --git a/src/main/java/org/apache/commons/text/diff/InsertCommand.java b/src/main/java/org/apache/commons/text/diff/InsertCommand.java
index dad4b75ef7..d7545d6ebc 100644
--- a/src/main/java/org/apache/commons/text/diff/InsertCommand.java
+++ b/src/main/java/org/apache/commons/text/diff/InsertCommand.java
@@ -36,7 +36,7 @@ public class InsertCommand extends EditCommand {
/**
* Constructs a new instance of InsertCommand.
*
- * @param object the object of the second sequence that should be inserted
+ * @param object the object of the second sequence that should be inserted.
*/
public InsertCommand(final T object) {
super(object);
@@ -47,7 +47,7 @@ public InsertCommand(final T object) {
* it calls its {@link CommandVisitor#visitInsertCommand visitInsertCommand}
* method.
*
- * @param visitor the visitor to be accepted
+ * @param visitor the visitor to be accepted.
*/
@Override
public void accept(final CommandVisitor visitor) {
diff --git a/src/main/java/org/apache/commons/text/diff/KeepCommand.java b/src/main/java/org/apache/commons/text/diff/KeepCommand.java
index 63f3546da2..cb5d1b2a34 100644
--- a/src/main/java/org/apache/commons/text/diff/KeepCommand.java
+++ b/src/main/java/org/apache/commons/text/diff/KeepCommand.java
@@ -36,19 +36,17 @@ public class KeepCommand extends EditCommand {
/**
* Constructs a new instance of KeepCommand.
*
- * @param object the object belonging to both sequences (the object is a
- * reference to the instance in the first sequence which is known
- * to be equal to an instance in the second sequence)
+ * @param object the object belonging to both sequences (the object is a reference to the instance in the first sequence which is known to be equal to an
+ * instance in the second sequence)
*/
public KeepCommand(final T object) {
super(object);
}
/**
- * Accepts a visitor. When a {@code KeepCommand} accepts a visitor, it
- * calls its {@link CommandVisitor#visitKeepCommand visitKeepCommand} method.
+ * Accepts a visitor. When a {@code KeepCommand} accepts a visitor, it calls its {@link CommandVisitor#visitKeepCommand visitKeepCommand} method.
*
- * @param visitor the visitor to be accepted
+ * @param visitor the visitor to be accepted.
*/
@Override
public void accept(final CommandVisitor visitor) {
diff --git a/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java b/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
index 15f2ed5ff5..9931e05057 100644
--- a/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
+++ b/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
@@ -20,7 +20,7 @@
import java.util.List;
/**
- * This class handles sequences of replacements resulting from a comparison.
+ * Handles sequences of replacements resulting from a comparison.
*
* The comparison of two objects sequences leads to the identification of common
* parts and parts which only belong to the first or to the second sequence. The
@@ -72,19 +72,19 @@ public class ReplacementsFinder implements CommandVisitor {
/**
* Constructs a new instance of {@link ReplacementsFinder}.
*
- * @param handler handler to call when synchronized sequences are found
+ * @param handler handler to call when synchronized sequences are found
*/
public ReplacementsFinder(final ReplacementsHandler handler) {
pendingInsertions = new ArrayList<>();
- pendingDeletions = new ArrayList<>();
- skipped = 0;
- this.handler = handler;
+ pendingDeletions = new ArrayList<>();
+ skipped = 0;
+ this.handler = handler;
}
/**
* Add an object to the pending deletions set.
*
- * @param object object to delete
+ * @param object object to delete.
*/
@Override
public void visitDeleteCommand(final T object) {
@@ -94,7 +94,7 @@ public void visitDeleteCommand(final T object) {
/**
* Add an object to the pending insertions set.
*
- * @param object object to insert
+ * @param object object to insert.
*/
@Override
public void visitInsertCommand(final T object) {
@@ -104,11 +104,10 @@ public void visitInsertCommand(final T object) {
/**
* Handle a synchronization object.
*
- * When a synchronization object is identified, the pending insertions and
- * pending deletions sets are provided to the user handler as subsequences.
+ * When a synchronization object is identified, the pending insertions and pending deletions sets are provided to the user handler as subsequences.
*
*
- * @param object synchronization object detected
+ * @param object synchronization object detected.
*/
@Override
public void visitKeepCommand(final T object) {
diff --git a/src/main/java/org/apache/commons/text/diff/ReplacementsHandler.java b/src/main/java/org/apache/commons/text/diff/ReplacementsHandler.java
index 3f8040ad2a..6bfa5f5d7d 100644
--- a/src/main/java/org/apache/commons/text/diff/ReplacementsHandler.java
+++ b/src/main/java/org/apache/commons/text/diff/ReplacementsHandler.java
@@ -14,12 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.commons.text.diff;
import java.util.List;
/**
- * This interface is devoted to handle synchronized replacement sequences.
+ * Handles synchronized replacement sequences.
*
* @param object type
* @see ReplacementsFinder
@@ -30,25 +31,18 @@ public interface ReplacementsHandler {
/**
* Handle two synchronized sequences.
*
- * This method is called by a {@link ReplacementsFinder ReplacementsFinder}
- * instance when it has synchronized two sub-sequences of object arrays
- * being compared, and at least one of the sequences is non-empty. Since the
- * sequences are synchronized, the objects before the two sub-sequences are
- * equals (if they exist). This property also holds for the objects after
- * the two sub-sequences.
+ * This method is called by a {@link ReplacementsFinder ReplacementsFinder} instance when it has synchronized two sub-sequences of object arrays being
+ * compared, and at least one of the sequences is non-empty. Since the sequences are synchronized, the objects before the two sub-sequences are equals (if
+ * they exist). This property also holds for the objects after the two sub-sequences.
*
*
- * The replacement is defined as replacing the {@code from}
- * sub-sequence into the {@code to} sub-sequence.
+ * The replacement is defined as replacing the {@code from} sub-sequence into the {@code to} sub-sequence.
*
*
- * @param skipped number of tokens skipped since the last call (i.e. number of
- * tokens that were in both sequences), this number should be strictly positive
- * except on the very first call where it can be zero (if the first object of
- * the two sequences are different)
- * @param from sub-sequence of objects coming from the first sequence
- * @param to sub-sequence of objects coming from the second sequence
+ * @param skipped number of tokens skipped since the last call (i.e. number of tokens that were in both sequences), this number should be strictly positive
+ * except on the very first call where it can be zero (if the first object of the two sequences are different).
+ * @param from sub-sequence of objects coming from the first sequence.
+ * @param to sub-sequence of objects coming from the second sequence.
*/
void handleReplacement(int skipped, List from, List to);
-
}
diff --git a/src/main/java/org/apache/commons/text/diff/StringsComparator.java b/src/main/java/org/apache/commons/text/diff/StringsComparator.java
index 99ce43aaa6..2f530650ac 100644
--- a/src/main/java/org/apache/commons/text/diff/StringsComparator.java
+++ b/src/main/java/org/apache/commons/text/diff/StringsComparator.java
@@ -35,7 +35,7 @@
*
* This class implements the comparison algorithm, which is the very efficient
* algorithm from Eugene W. Myers
- *
+ *
* An O(ND) Difference Algorithm and Its Variations. This algorithm produces
* the shortest possible {@link EditScript edit script} containing all the
* {@link EditCommand commands} needed to transform the first sequence into
@@ -53,8 +53,7 @@
public class StringsComparator {
/**
- * This class is a simple placeholder to hold the end part of a path
- * under construction in a {@link StringsComparator StringsComparator}.
+ * Holds the end part of a path under construction in a {@link StringsComparator StringsComparator}.
*/
private static final class Snake {
@@ -70,9 +69,9 @@ private static final class Snake {
/**
* Constructs a new instance of Snake with specified indices.
*
- * @param start start index of the snake
- * @param end end index of the snake
- * @param diag diagonal number
+ * @param start start index of the snake.
+ * @param end end index of the snake.
+ * @param diag diagonal number.
*/
Snake(final int start, final int end, final int diag) {
this.start = start;
@@ -83,7 +82,7 @@ private static final class Snake {
/**
* Gets the diagonal number of the snake.
*
- * @return diagonal number of the snake
+ * @return diagonal number of the snake.
*/
public int getDiag() {
return diag;
@@ -92,7 +91,7 @@ public int getDiag() {
/**
* Gets the end index of the snake.
*
- * @return end index of the snake
+ * @return end index of the snake.
*/
public int getEnd() {
return end;
@@ -101,20 +100,23 @@ public int getEnd() {
/**
* Gets the start index of the snake.
*
- * @return start index of the snake
+ * @return start index of the snake.
*/
public int getStart() {
return start;
}
}
+
/**
* First character sequence.
*/
private final String left;
+
/**
* Second character sequence.
*/
private final String right;
+
/**
* Temporary array.
*/
@@ -128,15 +130,13 @@ public int getStart() {
/**
* Constructs a new instance of StringsComparator.
*
- * It is guaranteed that the comparisons will always be done as
- * {@code o1.equals(o2)} where {@code o1} belongs to the first
- * sequence and {@code o2} belongs to the second sequence. This can be
- * important if subclassing is used for some elements in the first sequence
- * and the {@code equals} method is specialized.
+ * It is guaranteed that the comparisons will always be done as {@code o1.equals(o2)} where {@code o1} belongs to the first sequence and {@code o2}
+ * belongs to the second sequence. This can be important if subclassing is used for some elements in the first sequence and the {@code equals} method is
+ * specialized.
*
*
- * @param left first character sequence to be compared
- * @param right second character sequence to be compared
+ * @param left first character sequence to be compared.
+ * @param right second character sequence to be compared.
*/
public StringsComparator(final String left, final String right) {
this.left = left;
@@ -150,11 +150,11 @@ public StringsComparator(final String left, final String right) {
/**
* Builds an edit script.
*
- * @param start1 the begin of the first sequence to be compared
- * @param end1 the end of the first sequence to be compared
- * @param start2 the begin of the second sequence to be compared
- * @param end2 the end of the second sequence to be compared
- * @param script the edited script
+ * @param start1 the begin of the first sequence to be compared.
+ * @param end1 the end of the first sequence to be compared.
+ * @param start2 the begin of the second sequence to be compared.
+ * @param end2 the end of the second sequence to be compared.
+ * @param script the edited script.
*/
private void buildScript(final int start1, final int end1, final int start2, final int end2,
final EditScript script) {
@@ -197,11 +197,11 @@ private void buildScript(final int start1, final int end1, final int start2, fin
/**
* Builds a snake.
*
- * @param start the value of the start of the snake
- * @param diag the value of the diagonal of the snake
- * @param end1 the value of the end of the first sequence to be compared
- * @param end2 the value of the end of the second sequence to be compared
- * @return The snake built
+ * @param start the value of the start of the snake.
+ * @param diag the value of the diagonal of the snake.
+ * @param end1 the value of the end of the first sequence to be compared.
+ * @param end2 the value of the end of the second sequence to be compared.
+ * @return The snake built.
*/
private Snake buildSnake(final int start, final int diag, final int end1, final int end2) {
int end = start;
@@ -214,21 +214,17 @@ private Snake buildSnake(final int start, final int diag, final int end1, final
}
/**
- * Gets the middle snake corresponding to two subsequences of the
- * main sequences.
+ * Gets the middle snake corresponding to two subsequences of the main sequences.
*
- * The snake is found using the MYERS Algorithm (this algorithms has
- * also been implemented in the GNU diff program). This algorithm is
- * explained in Eugene Myers article:
- *
- * An O(ND) Difference Algorithm and Its Variations.
+ * The snake is found using the MYERS Algorithm (this algorithms has also been implemented in the GNU diff program). This algorithm is explained in Eugene
+ * Myers article: An O(ND) Difference Algorithm and Its Variations.
*
*
- * @param start1 the begin of the first sequence to be compared
- * @param end1 the end of the first sequence to be compared
- * @param start2 the begin of the second sequence to be compared
- * @param end2 the end of the second sequence to be compared
- * @return The middle snake
+ * @param start1 the begin of the first sequence to be compared.
+ * @param end1 the end of the first sequence to be compared.
+ * @param start2 the begin of the second sequence to be compared.
+ * @param end2 the end of the second sequence to be compared.
+ * @return The middle snake.
*/
private Snake getMiddleSnake(final int start1, final int end1, final int start2, final int end2) {
// Myers Algorithm
@@ -302,16 +298,12 @@ private Snake getMiddleSnake(final int start1, final int end1, final int start2,
/**
* Gets the {@link EditScript} object.
*
- * It is guaranteed that the objects embedded in the {@link InsertCommand
- * insert commands} come from the second sequence and that the objects
- * embedded in either the {@link DeleteCommand delete commands} or
- * {@link KeepCommand keep commands} come from the first sequence. This can
- * be important if subclassing is used for some elements in the first
- * sequence and the {@code equals} method is specialized.
+ * It is guaranteed that the objects embedded in the {@link InsertCommand insert commands} come from the second sequence and that the objects embedded in
+ * either the {@link DeleteCommand delete commands} or {@link KeepCommand keep commands} come from the first sequence. This can be important if subclassing
+ * is used for some elements in the first sequence and the {@code equals} method is specialized.
*
*
- * @return The edit script resulting from the comparison of the two
- * sequences
+ * @return The edit script resulting from the comparison of the two sequences.
*/
public EditScript getScript() {
final EditScript script = new EditScript<>();
diff --git a/src/main/java/org/apache/commons/text/doc-files/leaf.svg b/src/main/java/org/apache/commons/text/doc-files/leaf.svg
new file mode 100644
index 0000000000..71de588c64
--- /dev/null
+++ b/src/main/java/org/apache/commons/text/doc-files/leaf.svg
@@ -0,0 +1,45 @@
+
+
+
\ No newline at end of file
diff --git a/src/main/java/org/apache/commons/text/doc-files/logo.png b/src/main/java/org/apache/commons/text/doc-files/logo.png
new file mode 100644
index 0000000000..0c32a3e474
Binary files /dev/null and b/src/main/java/org/apache/commons/text/doc-files/logo.png differ
diff --git a/src/main/java/org/apache/commons/text/io/StringSubstitutorReader.java b/src/main/java/org/apache/commons/text/io/StringSubstitutorReader.java
index 57088f0eeb..99f648fedf 100644
--- a/src/main/java/org/apache/commons/text/io/StringSubstitutorReader.java
+++ b/src/main/java/org/apache/commons/text/io/StringSubstitutorReader.java
@@ -145,7 +145,7 @@ private boolean isDraining() {
* Reads a single character.
*
* @return a character as an {@code int} or {@code -1} for end-of-stream.
- * @throws IOException If an I/O error occurs
+ * @throws IOException If an I/O error occurs.
*/
@Override
public int read() throws IOException {
@@ -168,7 +168,7 @@ public int read() throws IOException {
* @param targetIndexIn Index in the target at which to start storing characters.
* @param targetLengthIn Maximum number of characters to read.
* @return The number of characters read, or -1 on end of stream.
- * @throws IOException If an I/O error occurs
+ * @throws IOException If an I/O error occurs.
*/
@Override
public int read(final char[] target, final int targetIndexIn, final int targetLengthIn) throws IOException {
diff --git a/src/main/java/org/apache/commons/text/lookup/AbstractPathFencedLookup.java b/src/main/java/org/apache/commons/text/lookup/AbstractPathFencedLookup.java
index 2a980ab2d8..b4fc4601b8 100644
--- a/src/main/java/org/apache/commons/text/lookup/AbstractPathFencedLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/AbstractPathFencedLookup.java
@@ -14,53 +14,38 @@
* See the license for the specific language governing permissions and
* limitations under the license.
*/
+
package org.apache.commons.text.lookup;
import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
/**
- * Abstracts guarding Path lookups with fences.
+ * Abstracts string lookup that guards Path lookups with a fence.
*/
abstract class AbstractPathFencedLookup extends AbstractStringLookup {
/**
- * Fences guarding Path resolution.
+ * A fence is made of Paths guarding Path resolution.
*/
- protected final List fences;
+ protected final PathFence fence;
/**
* Constructs a new instance.
*
- * @param fences The fences guarding Path resolution.
+ * @param paths The fences guarding Path resolution.
*/
- AbstractPathFencedLookup(final Path... fences) {
- this.fences = fences != null ? Arrays.stream(fences).map(Path::toAbsolutePath).collect(Collectors.toList()) : Collections.emptyList();
+ AbstractPathFencedLookup(final Path... paths) {
+ this.fence = PathFence.builder().setRoots(paths).get();
}
/**
- * Gets a Path for the given file name checking that it resolves within our fences.
+ * Gets a Path for the given file name checking that it resolves within our fence.
*
* @param fileName the file name to resolve.
* @return a fenced Path.
- * @throws IllegalArgumentException if the file name is not without our fences.
+ * @throws IllegalArgumentException if the file name is not without our fence.
*/
protected Path getPath(final String fileName) {
- final Path path = Paths.get(fileName);
- if (fences.isEmpty()) {
- return path;
- }
- final Path pathAbs = path.normalize().toAbsolutePath();
- final Optional first = fences.stream().filter(pathAbs::startsWith).findFirst();
- if (first.isPresent()) {
- return path;
- }
- throw IllegalArgumentExceptions.format("[%s] -> [%s] not in %s", fileName, pathAbs, fences);
+ return fence.apply(fileName);
}
-
}
diff --git a/src/main/java/org/apache/commons/text/lookup/BiFunctionStringLookup.java b/src/main/java/org/apache/commons/text/lookup/BiFunctionStringLookup.java
index 9e1891a5a9..336d429372 100644
--- a/src/main/java/org/apache/commons/text/lookup/BiFunctionStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/BiFunctionStringLookup.java
@@ -22,9 +22,13 @@
/**
* A function-based lookup where the request for a lookup is answered by applying that function with a key.
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
* @param A function's return type
* @param
A function's second input type
+ * @see StringLookupFactory
* @since 1.9
*/
final class BiFunctionStringLookup
* This class was adapted from Apache Commons Configuration.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @since 1.5
*/
class ConstantStringLookup extends AbstractStringLookup {
@@ -87,9 +91,9 @@ static void clear() {
*
* ClassUtils.
*
- * @param className the name of the class to be loaded
- * @return The corresponding class object
- * @throws ClassNotFoundException if the class cannot be loaded
+ * @param className the name of the class to be loaded.
+ * @return The corresponding class object.
+ * @throws ClassNotFoundException if the class cannot be loaded.
*/
protected Class> fetchClass(final String className) throws ClassNotFoundException {
return ClassUtils.getClass(className);
@@ -101,8 +105,8 @@ protected Class> fetchClass(final String className) throws ClassNotFoundExcept
* cache. Otherwise this method will invoke the {@code resolveField()} method and pass in the name of the class and
* the field.
*
- * @param key the name of the variable to be resolved
- * @return The value of this variable or null if it cannot be resolved
+ * @param key the name of the variable to be resolved.
+ * @return The value of this variable or null if it cannot be resolved.
*/
@Override
public synchronized String lookup(final String key) {
@@ -137,10 +141,10 @@ public synchronized String lookup(final String key) {
* {@code fetchClass()} to obtain the {@link Class} object for the target class. Then it will use
* reflection to obtain the field's value. For this to work the field must be accessible.
*
- * @param className the name of the class
- * @param fieldName the name of the member field of that class to read
- * @return The field's value
- * @throws ReflectiveOperationException if an error occurs
+ * @param className the name of the class.
+ * @param fieldName the name of the member field of that class to read.
+ * @return The field's value.
+ * @throws ReflectiveOperationException if an error occurs.
*/
protected Object resolveField(final String className, final String fieldName) throws ReflectiveOperationException {
final Class> clazz = fetchClass(className);
diff --git a/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java b/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java
index c684db35d4..a7dc0b7123 100644
--- a/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java
@@ -43,6 +43,11 @@
*
* The above examples convert {@code "yyyy-MM-dd"} to today's date, for example, {@code "2019-08-04"}.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
+ *
+ * @see StringLookupFactory
*/
final class DateStringLookup extends AbstractStringLookup {
@@ -61,9 +66,9 @@ private DateStringLookup() {
/**
* Formats the given {@code date} long with the given {@code format}.
*
- * @param dateMillis the date to format
+ * @param dateMillis the date to format.
* @param format the format string for {@link SimpleDateFormat}.
- * @return The formatted date
+ * @return The formatted date.
*/
private String formatDate(final long dateMillis, final String format) {
FastDateFormat dateFormat = null;
diff --git a/src/main/java/org/apache/commons/text/lookup/DnsStringLookup.java b/src/main/java/org/apache/commons/text/lookup/DnsStringLookup.java
index 0506b26997..5d76eb93d0 100644
--- a/src/main/java/org/apache/commons/text/lookup/DnsStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/DnsStringLookup.java
@@ -53,7 +53,11 @@
*
* The above examples convert {@code "address|apache.org"} to {@code "95.216.24.32} (or {@code "40.79.78.1"}).
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
* The above example converts {@code "UTF-8:SomePath"} to the UTF-8 contents of the file at {@code SomePath}.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @since 1.5
*/
final class FileStringLookup extends AbstractPathFencedLookup {
diff --git a/src/main/java/org/apache/commons/text/lookup/FunctionStringLookup.java b/src/main/java/org/apache/commons/text/lookup/FunctionStringLookup.java
index 4a7123ea9b..07df1489ea 100644
--- a/src/main/java/org/apache/commons/text/lookup/FunctionStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/FunctionStringLookup.java
@@ -22,8 +22,12 @@
/**
* A function-based lookup where the request for a lookup is answered by applying that function with a key.
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
* @param A function's input type
+ * @see StringLookupFactory
* @since 1.9
*/
final class FunctionStringLookup extends AbstractStringLookup {
diff --git a/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java b/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java
index 3eac7d4a2d..e52d5360b5 100644
--- a/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java
+++ b/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java
@@ -28,9 +28,9 @@ final class IllegalArgumentExceptions {
* Creates an {@link IllegalArgumentException} with a message
* formatted with {@link String#format(String,Object...)}.
*
- * @param format See {@link String#format(String,Object...)}
- * @param args See {@link String#format(String,Object...)}
- * @return an {@link IllegalArgumentException} with a message formatted with {@link String#format(String,Object...)}
+ * @param format See {@link String#format(String,Object...)}.
+ * @param args See {@link String#format(String,Object...)}.
+ * @return an {@link IllegalArgumentException} with a message formatted with {@link String#format(String,Object...)}.
*/
static IllegalArgumentException format(final String format, final Object... args) {
return new IllegalArgumentException(String.format(format, args));
@@ -40,10 +40,10 @@ static IllegalArgumentException format(final String format, final Object... args
* Creates an {@link IllegalArgumentException} with a message
* formatted with {@link String#format(String,Object...)}.
*
- * @param t the throwable cause
- * @param format See {@link String#format(String,Object...)}
- * @param args See {@link String#format(String,Object...)}
- * @return an {@link IllegalArgumentException} with a message formatted with {@link String#format(String,Object...)}
+ * @param t the throwable cause.
+ * @param format See {@link String#format(String,Object...)}.
+ * @param args See {@link String#format(String,Object...)}.
+ * @return an {@link IllegalArgumentException} with a message formatted with {@link String#format(String,Object...)}.
*/
static IllegalArgumentException format(final Throwable t, final String format, final Object... args) {
return new IllegalArgumentException(String.format(format, args), t);
diff --git a/src/main/java/org/apache/commons/text/lookup/InetAddressKeys.java b/src/main/java/org/apache/commons/text/lookup/InetAddressKeys.java
index a188d4fd58..e7eee0136b 100644
--- a/src/main/java/org/apache/commons/text/lookup/InetAddressKeys.java
+++ b/src/main/java/org/apache/commons/text/lookup/InetAddressKeys.java
@@ -21,7 +21,11 @@
/**
* Constants for referring to {@link InetAddress} APIs.
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @since 1.8
*/
final class InetAddressKeys {
diff --git a/src/main/java/org/apache/commons/text/lookup/InetAddressStringLookup.java b/src/main/java/org/apache/commons/text/lookup/InetAddressStringLookup.java
index 346634cdcb..5a9a72a359 100644
--- a/src/main/java/org/apache/commons/text/lookup/InetAddressStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/InetAddressStringLookup.java
@@ -35,7 +35,11 @@
*
canonical-name: for the local canonical host name, for example {@code EXAMPLE.apache.org}.
*
address: for the local host address, for example {@code 192.168.56.1}.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @since 1.3
*/
final class InetAddressStringLookup extends AbstractStringLookup {
@@ -51,7 +55,7 @@ final class InetAddressStringLookup extends AbstractStringLookup {
static final InetAddressStringLookup LOOPACK_ADDRESS = new InetAddressStringLookup(InetAddress::getLoopbackAddress);
/**
- * Supplies the InetAddress.
+ * Supplies the {@link InetAddress}.
*/
private final FailableSupplier inetAddressSupplier;
diff --git a/src/main/java/org/apache/commons/text/lookup/InterpolatorStringLookup.java b/src/main/java/org/apache/commons/text/lookup/InterpolatorStringLookup.java
index c864698043..9027c5d5f4 100644
--- a/src/main/java/org/apache/commons/text/lookup/InterpolatorStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/InterpolatorStringLookup.java
@@ -26,6 +26,11 @@
*
* Uses the {@link StringLookupFactory default lookups}.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
+ *
+ * @see StringLookupFactory
*/
final class InterpolatorStringLookup extends AbstractStringLookup {
@@ -108,8 +113,8 @@ public Map getStringLookupMap() {
* the prefix stripped to the lookup object registered for this prefix. If no prefix can be found or if the
* associated lookup object cannot resolve this variable, the default lookup object will be used.
*
- * @param key the name of the variable whose value is to be looked up
- * @return The value of this variable or null if it cannot be resolved
+ * @param key the name of the variable whose value is to be looked up.
+ * @return The value of this variable or null if it cannot be resolved.
*/
@Override
public String lookup(String key) {
diff --git a/src/main/java/org/apache/commons/text/lookup/JavaPlatformStringLookup.java b/src/main/java/org/apache/commons/text/lookup/JavaPlatformStringLookup.java
index dea176ef39..2b280b9819 100644
--- a/src/main/java/org/apache/commons/text/lookup/JavaPlatformStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/JavaPlatformStringLookup.java
@@ -53,7 +53,11 @@
* The above examples convert {@code "version"} to the current VM version, for example,
* {@code "Java version 1.8.0_181"}.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @since 1.3
*/
final class JavaPlatformStringLookup extends AbstractStringLookup {
@@ -62,14 +66,19 @@ final class JavaPlatformStringLookup extends AbstractStringLookup {
* Defines the singleton for this class.
*/
static final JavaPlatformStringLookup INSTANCE = new JavaPlatformStringLookup();
+
/** {@code hardware} key for driving {@link JavaPlatformStringLookup#lookup(String)}. */
private static final String KEY_HARDWARE = "hardware";
+
/** {@code locale} key for driving {@link JavaPlatformStringLookup#lookup(String)}. */
private static final String KEY_LOCALE = "locale";
+
/** {@code os} key for driving {@link JavaPlatformStringLookup#lookup(String)}. */
private static final String KEY_OS = "os";
+
/** {@code runtime} key for driving {@link JavaPlatformStringLookup#lookup(String)}. */
private static final String KEY_RUNTIME = "runtime";
+
/** {@code version} key for driving {@link JavaPlatformStringLookup#lookup(String)}. */
private static final String KEY_VERSION = "version";
@@ -83,12 +92,12 @@ final class JavaPlatformStringLookup extends AbstractStringLookup {
*/
public static void main(final String[] args) {
System.out.println(JavaPlatformStringLookup.class);
- System.out.printf("%s = %s%n", KEY_VERSION, JavaPlatformStringLookup.INSTANCE.lookup(KEY_VERSION));
- System.out.printf("%s = %s%n", KEY_RUNTIME, JavaPlatformStringLookup.INSTANCE.lookup(KEY_RUNTIME));
- System.out.printf("%s = %s%n", KEY_VM, JavaPlatformStringLookup.INSTANCE.lookup(KEY_VM));
- System.out.printf("%s = %s%n", KEY_OS, JavaPlatformStringLookup.INSTANCE.lookup(KEY_OS));
- System.out.printf("%s = %s%n", KEY_HARDWARE, JavaPlatformStringLookup.INSTANCE.lookup(KEY_HARDWARE));
- System.out.printf("%s = %s%n", KEY_LOCALE, JavaPlatformStringLookup.INSTANCE.lookup(KEY_LOCALE));
+ System.out.printf("%s = %s%n", KEY_VERSION, INSTANCE.lookup(KEY_VERSION));
+ System.out.printf("%s = %s%n", KEY_RUNTIME, INSTANCE.lookup(KEY_RUNTIME));
+ System.out.printf("%s = %s%n", KEY_VM, INSTANCE.lookup(KEY_VM));
+ System.out.printf("%s = %s%n", KEY_OS, INSTANCE.lookup(KEY_OS));
+ System.out.printf("%s = %s%n", KEY_HARDWARE, INSTANCE.lookup(KEY_HARDWARE));
+ System.out.printf("%s = %s%n", KEY_LOCALE, INSTANCE.lookup(KEY_LOCALE));
}
/**
@@ -152,7 +161,7 @@ private String getSystemProperty(final String name) {
/**
* Gets the given system property.
*
- * @param prefix the prefix to use for the result string
+ * @param prefix the prefix to use for the result string.
* @param name a system property name.
* @return The prefix + a system property value.
*/
@@ -188,7 +197,7 @@ String getVirtualMachine() {
*
*
*
- * @param key the key to be looked up, may be null
+ * @param key the key to be looked up, may be null.
* @return The value of the environment variable.
*/
@Override
diff --git a/src/main/java/org/apache/commons/text/lookup/PathFence.java b/src/main/java/org/apache/commons/text/lookup/PathFence.java
new file mode 100644
index 0000000000..95b9b615f5
--- /dev/null
+++ b/src/main/java/org/apache/commons/text/lookup/PathFence.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+/**
+ * A Path fence guards against using paths outside of a "fence" of made of root paths.
+ *
+ * Keep package-private.
+ */
+final class PathFence {
+
+ /**
+ * Builds {@link PathFence} instances.
+ */
+ static final class Builder implements Supplier {
+
+ /** The empty Path array. */
+ private static final Path[] EMPTY = {};
+
+ /**
+ * A fence is made of root Paths.
+ */
+ private Path[] roots = EMPTY;
+
+ @Override
+ public PathFence get() {
+ return new PathFence(this);
+ }
+
+ /**
+ * Sets the paths that delineate this fence.
+ *
+ * @param paths the paths that delineate this fence.
+ * @return {@code this} instance.
+ */
+ Builder setRoots(final Path... paths) {
+ this.roots = paths != null ? paths.clone() : EMPTY;
+ return this;
+ }
+ }
+
+ /**
+ * Creates a new builder.
+ *
+ * @return a new builder.
+ */
+ static Builder builder() {
+ return new Builder();
+ }
+
+ /**
+ * A fence is made of Paths guarding Path resolution.
+ */
+ private final List roots;
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param builder A builder.
+ */
+ private PathFence(final Builder builder) {
+ this.roots = Arrays.stream(builder.roots).map(Path::toAbsolutePath).collect(Collectors.toList());
+ }
+
+ /**
+ * Gets a Path for the given file name checking that it resolves within our fence.
+ *
+ * @param fileName the file name to resolve.
+ * @return a fenced Path.
+ * @throws IllegalArgumentException if the file name is not without our fence.
+ */
+ Path apply(final String fileName) {
+ final Path path = Paths.get(fileName);
+ if (roots.isEmpty()) {
+ return path;
+ }
+ final Path pathAbs = path.normalize().toAbsolutePath();
+ final Optional first = roots.stream().filter(pathAbs::startsWith).findFirst();
+ if (first.isPresent()) {
+ return path;
+ }
+ throw new IllegalArgumentException(String.format("[%s] -> [%s] not in the fence %s", fileName, pathAbs, roots));
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/text/lookup/PropertiesStringLookup.java b/src/main/java/org/apache/commons/text/lookup/PropertiesStringLookup.java
index 7420c407a0..b5aa177116 100644
--- a/src/main/java/org/apache/commons/text/lookup/PropertiesStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/PropertiesStringLookup.java
@@ -35,7 +35,11 @@
*
* For example: "com/domain/document.properties:key".
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @see Properties
* @since 1.5
*/
@@ -53,7 +57,7 @@ final class PropertiesStringLookup extends AbstractPathFencedLookup {
* Creates a lookup key for a given file and key.
*/
static String toPropertyKey(final String file, final String key) {
- return AbstractStringLookup.toLookupKey(file, SEPARATOR, key);
+ return toLookupKey(file, SEPARATOR, key);
}
/**
@@ -74,7 +78,7 @@ static String toPropertyKey(final String file, final String key) {
* Note the use of "::" instead of ":" to allow for "C:" drive letters in paths.
*
*
- * @param key the key to be looked up, may be null
+ * @param key the key to be looked up, may be null.
* @return The value associated with the key.
*/
@Override
diff --git a/src/main/java/org/apache/commons/text/lookup/ResourceBundleStringLookup.java b/src/main/java/org/apache/commons/text/lookup/ResourceBundleStringLookup.java
index e92d131aa2..6ffcc5b4a9 100644
--- a/src/main/java/org/apache/commons/text/lookup/ResourceBundleStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/ResourceBundleStringLookup.java
@@ -28,7 +28,11 @@
*
* For example: "com.domain.messages:MyKey".
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @see ResourceBundle
* @since 1.3
*/
@@ -75,7 +79,7 @@ String getString(final String keyBundleName, final String bundleKey) {
*
* For example: "com.domain.messages:MyKey".
*
- * @param key the key to be looked up, may be null
+ * @param key the key to be looked up, may be null.
* @return The value associated with the key.
* @see ResourceBundle
* @see ResourceBundle#getBundle(String)
diff --git a/src/main/java/org/apache/commons/text/lookup/ScriptStringLookup.java b/src/main/java/org/apache/commons/text/lookup/ScriptStringLookup.java
index 697214508f..2ed725b456 100644
--- a/src/main/java/org/apache/commons/text/lookup/ScriptStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/ScriptStringLookup.java
@@ -39,7 +39,11 @@
*
+ * Public access is through {@link StringLookupFactory}.
+ *
*
+ * @see StringLookupFactory
* @since 1.5
*/
final class ScriptStringLookup extends AbstractStringLookup {
@@ -62,7 +66,7 @@ private ScriptStringLookup() {
* For example: {@code "javascript:3 + 4"}.
*
*
- * @param key the engine:script to execute, may be null
+ * @param key the engine:script to execute, may be null.
* @return The value returned by the execution.
*/
@Override
diff --git a/src/main/java/org/apache/commons/text/lookup/StringLookupFactory.java b/src/main/java/org/apache/commons/text/lookup/StringLookupFactory.java
index a323335b4c..699b7deab7 100644
--- a/src/main/java/org/apache/commons/text/lookup/StringLookupFactory.java
+++ b/src/main/java/org/apache/commons/text/lookup/StringLookupFactory.java
@@ -30,6 +30,7 @@
import java.util.function.Function;
import java.util.function.Supplier;
+import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.text.StringSubstitutor;
@@ -277,8 +278,8 @@ static final class DefaultStringLookupsHolder {
* Adds the key and string lookup from {@code lookup} to {@code map}, also adding any additional key aliases if needed. Keys are normalized using the
* {@link #toKey(String)} method.
*
- * @param lookup lookup to add
- * @param map map to add to
+ * @param lookup lookup to add.
+ * @param map map to add to.
*/
private static void addLookup(final DefaultStringLookup lookup, final Map map) {
map.put(toKey(lookup.getKey()), lookup.getStringLookup());
@@ -291,7 +292,7 @@ private static void addLookup(final DefaultStringLookup lookup, final Map createDefaultStringLookups() {
final Map lookupMap = new HashMap<>();
@@ -319,8 +320,8 @@ private static Map createDefaultStringLookups() {
* Constructs a lookup map by parsing the given string. The string is expected to contain comma or space-separated names of values from the
* {@link DefaultStringLookup} enum. If the given string is null or empty, an empty map is returned.
*
- * @param str string to parse; may be null or empty
- * @return lookup map parsed from the given string
+ * @param str string to parse; may be null or empty.
+ * @return lookup map parsed from the given string.
*/
private static Map parseStringLookups(final String str) {
final Map lookupMap = new HashMap<>();
@@ -342,11 +343,11 @@ private static Map parseStringLookups(final String str) {
/**
* Constructs a new instance initialized with the given properties.
*
- * @param props initialization properties
+ * @param props initialization properties.
*/
DefaultStringLookupsHolder(final Properties props) {
- final Map lookups = props.containsKey(StringLookupFactory.DEFAULT_STRING_LOOKUPS_PROPERTY)
- ? parseStringLookups(props.getProperty(StringLookupFactory.DEFAULT_STRING_LOOKUPS_PROPERTY))
+ final Map lookups = props.containsKey(DEFAULT_STRING_LOOKUPS_PROPERTY)
+ ? parseStringLookups(props.getProperty(DEFAULT_STRING_LOOKUPS_PROPERTY))
: createDefaultStringLookups();
defaultStringLookups = Collections.unmodifiableMap(lookups);
}
@@ -354,7 +355,7 @@ private static Map parseStringLookups(final String str) {
/**
* Gets the default string lookups map.
*
- * @return default string lookups map
+ * @return default string lookups map.
*/
Map getDefaultStringLookups() {
return defaultStringLookups;
@@ -363,7 +364,10 @@ Map getDefaultStringLookups() {
/**
* Name of the system property used to determine the string lookups added by the {@link #addDefaultStringLookups(Map)} method. Use of this property is only
- * required in cases where the set of default lookups must be modified. (See the class documentation for details.)
+ * required in cases where the set of default lookups must be modified. (See the {@link StringLookupFactory class documentation} for details.)
+ *
+ * The format of the property string is a comma-separated list of names from the {@link DefaultStringLookup} enum.
+ *
- * The above examples convert {@code "HelloWorld!"} to {@code "SGVsbG9Xb3JsZCE="}.
+ * The examples above convert {@code "HelloWorld!"} to {@code "SGVsbG9Xb3JsZCE="}.
*
* Defines the singleton for this class.
*/
@@ -438,7 +442,7 @@ Map getDefaultStringLookups() {
* StringSubstitutor.createInterpolator().replace("... ${env:USER} ..."));
*
*
- * The above examples convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use {@code "USERNAME"} to the same effect.
+ * The examples above convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use {@code "USERNAME"} to the same effect.
*
*/
static final FunctionStringLookup INSTANCE_ENVIRONMENT_VARIABLES = FunctionStringLookup.on(System::getenv);
@@ -657,6 +661,9 @@ private StringLookupFactory(final Path[] fences) {
* Adds the default string lookups for this class to {@code stringLookupMap}. The default string lookups are a set of built-in lookups added for convenience
* during string interpolation. The defaults may be configured using the {@value #DEFAULT_STRING_LOOKUPS_PROPERTY} system property. See the class
* documentation for details and a list of lookups.
+ *
+ * The format of the property string is a comma-separated list of names from the {@link DefaultStringLookup} enum.
+ *
*
* @param stringLookupMap the map of string lookups to edit.
* @since 1.5
@@ -684,14 +691,14 @@ public void addDefaultStringLookups(final Map stringLookup
* StringSubstitutor.createInterpolator().replace("... ${base64Decoder:SGVsbG9Xb3JsZCE=} ..."));
*
*
- * The above examples convert {@code "SGVsbG9Xb3JsZCE="} to {@code "HelloWorld!"}.
+ * The examples above convert {@code "SGVsbG9Xb3JsZCE="} to {@code "HelloWorld!"}.
*
- * The above examples convert {@code "yyyy-MM-dd"} to todays's date, for example, {@code "2019-08-04"}.
+ * The examples above convert {@code "yyyy-MM-dd"} to todays's date, for example, {@code "2019-08-04"}.
*
*
* @return The DateStringLookup singleton instance.
@@ -856,7 +863,7 @@ public StringLookup dateStringLookup() {
* new StringSubstitutor(variableResolver).replace("... ${dns:address|apache.org} ...");
*
*
- * The above examples convert {@code "address|apache.org"} to the IP address of {@code apache.org}.
+ * The examples above convert {@code "address|apache.org"} to the IP address of {@code apache.org}.
*
- * The above examples convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use {@code "USERNAME"} to the same effect.
+ * The examples above convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use {@code "USERNAME"} to the same effect.
*
- * The above examples convert {@code "UTF-8:com/domain/document.txt"} to the contents of the file.
+ * The examples above convert {@code "UTF-8:com/domain/document.txt"} to the contents of the file.
*
*
* @return a file StringLookup instance.
@@ -1017,7 +1024,7 @@ public StringLookup functionStringLookup(final Function function)
* StringSubstitutor.createInterpolator().replace("... ${sys:os.name}, ${env:USER} ..."));
*
*
- * The above examples convert {@code "${sys:os.name}, ${env:USER}"} to the OS name and Linux user name.
+ * The examples above convert {@code "${sys:os.name}, ${env:USER}"} to the OS name and Linux user name.
*
- * The above examples convert {@code "version"} to the current VM version, for example, {@code "Java version 1.8.0_181"}.
+ * The examples above convert {@code "version"} to the current VM version, for example, {@code "Java version 1.8.0_181"}.
*
- * The above examples convert {@code "canonical-name"} to the current host name, for example, {@code "EXAMPLE.apache.org"}.
+ * The examples above convert {@code "canonical-name"} to the current host name, for example, {@code "EXAMPLE.apache.org"}.
*
- * The above examples convert {@code "canonical-name"} to the current host name, for example, {@code "EXAMPLE.apache.org"}.
+ * The examples above convert {@code "canonical-name"} to the current host name, for example, {@code "EXAMPLE.apache.org"}.
*
*
* @return The InetAddressStringLookup singleton instance.
@@ -1185,7 +1192,7 @@ public StringLookup mapStringLookup(final Map map) {
* @return The NullStringLookup singleton instance.
*/
public StringLookup nullStringLookup() {
- return StringLookupFactory.INSTANCE_NULL;
+ return INSTANCE_NULL;
}
/**
@@ -1195,13 +1202,13 @@ public StringLookup nullStringLookup() {
* if a lookup causes causes a path to resolve outside of these fences. Otherwise, the result is unfenced to preserved behavior from previous versions.
*
*
- * We looks up a value for the key in the format "DocumentPath::MyKey".
+ * We looks up a value for the key in the format {@code "DocumentPath::MyKey"}.
*
*
* Note the use of "::" instead of ":" to allow for "C:" drive letters in paths.
*
*
- * For example: "com/domain/document.properties::MyKey".
+ * For example: {@code "com/domain/document.properties::MyKey"}.
*
- * The above examples convert {@code "com/domain/document.properties::MyKey"} to the key value in the properties file at the path
- * "com/domain/document.properties".
+ * The examples above convert {@code "com/domain/document.properties::MyKey"} to the key value in the properties file at the path
+ * {@code "com/domain/document.properties"}.
*
- * The above examples convert {@code "com.domain.messages:MyKey"} to the key value in the resource bundle at {@code "com.domain.messages"}.
+ * The examples above convert {@code "com.domain.messages:MyKey"} to the key value in the resource bundle at {@code "com.domain.messages"}.
*
*
* @return The ResourceBundleStringLookup singleton instance.
@@ -1392,7 +1399,7 @@ public StringLookup resourceBundleStringLookup(final String bundleName) {
* String value = new StringSubstitutor(variableResolver).replace("${script:javascript:3 + 4}");
*
*
- * The above examples convert {@code "javascript:3 + 4"} to {@code "7"}.
+ * The examples above convert {@code "javascript:3 + 4"} to {@code "7"}.
*
- * The above examples convert {@code "os.name"} to the operating system name.
+ * The examples above convert {@code "os.name"} to the operating system name.
*
- * The above examples convert {@code "Hello World!"} to {@code "Hello%20World%21"}.
+ * The examples above convert {@code "Hello World!"} to {@code "Hello%20World%21"}.
*
*
* @return The UrlStringLookup singleton instance.
@@ -1528,7 +1535,7 @@ public StringLookup urlEncoderStringLookup() {
* String value = new StringSubstitutor(variableResolver).replace("${url:UTF-8:https://www.apache.org}");
*
*
- * The above examples convert {@code "UTF-8:https://www.apache.org"} to the contents of that page.
+ * The examples above convert {@code "UTF-8:https://www.apache.org"} to the contents of that page.
*
- * The above examples convert {@code ""} to {@code "<element>"}.
+ * The examples above convert {@code ""} to {@code "<element>"}.
*
*
* @return The XmlEncoderStringLookup singleton instance.
@@ -1611,10 +1618,17 @@ public StringLookup xmlEncoderStringLookup() {
* if a lookup causes causes a path to resolve outside of these fences. Otherwise, the result is unfenced to preserved behavior from previous versions.
*
*
- * We look up the value for the key in the format "DocumentPath:XPath".
+ * We looks up values in an XML document in the format {@code "DocumentPath:XPath"}.
*
*
- * For example: "com/domain/document.xml:/path/to/node".
+ * For example:
+ *
+ *
+ *
{@code "com/domain/document.xml:/path/to/node"}
+ *
+ *
+ * Secure processing is enabled by default and can be overridden with the system property {@code "XmlStringLookup.secure"} set to {@code false}. The secure
+ * boolean String parsing follows the syntax defined by {@link Boolean#parseBoolean(String)}.
*
*
* Using a {@link StringLookup} from the {@link StringLookupFactory}:
@@ -1631,14 +1645,14 @@ public StringLookup xmlEncoderStringLookup() {
* StringSubstitutor.createInterpolator().replace("... ${xml:com/domain/document.xml:/path/to/node} ..."));
*
*
- * The above examples convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML document.
+ * The examples above convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML document.
*
*
* @return An XML StringLookup instance.
* @since 1.5
*/
public StringLookup xmlStringLookup() {
- return fences != null ? xmlStringLookup(XmlStringLookup.DEFAULT_FEATURES, fences) : XmlStringLookup.INSTANCE;
+ return fences != null ? xmlStringLookup(XmlStringLookup.DEFAULT_XPATH_FEATURES, fences) : XmlStringLookup.INSTANCE;
}
/**
@@ -1648,10 +1662,17 @@ public StringLookup xmlStringLookup() {
* if a lookup causes causes a path to resolve outside of these fences. Otherwise, the result is unfenced to preserved behavior from previous versions.
*
*
- * We look up the value for the key in the format "DocumentPath:XPath".
+ * We looks up values in an XML document in the format {@code "]DocumentPath:XPath"}.
*
*
- * For example: "com/domain/document.xml:/path/to/node".
+ * For example:
+ *
+ *
+ *
{@code "com/domain/document.xml:/path/to/node"}
+ *
+ *
+ * Secure processing is enabled by default and can be overridden with the system property {@code "XmlStringLookup.secure"} set to {@code false}. The secure
+ * boolean String parsing follows the syntax defined by {@link Boolean#parseBoolean(String)}.
*
*
* Using a {@link StringLookup} from the {@link StringLookupFactory}:
@@ -1668,16 +1689,17 @@ public StringLookup xmlStringLookup() {
* StringSubstitutor.createInterpolator().replace("... ${xml:com/domain/document.xml:/path/to/node} ..."));
*
*
- * The above examples convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML document.
+ * The examples above convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML document.
*
*
- * @param xPathFactoryFeatures XPathFactory features to set.
+ * @param factoryFeatures DocumentBuilderFactory and XPathFactory features to set.
* @return An XML StringLookup instance.
+ * @see DocumentBuilderFactory#setFeature(String, boolean)
* @see XPathFactory#setFeature(String, boolean)
* @since 1.11.0
*/
- public StringLookup xmlStringLookup(final Map xPathFactoryFeatures) {
- return xmlStringLookup(xPathFactoryFeatures, fences);
+ public StringLookup xmlStringLookup(final Map factoryFeatures) {
+ return xmlStringLookup(factoryFeatures, fences);
}
/**
@@ -1687,17 +1709,23 @@ public StringLookup xmlStringLookup(final Map xPathFactoryFeatu
* if a lookup causes causes a path to resolve outside of these fences. Otherwise, the result is unfenced to preserved behavior from previous versions.
*
*
- * We look up the value for the key in the format "DocumentPath:XPath".
+ * We looks up values in an XML document in the format {@code "DocumentPath:XPath"}.
+ *
+ *
+ * For example:
*
+ *
+ *
{@code "com/domain/document.xml:/path/to/node"}
+ *
*
- * For example: "com/domain/document.xml:/path/to/node".
+ * Secure processing is enabled by default and can be overridden with this constructor.
*
*
* Using a {@link StringLookup} from the {@link StringLookupFactory} fenced by the current directory ({@code Paths.get("")}):
*
* To use a {@link StringLookup} fenced by the current directory, use:
@@ -1705,27 +1733,27 @@ public StringLookup xmlStringLookup(final Map xPathFactoryFeatu
*
*
- * The above examples convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML document.
+ * The examples above convert {@code "com/domain/document.xml:/path/to/node"} to the value of the XPath in the XML document.
*
*
* {@link StringSubstitutor} methods like {@link StringSubstitutor#replace(String)} will throw a {@link IllegalArgumentException} when a file doesn't
* resolves in a fence.
*
*
- * @param xPathFactoryFeatures XPathFactory features to set.
- * @param fences The fences guarding Path resolution.
+ * @param factoryFeatures DocumentBuilderFactory and XPathFactory features to set.
+ * @param fences The fences guarding Path resolution.
* @return An XML StringLookup instance.
+ * @see DocumentBuilderFactory#setFeature(String, boolean)
+ * @see XPathFactory#setFeature(String, boolean)
* @since 1.12.0
*/
- public StringLookup xmlStringLookup(final Map xPathFactoryFeatures, final Path... fences) {
- return new XmlStringLookup(xPathFactoryFeatures, fences);
+ public StringLookup xmlStringLookup(final Map factoryFeatures, final Path... fences) {
+ return new XmlStringLookup(factoryFeatures, factoryFeatures, fences);
}
}
diff --git a/src/main/java/org/apache/commons/text/lookup/UrlDecoderStringLookup.java b/src/main/java/org/apache/commons/text/lookup/UrlDecoderStringLookup.java
index 8072d36cac..0aabf06b8e 100644
--- a/src/main/java/org/apache/commons/text/lookup/UrlDecoderStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/UrlDecoderStringLookup.java
@@ -24,7 +24,11 @@
/**
* Decodes URL Strings using the UTF-8 encoding.
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
+ *
+ * @see StringLookupFactory
* @since 1.5
*/
final class UrlStringLookup extends AbstractStringLookup {
@@ -55,7 +60,7 @@ private UrlStringLookup() {
* For example: "UTF-8:https://www.apache.org".
*
*
- * @param key the key to be looked up, may be null
+ * @param key the key to be looked up, may be null.
* @return The value associated with the key.
*/
@Override
diff --git a/src/main/java/org/apache/commons/text/lookup/XmlDecoderStringLookup.java b/src/main/java/org/apache/commons/text/lookup/XmlDecoderStringLookup.java
index 3176f33ad0..f3c4e93c10 100644
--- a/src/main/java/org/apache/commons/text/lookup/XmlDecoderStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/XmlDecoderStringLookup.java
@@ -22,6 +22,11 @@
/**
* Decodes strings according to the XML 1.0 specification.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
+ *
+ * @see StringLookupFactory
* @see StringEscapeUtils#unescapeXml(String)
*/
final class XmlDecoderStringLookup extends AbstractStringLookup {
diff --git a/src/main/java/org/apache/commons/text/lookup/XmlEncoderStringLookup.java b/src/main/java/org/apache/commons/text/lookup/XmlEncoderStringLookup.java
index 50e6ffbc4e..b70cd20c9e 100644
--- a/src/main/java/org/apache/commons/text/lookup/XmlEncoderStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/XmlEncoderStringLookup.java
@@ -22,6 +22,11 @@
/**
* Encodes strings according to the XML 1.0 specification.
*
+ *
+ * Public access is through {@link StringLookupFactory}.
+ *
+ *
+ * @see StringLookupFactory
* @see StringEscapeUtils#escapeXml10(String)
* @since 1.11.0
*/
diff --git a/src/main/java/org/apache/commons/text/lookup/XmlStringLookup.java b/src/main/java/org/apache/commons/text/lookup/XmlStringLookup.java
index a476cc0786..ee33441993 100644
--- a/src/main/java/org/apache/commons/text/lookup/XmlStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/XmlStringLookup.java
@@ -26,38 +26,56 @@
import java.util.Objects;
import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang3.StringUtils;
-import org.xml.sax.InputSource;
+import org.w3c.dom.Document;
/**
- * Looks up keys from an XML document.
+ * Looks up values in an XML document in the format {@code "DocumentPath:XPath"}.
*
- * Looks up the value for a given key in the format "Document:XPath".
+ * For example:
*
+ *
+ *
{@code "com/domain/document.xml:/path/to/node"}
+ *
*
- * For example: "com/domain/document.xml:/path/to/node".
+ * Secure processing is enabled by default and can be overridden with {@link StringLookupFactory#xmlStringLookup(Map, Path...)}.
*
*
* @since 1.5
*/
final class XmlStringLookup extends AbstractPathFencedLookup {
+ /**
+ * The number of key parts.
+ */
+ private static final int KEY_PARTS_LEN = 2;
+
/**
* Defines default XPath factory features.
*/
- static final Map DEFAULT_FEATURES;
+ static final Map DEFAULT_XPATH_FEATURES;
+ /**
+ * Defines default XML factory features.
+ */
+ static final Map DEFAULT_XML_FEATURES;
static {
- DEFAULT_FEATURES = new HashMap<>(1);
- DEFAULT_FEATURES.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+ DEFAULT_XPATH_FEATURES = new HashMap<>(1);
+ DEFAULT_XPATH_FEATURES.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+ DEFAULT_XML_FEATURES = new HashMap<>(1);
+ DEFAULT_XML_FEATURES.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
}
/**
- * Defines the singleton for this class.
+ * Defines the singleton for this class with secure processing enabled by default.
+ *
+ * Secure processing is enabled by default and can be overridden with {@link StringLookupFactory#xmlStringLookup(Map, Path...)}.
+ *
*/
- static final XmlStringLookup INSTANCE = new XmlStringLookup(DEFAULT_FEATURES, (Path[]) null);
+ static final XmlStringLookup INSTANCE = new XmlStringLookup(DEFAULT_XML_FEATURES, DEFAULT_XPATH_FEATURES, (Path[]) null);
/**
* Defines XPath factory features.
@@ -65,23 +83,37 @@ final class XmlStringLookup extends AbstractPathFencedLookup {
private final Map xPathFactoryFeatures;
/**
- * No need to build instances for now.
+ * Defines XML factory features.
+ */
+ private final Map xmlFactoryFeatures;
+
+ /**
+ * Constructs a new instance.
*
- * @param xPathFactoryFeatures XPathFactory features to set.
+ * @param xmlFactoryFeatures The {@link DocumentBuilderFactory} features to set.
+ * @param xPathFactoryFeatures The {@link XPathFactory} features to set.
+ * @see DocumentBuilderFactory#setFeature(String, boolean)
* @see XPathFactory#setFeature(String, boolean)
*/
- XmlStringLookup(final Map xPathFactoryFeatures, final Path... fences) {
+ XmlStringLookup(final Map xmlFactoryFeatures, final Map xPathFactoryFeatures, final Path... fences) {
super(fences);
+ this.xmlFactoryFeatures = Objects.requireNonNull(xmlFactoryFeatures, "xmlFactoryFeatures");
this.xPathFactoryFeatures = Objects.requireNonNull(xPathFactoryFeatures, "xPathFfactoryFeatures");
}
/**
- * Looks up the value for the key in the format "DocumentPath:XPath".
+ * Looks up a value for the key in the format {@code "DocumentPath:XPath"}.
*
- * For example: "com/domain/document.xml:/path/to/node".
+ * For example:
+ *
+ *
+ *
{@code "com/domain/document.xml:/path/to/node"}
+ *
+ *
+ * Secure processing is enabled by default and can be overridden with {@link StringLookupFactory#xmlStringLookup(Map, Path...)}.
*
*
- * @param key the key to be looked up, may be null
+ * @param key the key to be looked up, may be null.
* @return The value associated with the key.
*/
@Override
@@ -91,22 +123,26 @@ public String lookup(final String key) {
}
final String[] keys = key.split(SPLIT_STR);
final int keyLen = keys.length;
- if (keyLen != 2) {
- throw IllegalArgumentExceptions.format("Bad XML key format [%s]; expected format is DocumentPath:XPath.",
- key);
+ if (keyLen != KEY_PARTS_LEN) {
+ throw IllegalArgumentExceptions.format("Bad XML key format '%s'; the expected format is 'DocumentPath:XPath'.", key);
}
final String documentPath = keys[0];
- final String xpath = StringUtils.substringAfter(key, SPLIT_CH);
- try (InputStream inputStream = Files.newInputStream(getPath(documentPath))) {
- final XPathFactory factory = XPathFactory.newInstance();
- for (final Entry p : xPathFactoryFeatures.entrySet()) {
- factory.setFeature(p.getKey(), p.getValue());
+ final String xpath = StringUtils.substringAfterLast(key, SPLIT_CH);
+ final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
+ try {
+ for (final Entry p : xmlFactoryFeatures.entrySet()) {
+ dbFactory.setFeature(p.getKey(), p.getValue());
+ }
+ try (InputStream inputStream = Files.newInputStream(getPath(documentPath))) {
+ final Document doc = dbFactory.newDocumentBuilder().parse(inputStream);
+ final XPathFactory xpFactory = XPathFactory.newInstance();
+ for (final Entry p : xPathFactoryFeatures.entrySet()) {
+ xpFactory.setFeature(p.getKey(), p.getValue());
+ }
+ return xpFactory.newXPath().evaluate(xpath, doc);
}
- return factory.newXPath().evaluate(xpath, new InputSource(inputStream));
} catch (final Exception e) {
- throw IllegalArgumentExceptions.format(e, "Error looking up XML document [%s] and XPath [%s].",
- documentPath, xpath);
+ throw new IllegalArgumentException(e);
}
}
-
}
diff --git a/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java b/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java
index 68ec022d23..04dc401689 100644
--- a/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java
+++ b/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java
@@ -124,11 +124,11 @@ static final class CharArrayMatcher extends AbstractStringMatcher {
/**
* Returns the number of matching characters, {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd the end index of the active buffer, valid for buffer.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -148,11 +148,11 @@ public int isMatch(final char[] buffer, final int start, final int bufferStart,
/**
* Returns the number of matching characters, {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd the end index of the active buffer, valid for buffer.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final CharSequence buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -209,11 +209,11 @@ static final class CharMatcher extends AbstractStringMatcher {
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -223,11 +223,11 @@ public int isMatch(final char[] buffer, final int start, final int bufferStart,
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final CharSequence buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -264,7 +264,7 @@ static final class CharSetMatcher extends AbstractStringMatcher {
/**
* Constructs a matcher from a character array.
*
- * @param chars the characters to match, must not be null
+ * @param chars the characters to match, must not be null.
*/
CharSetMatcher(final char[] chars) {
this.chars = chars.clone();
@@ -274,11 +274,11 @@ static final class CharSetMatcher extends AbstractStringMatcher {
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -288,11 +288,11 @@ public int isMatch(final char[] buffer, final int start, final int bufferStart,
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final CharSequence buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -333,11 +333,11 @@ static final class NoneMatcher extends AbstractStringMatcher {
/**
* Always returns {@code 0}.
*
- * @param buffer unused
- * @param start unused
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer unused.
+ * @param start unused.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -347,11 +347,11 @@ public int isMatch(final char[] buffer, final int start, final int bufferStart,
/**
* Always returns {@code 0}.
*
- * @param buffer unused
- * @param start unused
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer unused.
+ * @param start unused.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final CharSequence buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -392,11 +392,11 @@ static final class TrimMatcher extends AbstractStringMatcher {
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
@@ -406,11 +406,11 @@ public int isMatch(final char[] buffer, final int start, final int bufferStart,
/**
* Returns {@code 1} if there is a match, or {@code 0} if there is no match.
*
- * @param buffer the text content to match against, do not change
- * @param start the starting position for the match, valid for buffer
- * @param bufferStart unused
- * @param bufferEnd unused
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param start the starting position for the match, valid for buffer.
+ * @param bufferStart unused.
+ * @param bufferEnd unused.
+ * @return The number of matching characters, zero for no match.
*/
@Override
public int isMatch(final CharSequence buffer, final int start, final int bufferStart, final int bufferEnd) {
diff --git a/src/main/java/org/apache/commons/text/matcher/StringMatcher.java b/src/main/java/org/apache/commons/text/matcher/StringMatcher.java
index af94b86831..57d93b5d19 100644
--- a/src/main/java/org/apache/commons/text/matcher/StringMatcher.java
+++ b/src/main/java/org/apache/commons/text/matcher/StringMatcher.java
@@ -53,9 +53,9 @@ default StringMatcher andThen(final StringMatcher stringMatcher) {
* characters that matched.
*
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @return The number of matching characters, zero for no match.
* @since 1.9
*/
default int isMatch(final char[] buffer, final int pos) {
@@ -106,9 +106,9 @@ default int isMatch(final char[] buffer, final int pos) {
* characters that matched.
*
*
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @return The number of matching characters, zero for no match
+ * @param buffer the text content to match against, do not change.
+ * @param pos the starting position for the match, valid for buffer.
+ * @return The number of matching characters, zero for no match.
* @since 1.9
*/
default int isMatch(final CharSequence buffer, final int pos) {
diff --git a/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java b/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java
index 0a3b9d8afd..b3c1226575 100644
--- a/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java
+++ b/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java
@@ -91,7 +91,7 @@ private StringMatcherFactory() {
/**
* Creates a matcher that matches all of the given matchers in order.
*
- * @param stringMatchers the matcher
+ * @param stringMatchers the matcher.
* @return a matcher that matches all of the given matchers in order.
* @since 1.9
*/
@@ -109,8 +109,8 @@ public StringMatcher andMatcher(final StringMatcher... stringMatchers) {
/**
* Constructor that creates a matcher from a character.
*
- * @param ch the character to match, must not be null
- * @return a new Matcher for the given char
+ * @param ch the character to match, must not be null.
+ * @return a new Matcher for the given char.
*/
public StringMatcher charMatcher(final char ch) {
return new AbstractStringMatcher.CharMatcher(ch);
@@ -119,8 +119,8 @@ public StringMatcher charMatcher(final char ch) {
/**
* Constructor that creates a matcher from a set of characters.
*
- * @param chars the characters to match, null or empty matches nothing
- * @return a new matcher for the given char[]
+ * @param chars the characters to match, null or empty matches nothing.
+ * @return a new matcher for the given char[].
*/
public StringMatcher charSetMatcher(final char... chars) {
final int len = ArrayUtils.getLength(chars);
@@ -136,8 +136,8 @@ public StringMatcher charSetMatcher(final char... chars) {
/**
* Creates a matcher from a string representing a set of characters.
*
- * @param chars the characters to match, null or empty matches nothing
- * @return a new Matcher for the given characters
+ * @param chars the characters to match, null or empty matches nothing.
+ * @return a new Matcher for the given characters.
*/
public StringMatcher charSetMatcher(final String chars) {
final int len = StringUtils.length(chars);
@@ -153,7 +153,7 @@ public StringMatcher charSetMatcher(final String chars) {
/**
* Returns a matcher which matches the comma character.
*
- * @return a matcher for a comma
+ * @return a matcher for a comma.
*/
public StringMatcher commaMatcher() {
return COMMA_MATCHER;
@@ -162,7 +162,7 @@ public StringMatcher commaMatcher() {
/**
* Returns a matcher which matches the double quote character.
*
- * @return a matcher for a double quote
+ * @return a matcher for a double quote.
*/
public StringMatcher doubleQuoteMatcher() {
return DOUBLE_QUOTE_MATCHER;
@@ -171,7 +171,7 @@ public StringMatcher doubleQuoteMatcher() {
/**
* Matches no characters.
*
- * @return a matcher that matches nothing
+ * @return a matcher that matches nothing.
*/
public StringMatcher noneMatcher() {
return NONE_MATCHER;
@@ -180,7 +180,7 @@ public StringMatcher noneMatcher() {
/**
* Returns a matcher which matches the single or double quote character.
*
- * @return a matcher for a single or double quote
+ * @return a matcher for a single or double quote.
*/
public StringMatcher quoteMatcher() {
return QUOTE_MATCHER;
@@ -189,7 +189,7 @@ public StringMatcher quoteMatcher() {
/**
* Returns a matcher which matches the single quote character.
*
- * @return a matcher for a single quote
+ * @return a matcher for a single quote.
*/
public StringMatcher singleQuoteMatcher() {
return SINGLE_QUOTE_MATCHER;
@@ -198,7 +198,7 @@ public StringMatcher singleQuoteMatcher() {
/**
* Returns a matcher which matches the space character.
*
- * @return a matcher for a space
+ * @return a matcher for a space.
*/
public StringMatcher spaceMatcher() {
return SPACE_MATCHER;
@@ -207,7 +207,7 @@ public StringMatcher spaceMatcher() {
/**
* Matches the same characters as StringTokenizer, namely space, tab, newline and form feed.
*
- * @return The split matcher
+ * @return The split matcher.
*/
public StringMatcher splitMatcher() {
return SPLIT_MATCHER;
@@ -216,8 +216,8 @@ public StringMatcher splitMatcher() {
/**
* Creates a matcher from a string.
*
- * @param chars the string to match, null or empty matches nothing
- * @return a new Matcher for the given String
+ * @param chars the string to match, null or empty matches nothing.
+ * @return a new Matcher for the given String.
* @since 1.9
*/
public StringMatcher stringMatcher(final char... chars) {
@@ -230,8 +230,8 @@ public StringMatcher stringMatcher(final char... chars) {
/**
* Creates a matcher from a string.
*
- * @param str the string to match, null or empty matches nothing
- * @return a new Matcher for the given String
+ * @param str the string to match, null or empty matches nothing.
+ * @return a new Matcher for the given String.
*/
public StringMatcher stringMatcher(final String str) {
return StringUtils.isEmpty(str) ? NONE_MATCHER : stringMatcher(str.toCharArray());
@@ -240,7 +240,7 @@ public StringMatcher stringMatcher(final String str) {
/**
* Returns a matcher which matches the tab character.
*
- * @return a matcher for a tab
+ * @return a matcher for a tab.
*/
public StringMatcher tabMatcher() {
return TAB_MATCHER;
@@ -249,7 +249,7 @@ public StringMatcher tabMatcher() {
/**
* Matches the String trim() whitespace characters.
*
- * @return The trim matcher
+ * @return The trim matcher.
*/
public StringMatcher trimMatcher() {
return TRIM_MATCHER;
diff --git a/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java b/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java
index 74e1713894..214f380f52 100644
--- a/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java
+++ b/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java
@@ -251,7 +251,7 @@ public String apply(final double d) {
/**
* Returns a formatted string representation of the given finite value.
*
- * @param d double value
+ * @param d double value.
*/
private String applyFinite(final double d) {
final ParsedDecimal n = ParsedDecimal.from(d);
@@ -268,7 +268,7 @@ private String applyFinite(final double d) {
/**
* Returns a formatted representation of the given rounded decimal value to {@code dst}.
*
- * @param val value to format
+ * @param val value to format.
* @return a formatted representation of the given rounded decimal value to {@code dst}.
*/
protected abstract String applyFiniteInternal(ParsedDecimal val);
@@ -411,7 +411,7 @@ private static String getDigitString(final DecimalFormatSymbols symbols) {
/**
* Builds a new instance that delegates double function construction to the given factory object.
*
- * @param factory factory function
+ * @param factory factory function.
*/
private Builder(final Function> factory) {
this.factory = factory;
@@ -423,8 +423,8 @@ private Builder(final Function> factory) {
* returned, regardless of the sign of the input number. The default value is {@code true}.
*
* @param signedZero if {@code true}, the zero string may be returned with a preceding minus sign; if {@code false}, the zero string will only be
- * returned in its positive form
- * @return this instance
+ * returned in its positive form.
+ * @return {@code this} instance.
*/
public Builder allowSignedZero(final boolean signedZero) {
this.signedZero = signedZero;
@@ -436,8 +436,8 @@ public Builder allowSignedZero(final boolean signedZero) {
* only applies to formats that use scientific notation, namely {@link DoubleFormat#SCIENTIFIC SCIENTIFIC}, {@link DoubleFormat#ENGINEERING
* ENGINEERING}, and {@link DoubleFormat#MIXED MIXED}. The default value is {@code false}.
*
- * @param alwaysIncludeExponent if {@code true}, exponents will always be included in formatted output even if the exponent value is zero
- * @return this instance
+ * @param alwaysIncludeExponent if {@code true}, exponents will always be included in formatted output even if the exponent value is zero.
+ * @return {@code this} instance.
*/
public Builder alwaysIncludeExponent(final boolean alwaysIncludeExponent) {
this.alwaysIncludeExponent = alwaysIncludeExponent;
@@ -459,8 +459,8 @@ public DoubleFunction build() {
* Sets the decimal separator character, i.e., the character placed between the whole number and fractional portions of the formatted strings. The
* default value is {@code '.'}.
*
- * @param decimalSeparator decimal separator character
- * @return this instance
+ * @param decimalSeparator decimal separator character.
+ * @return {@code this} instance.
*/
public Builder decimalSeparator(final char decimalSeparator) {
this.decimalSeparator = decimalSeparator;
@@ -470,10 +470,10 @@ public Builder decimalSeparator(final char decimalSeparator) {
/**
* Sets the string containing the digit characters 0-9, in that order. The default value is the string {@code "0123456789"}.
*
- * @param digits string containing the digit characters 0-9
- * @return this instance
- * @throws NullPointerException if the argument is {@code null}
- * @throws IllegalArgumentException if the argument does not have a length of exactly 10
+ * @param digits string containing the digit characters 0-9.
+ * @return {@code this} instance.
+ * @throws NullPointerException if the argument is {@code null}.
+ * @throws IllegalArgumentException if the argument does not have a length of exactly 10.
*/
public Builder digits(final String digits) {
Objects.requireNonNull(digits, "digits");
@@ -489,9 +489,9 @@ public Builder digits(final String digits) {
* Sets the exponent separator character, i.e., the string placed between the mantissa and the exponent. The default value is {@code "E"}, as in
* {@code "1.2E6"}.
*
- * @param exponentSeparator exponent separator string
- * @return this instance
- * @throws NullPointerException if the argument is {@code null}
+ * @param exponentSeparator exponent separator string.
+ * @return {@code this} instance.
+ * @throws NullPointerException if the argument is {@code null}.
*/
public Builder exponentSeparator(final String exponentSeparator) {
this.exponentSeparator = Objects.requireNonNull(exponentSeparator, "exponentSeparator");
@@ -512,9 +512,9 @@ public Builder exponentSeparator(final String exponentSeparator) {
* The digit character string is constructed by starting at the configured {@link DecimalFormatSymbols#getZeroDigit() zero digit} and adding the next 9
* consecutive characters.
*
- * @param symbols format symbols
- * @return this instance
- * @throws NullPointerException if the argument is {@code null}
+ * @param symbols format symbols.
+ * @return {@code this} instance.
+ * @throws NullPointerException if the argument is {@code null}.
*/
public Builder formatSymbols(final DecimalFormatSymbols symbols) {
Objects.requireNonNull(symbols, "symbols");
@@ -526,7 +526,7 @@ public Builder formatSymbols(final DecimalFormatSymbols symbols) {
/**
* Builds a new double format function.
*
- * @return format function
+ * @return a new double format function.
*/
@Override
public DoubleFunction get() {
@@ -536,8 +536,8 @@ public DoubleFunction get() {
/**
* Sets the character used to separate groups of thousands. Default value is {@code ','}.
*
- * @param groupingSeparator character used to separate groups of thousands
- * @return this instance
+ * @param groupingSeparator character used to separate groups of thousands.
+ * @return {@code this} instance.
* @see #groupThousands(boolean)
*/
public Builder groupingSeparator(final char groupingSeparator) {
@@ -550,8 +550,8 @@ public Builder groupingSeparator(final char groupingSeparator) {
* the number {@code 1000} could be formatted as {@code "1,000"}. This property only applies to the {@link DoubleFormat#PLAIN PLAIN} format. Default
* value is {@code false}.
*
- * @param groupThousands if {@code true}, thousands will be grouped
- * @return this instance
+ * @param groupThousands if {@code true}, thousands will be grouped.
+ * @return {@code this} instance.
* @see #groupingSeparator(char)
*/
public Builder groupThousands(final boolean groupThousands) {
@@ -565,8 +565,8 @@ public Builder groupThousands(final boolean groupThousands) {
* is {@code true}.
*
* @param fractionPlaceholder if {@code true}, a zero character is placed in the fraction position when no fractional value is present; if
- * {@code false}, fractional digits are only included when needed
- * @return this instance
+ * {@code false}, fractional digits are only included when needed.
+ * @return {@code this} instance.
*/
public Builder includeFractionPlaceholder(final boolean fractionPlaceholder) {
this.fractionPlaceholder = fractionPlaceholder;
@@ -576,9 +576,9 @@ public Builder includeFractionPlaceholder(final boolean fractionPlaceholder) {
/**
* Sets the string used to represent infinity. For negative infinity, this string is prefixed with the {@link #minusSign(char) minus sign}.
*
- * @param infinity string used to represent infinity
- * @return this instance
- * @throws NullPointerException if the argument is {@code null}
+ * @param infinity string used to represent infinity.
+ * @return {@code this} instance.
+ * @throws NullPointerException if the argument is {@code null}.
*/
public Builder infinity(final String infinity) {
this.infinity = Objects.requireNonNull(infinity, "infinity");
@@ -589,8 +589,8 @@ public Builder infinity(final String infinity) {
* Sets the maximum number of significant decimal digits used in format results. A value of {@code 0} indicates no limit. The default value is
* {@code 0}.
*
- * @param maxPrecision maximum precision
- * @return this instance
+ * @param maxPrecision maximum precision.
+ * @return {@code this} instance.
*/
public Builder maxPrecision(final int maxPrecision) {
this.maxPrecision = maxPrecision;
@@ -603,8 +603,8 @@ public Builder maxPrecision(final int maxPrecision) {
* {@code minDecimalExponent} is set to {@code -2} and the number {@code 3.14159} is formatted, the plain format result will be {@code "3.14"}. If
* {@code 0.001} is formatted, then the result is the zero string.
*
- * @param minDecimalExponent minimum decimal exponent
- * @return this instance
+ * @param minDecimalExponent minimum decimal exponent.
+ * @return {@code this} instance.
*/
public Builder minDecimalExponent(final int minDecimalExponent) {
this.minDecimalExponent = minDecimalExponent;
@@ -614,8 +614,8 @@ public Builder minDecimalExponent(final int minDecimalExponent) {
/**
* Sets the character used as the minus sign.
*
- * @param minusSign character to use as the minus sign
- * @return this instance
+ * @param minusSign character to use as the minus sign.
+ * @return {@code this} instance.
*/
public Builder minusSign(final char minusSign) {
this.minusSign = minusSign;
@@ -625,9 +625,9 @@ public Builder minusSign(final char minusSign) {
/**
* Sets the string used to represent {@link Double#NaN}.
*
- * @param nan string used to represent {@link Double#NaN}
- * @return this instance
- * @throws NullPointerException if the argument is {@code null}
+ * @param nan string used to represent {@link Double#NaN}.
+ * @return {@code this} instance.
+ * @throws NullPointerException if the argument is {@code null}.
*/
public Builder nan(final String nan) {
this.nan = Objects.requireNonNull(nan, "nan");
@@ -635,21 +635,23 @@ public Builder nan(final String nan) {
}
/**
- * Sets the maximum decimal exponent for numbers formatted as plain decimal strings when using the {@link DoubleFormat#MIXED MIXED} format type. If the
- * number being formatted has an absolute value less than 10plainFormatMaxDecimalExponent + 1 and greater than or equal to
- * 10plainFormatMinDecimalExponent after any necessary rounding, then the formatted result will use the
+ * Sets the maximum decimal exponent for numbers formatted as plain decimal strings when using the {@link DoubleFormat#MIXED MIXED} format type.
+ *
+ * If the number being formatted has an absolute value less than 10plainFormatMaxDecimalExponent + 1 and greater than or equal
+ * to 10plainFormatMinDecimalExponent after any necessary rounding, then the formatted result will use the
* {@link DoubleFormat#PLAIN PLAIN} format type. Otherwise, {@link DoubleFormat#SCIENTIFIC SCIENTIFIC} format will be used. For example, if this value
* is set to {@code 2}, the number {@code 999} will be formatted as {@code "999.0"} while {@code 1000} will be formatted as {@code "1.0E3"}.
- *
+ *
*
* The default value is {@code 6}.
- *
+ *
*
* This value is ignored for formats other than {@link DoubleFormat#MIXED}.
+ *
*
* @param plainFormatMaxDecimalExponent maximum decimal exponent for values formatted as plain strings when using the {@link DoubleFormat#MIXED MIXED}
* format type.
- * @return this instance
+ * @return {@code this} instance
* @see #plainFormatMinDecimalExponent(int)
*/
public Builder plainFormatMaxDecimalExponent(final int plainFormatMaxDecimalExponent) {
@@ -658,21 +660,23 @@ public Builder plainFormatMaxDecimalExponent(final int plainFormatMaxDecimalExpo
}
/**
- * Sets the minimum decimal exponent for numbers formatted as plain decimal strings when using the {@link DoubleFormat#MIXED MIXED} format type. If the
- * number being formatted has an absolute value less than 10plainFormatMaxDecimalExponent + 1 and greater than or equal to
- * 10plainFormatMinDecimalExponent after any necessary rounding, then the formatted result will use the
+ * Sets the minimum decimal exponent for numbers formatted as plain decimal strings when using the {@link DoubleFormat#MIXED MIXED} format type.
+ *
+ * If the number being formatted has an absolute value less than 10plainFormatMaxDecimalExponent + 1 and greater than or equal
+ * to 10plainFormatMinDecimalExponent after any necessary rounding, then the formatted result will use the
* {@link DoubleFormat#PLAIN PLAIN} format type. Otherwise, {@link DoubleFormat#SCIENTIFIC SCIENTIFIC} format will be used. For example, if this value
* is set to {@code -2}, the number {@code 0.01} will be formatted as {@code "0.01"} while {@code 0.0099} will be formatted as {@code "9.9E-3"}.
- *
+ *
*
* The default value is {@code -3}.
- *
+ *
*
* This value is ignored for formats other than {@link DoubleFormat#MIXED}.
+ *
*
* @param plainFormatMinDecimalExponent maximum decimal exponent for values formatted as plain strings when using the {@link DoubleFormat#MIXED MIXED}
* format type.
- * @return this instance
+ * @return {@code this} instance
* @see #plainFormatMinDecimalExponent(int)
*/
public Builder plainFormatMinDecimalExponent(final int plainFormatMinDecimalExponent) {
diff --git a/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java b/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java
index 4bc4d1c681..d4541b0280 100644
--- a/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java
+++ b/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java
@@ -44,59 +44,64 @@ interface FormatOptions {
/**
* Gets the decimal separator character.
+ *
* @return decimal separator character
*/
char getDecimalSeparator();
/**
- * Gets an array containing the localized digit characters 0-9 in that order.
- * This string must be non-null and have a length of 10.
- * @return array containing the digit characters 0-9
+ * Gets an array containing the localized digit characters 0-9 in that order. This string must be non-null and have a length of 10.
+ *
+ * @return array containing the digit characters 0-9.
*/
char[] getDigits();
/**
* Gets the exponent separator as an array of characters.
- * @return exponent separator as an array of characters
+ *
+ * @return exponent separator as an array of characters.
*/
char[] getExponentSeparatorChars();
/**
* Gets the character used to separate thousands groupings.
- * @return character used to separate thousands groupings
+ *
+ * @return character used to separate thousands groupings.
*/
char getGroupingSeparator();
/**
* Gets the minus sign character.
- * @return minus sign character
+ *
+ * @return minus sign character.
*/
char getMinusSign();
/**
- * Return {@code true} if exponent values should always be included in
- * formatted output, even if the value is zero.
- * @return {@code true} if exponent values should always be included
+ * Return {@code true} if exponent values should always be included in formatted output, even if the value is zero.
+ *
+ * @return {@code true} if exponent values should always be included.
*/
boolean isAlwaysIncludeExponent();
/**
* Return {@code true} if thousands should be grouped.
- * @return {@code true} if thousand should be grouped
+ *
+ * @return {@code true} if thousand should be grouped.
*/
boolean isGroupThousands();
/**
- * Return {@code true} if fraction placeholders (e.g., {@code ".0"} in {@code "1.0"})
- * should be included.
- * @return {@code true} if fraction placeholders should be included
+ * Return {@code true} if fraction placeholders (e.g., {@code ".0"} in {@code "1.0"}) should be included.
+ *
+ * @return {@code true} if fraction placeholders should be included.
*/
boolean isIncludeFractionPlaceholder();
/**
- * Return {@code true} if the string zero should be prefixed with the minus sign
- * for negative zero values.
- * @return {@code true} if the minus zero string should be allowed
+ * Return {@code true} if the string zero should be prefixed with the minus sign for negative zero values.
+ *
+ * @return {@code true} if the minus zero string should be allowed.
*/
boolean isSignedZero();
}
@@ -128,8 +133,9 @@ interface FormatOptions {
/**
* Gets the numeric value of the given digit character. No validation of the
* character type is performed.
- * @param ch digit character
- * @return numeric value of the digit character, ex: '1' = 1
+ *
+ * @param ch digit character.
+ * @return numeric value of the digit character, ex: '1' = 1.
*/
private static int digitValue(final char ch) {
return ch - ZERO_CHAR;
@@ -137,9 +143,10 @@ private static int digitValue(final char ch) {
/**
* Constructs a new instance from the given double value.
- * @param d double value
- * @return a new instance containing the parsed components of the given double value
- * @throws IllegalArgumentException if {@code d} is {@code NaN} or infinite
+ *
+ * @param d double value.
+ * @return a new instance containing the parsed components of the given double value.
+ * @throws IllegalArgumentException if {@code d} is {@code NaN} or infinite.
*/
public static ParsedDecimal from(final double d) {
if (!Double.isFinite(d)) {
@@ -206,9 +213,10 @@ public static ParsedDecimal from(final double d) {
/**
* Parses a double exponent value from {@code chars}, starting at the {@code start}
* index and continuing through the end of the array.
- * @param chars character array to parse a double exponent value from
- * @param start start index
- * @return parsed exponent value
+ *
+ * @param chars character array to parse a double exponent value from.
+ * @param start start index.
+ * @return parsed exponent value.
*/
private static int parseExponent(final char[] chars, final int start) {
int i = start;
@@ -245,10 +253,11 @@ private static int parseExponent(final char[] chars, final int start) {
/**
* Constructs a new instance from its parts.
- * @param negative {@code true} if the value is negative
- * @param digits array containing significant digits
- * @param digitCount number of digits used from the {@code digits} array
- * @param exponent exponent value
+ *
+ * @param negative {@code true} if the value is negative.
+ * @param digits array containing significant digits.
+ * @param digitCount number of digits used from the {@code digits} array.
+ * @param exponent exponent value.
*/
private ParsedDecimal(final boolean negative, final int[] digits, final int digitCount,
final int exponent) {
@@ -260,7 +269,8 @@ private ParsedDecimal(final boolean negative, final int[] digits, final int digi
/**
* Appends the given character to the output buffer.
- * @param ch character to append
+ *
+ * @param ch character to append.
*/
private void append(final char ch) {
outputChars[outputIdx++] = ch;
@@ -268,7 +278,8 @@ private void append(final char ch) {
/**
* Appends the given character array directly to the output buffer.
- * @param chars characters to append
+ *
+ * @param chars characters to append.
*/
private void append(final char[] chars) {
for (final char c : chars) {
@@ -278,10 +289,10 @@ private void append(final char[] chars) {
/**
* Appends the fractional component of the number to the current output buffer.
- * @param zeroCount number of zeros to add after the decimal point and before the
- * first significant digit
- * @param startIdx significant digit start index
- * @param opts format options
+ *
+ * @param zeroCount number of zeros to add after the decimal point and before the first significant digit.
+ * @param startIdx significant digit start index.
+ * @param opts format options.
*/
private void appendFraction(final int zeroCount, final int startIdx, final FormatOptions opts) {
final char[] localizedDigits = opts.getDigits();
@@ -307,20 +318,20 @@ private void appendFraction(final int zeroCount, final int startIdx, final Forma
/**
* Appends the localized representation of the digit {@code n} to the output buffer.
- * @param n digit to append
- * @param digitChars character array containing localized versions of the digits {@code 0-9}
- * in that order
+ *
+ * @param n digit to append.
+ * @param digitChars character array containing localized versions of the digits {@code 0-9} in that order.
*/
private void appendLocalizedDigit(final int n, final char[] digitChars) {
append(digitChars[n]);
}
/**
- * Appends the whole number portion of this value to the output buffer. No thousands
- * separators are added.
- * @param wholeCount total number of digits required to the left of the decimal point
- * @param opts format options
- * @return number of digits from {@code digits} appended to the output buffer
+ * Appends the whole number portion of this value to the output buffer. No thousands separators are added.
+ *
+ * @param wholeCount total number of digits required to the left of the decimal point.
+ * @param opts format options.
+ * @return number of digits from {@code digits} appended to the output buffer.
* @see #appendWholeGrouped(int, FormatOptions)
*/
private int appendWhole(final int wholeCount, final FormatOptions opts) {
@@ -350,11 +361,11 @@ private int appendWhole(final int wholeCount, final FormatOptions opts) {
}
/**
- * Appends the whole number portion of this value to the output buffer, adding thousands
- * separators as needed.
+ * Appends the whole number portion of this value to the output buffer, adding thousands separators as needed.
+ *
* @param wholeCount total number of digits required to the right of the decimal point
- * @param opts format options
- * @return number of digits from {@code digits} appended to the output buffer
+ * @param opts format options.
+ * @return number of digits from {@code digits} appended to the output buffer.
* @see #appendWhole(int, FormatOptions)
*/
private int appendWholeGrouped(final int wholeCount, final FormatOptions opts) {
@@ -392,12 +403,12 @@ private int appendWholeGrouped(final int wholeCount, final FormatOptions opts) {
}
/**
- * Gets the number of characters required for the digit portion of a string representation of
- * this value. This excludes any exponent or thousands groupings characters.
- * @param decimalPos decimal point position relative to the {@code digits} array
- * @param opts format options
- * @return number of characters required for the digit portion of a string representation of
- * this value
+ * Gets the number of characters required for the digit portion of a string representation of this value. This excludes any exponent or thousands groupings
+ * characters.
+ *
+ * @param decimalPos decimal point position relative to the {@code digits} array.
+ * @param opts format options.
+ * @return number of characters required for the digit portion of a string representation of this value.
*/
private int getDigitStringSize(final int decimalPos, final FormatOptions opts) {
int size = digitCount;
@@ -425,21 +436,20 @@ private int getDigitStringSize(final int decimalPos, final FormatOptions opts) {
}
/**
- * Gets the exponent value. This exponent produces a floating point value with the
- * correct magnitude when applied to the internal unsigned integer.
- * @return exponent value
+ * Gets the exponent value. This exponent produces a floating point value with the correct magnitude when applied to the internal unsigned integer.
+ *
+ * @return exponent value.
*/
public int getExponent() {
return exponent;
}
/**
- * Gets the number of characters required to create a plain format representation
- * of this value.
- * @param decimalPos decimal position relative to the {@code digits} array
- * @param opts format options
- * @return number of characters in the plain string representation of this value,
- * created using the given parameters
+ * Gets the number of characters required to create a plain format representation of this value.
+ *
+ * @param decimalPos decimal position relative to the {@code digits} array.
+ * @param opts format options.
+ * @return number of characters in the plain string representation of this value, created using the given parameters.
*/
private int getPlainStringSize(final int decimalPos, final FormatOptions opts) {
int size = getDigitStringSize(decimalPos, opts);
@@ -453,30 +463,31 @@ private int getPlainStringSize(final int decimalPos, final FormatOptions opts) {
}
/**
- * Gets the exponent that would be used when representing this number in scientific
- * notation (i.e., with a single non-zero digit in front of the decimal point).
- * @return the exponent that would be used when representing this number in scientific
- * notation
+ * Gets the exponent that would be used when representing this number in scientific notation (i.e., with a single non-zero digit in front of the decimal
+ * point).
+ *
+ * @return the exponent that would be used when representing this number in scientific notation.
*/
public int getScientificExponent() {
return digitCount + exponent - 1;
}
/**
- * Tests {@code true} if this value is equal to zero. The sign field is ignored,
- * meaning that this method will return {@code true} for both {@code +0} and {@code -0}.
- * @return {@code true} if the value is equal to zero
+ * Tests {@code true} if this value is equal to zero. The sign field is ignored, meaning that this method will return {@code true} for both {@code +0} and
+ * {@code -0}.
+ *
+ * @return {@code true} if the value is equal to zero.
*/
boolean isZero() {
return digits[0] == 0;
}
/**
- * Ensures that this instance has at most the given number of significant digits
- * (i.e. precision). If this instance already has a precision less than or equal
- * to the argument, nothing is done. If the given precision requires a reduction in the number
- * of digits, then the value is rounded using {@link java.math.RoundingMode#HALF_EVEN half-even rounding}.
- * @param precision maximum number of significant digits to include
+ * Ensures that this instance has at most the given number of significant digits (i.e. precision). If this instance already has a precision less
+ * than or equal to the argument, nothing is done. If the given precision requires a reduction in the number of digits, then the value is rounded using
+ * {@link java.math.RoundingMode#HALF_EVEN half-even rounding}.
+ *
+ * @param precision maximum number of significant digits to include.
*/
public void maxPrecision(final int precision) {
if (precision > 0 && precision < digitCount) {
@@ -490,6 +501,7 @@ public void maxPrecision(final int precision) {
/**
* Gets the output buffer as a string.
+ *
* @return output buffer as a string
*/
private String outputString() {
@@ -500,7 +512,8 @@ private String outputString() {
/**
* Prepares the output buffer for a string of the given size.
- * @param size buffer size
+ *
+ * @param size buffer size.
*/
private void prepareOutput(final int size) {
outputChars = new char[size];
@@ -508,21 +521,20 @@ private void prepareOutput(final int size) {
}
/**
- * Returns {@code true} if a grouping separator should be added after the whole digit
- * character at the given position.
- * @param pos whole digit character position, with values starting at 1 and increasing
- * from right to left.
- * @return {@code true} if a grouping separator should be added
+ * Returns {@code true} if a grouping separator should be added after the whole digit character at the given position.
+ *
+ * @param pos whole digit character position, with values starting at 1 and increasing from right to left.
+ * @return {@code true} if a grouping separator should be added.
*/
private boolean requiresGroupingSeparatorAfterPosition(final int pos) {
return pos > 1 && pos % THOUSANDS_GROUP_SIZE == 1;
}
/**
- * Rounds the instance to the given decimal exponent position using
- * {@link java.math.RoundingMode#HALF_EVEN half-even rounding}. For example, a value of {@code -2}
- * will round the instance to the digit at the position 10-2 (i.e. to the closest multiple of 0.01).
- * @param roundExponent exponent defining the decimal place to round to
+ * Rounds the instance to the given decimal exponent position using {@link java.math.RoundingMode#HALF_EVEN half-even rounding}. For example, a value of
+ * {@code -2} will round the instance to the digit at the position 10-2 (i.e. to the closest multiple of 0.01).
+ *
+ * @param roundExponent exponent defining the decimal place to round to.
*/
public void round(final int roundExponent) {
if (roundExponent > exponent) {
@@ -543,8 +555,8 @@ public void round(final int roundExponent) {
/**
* Rounds the value up to the given number of digits.
- * @param count target number of digits; must be greater than zero and
- * less than the current number of digits
+ *
+ * @param count target number of digits; must be greater than zero and less than the current number of digits.
*/
private void roundUp(final int count) {
int removedDigits = digitCount - count;
@@ -572,10 +584,10 @@ private void roundUp(final int count) {
}
/**
- * Sets the value of this instance to a single digit with the given exponent.
- * The sign of the value is retained.
- * @param digit digit value
- * @param newExponent new exponent value
+ * Sets the value of this instance to a single digit with the given exponent. The sign of the value is retained.
+ *
+ * @param digit digit value.
+ * @param newExponent new exponent value.
*/
private void setSingleDigitValue(final int digit, final int newExponent) {
digits[0] = digit;
@@ -584,33 +596,31 @@ private void setSingleDigitValue(final int digit, final int newExponent) {
}
/**
- * Returns {@code true} if a formatted string with the given target exponent should include
- * the exponent field.
- * @param targetExponent exponent of the formatted result
- * @param opts format options
- * @return {@code true} if the formatted string should include the exponent field
+ * Returns {@code true} if a formatted string with the given target exponent should include the exponent field.
+ *
+ * @param targetExponent exponent of the formatted result.
+ * @param opts format options.
+ * @return {@code true} if the formatted string should include the exponent field.
*/
private boolean shouldIncludeExponent(final int targetExponent, final FormatOptions opts) {
return targetExponent != 0 || opts.isAlwaysIncludeExponent();
}
/**
- * Returns {@code true} if formatted strings should include the minus sign, considering
- * the value of this instance and the given format options.
- * @param opts format options
- * @return {@code true} if a minus sign should be included in the output
+ * Returns {@code true} if formatted strings should include the minus sign, considering the value of this instance and the given format options.
+ *
+ * @param opts format options.
+ * @return {@code true} if a minus sign should be included in the output.
*/
private boolean shouldIncludeMinus(final FormatOptions opts) {
return negative && (opts.isSignedZero() || !isZero());
}
/**
- * Returns {@code true} if a rounding operation for the given number of digits should
- * round up.
- * @param count number of digits to round to; must be greater than zero and less
- * than the current number of digits
- * @return {@code true} if a rounding operation for the given number of digits should
- * round up
+ * Returns {@code true} if a rounding operation for the given number of digits should round up.
+ *
+ * @param count number of digits to round to; must be greater than zero and less than the current number of digits.
+ * @return {@code true} if a rounding operation for the given number of digits should round up.
*/
private boolean shouldRoundUp(final int count) {
// Round up in the following cases:
@@ -639,8 +649,8 @@ private boolean shouldRoundUp(final int count) {
* 1e11 = "100.0E9"
*
*
- * @param opts format options
- * @return value in engineering format
+ * @param opts format options.
+ * @return value in engineering format.
*/
public String toEngineeringString(final FormatOptions opts) {
final int decimalPos = 1 + Math.floorMod(getScientificExponent(), ENG_EXPONENT_MOD);
@@ -659,8 +669,8 @@ public String toEngineeringString(final FormatOptions opts) {
* 1e11 = "100000000000.0"
*
*
- * @param opts format options
- * @return value in plain format
+ * @param opts format options.
+ * @return value in plain format.
*/
public String toPlainString(final FormatOptions opts) {
final int decimalPos = digitCount + exponent;
@@ -692,20 +702,19 @@ public String toPlainString(final FormatOptions opts) {
* 1e11 = "1.0E11"
*
*
- * @param opts format options
- * @return value in scientific format
+ * @param opts format options.
+ * @return value in scientific format.
*/
public String toScientificString(final FormatOptions opts) {
return toScientificString(1, opts);
}
/**
- * Returns a string representation of the value in scientific notation using the
- * given decimal point position.
- * @param decimalPos decimal position relative to the {@code digits} array; this value
- * is expected to be greater than 0
- * @param opts format options
- * @return value in scientific format
+ * Returns a string representation of the value in scientific notation using the given decimal point position.
+ *
+ * @param decimalPos decimal position relative to the {@code digits} array; this value is expected to be greater than 0.
+ * @param opts format options.
+ * @return value in scientific format.
*/
private String toScientificString(final int decimalPos, final FormatOptions opts) {
final int targetExponent = digitCount + exponent - decimalPos;
@@ -759,8 +768,8 @@ private String toScientificString(final int decimalPos, final FormatOptions opts
/**
* Truncates the value to the given number of digits.
- * @param count number of digits; must be greater than zero and less than
- * the current number of digits
+ *
+ * @param count number of digits; must be greater than zero and less than the current number of digits.
*/
private void truncate(final int count) {
// trim all trailing zero digits, making sure to leave
diff --git a/src/main/java/org/apache/commons/text/similarity/CosineDistance.java b/src/main/java/org/apache/commons/text/similarity/CosineDistance.java
index b4afc76efa..4d98ab4be8 100644
--- a/src/main/java/org/apache/commons/text/similarity/CosineDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/CosineDistance.java
@@ -44,11 +44,8 @@ public CosineDistance() {
@Override
public Double apply(final CharSequence left, final CharSequence right) {
- final CharSequence[] leftTokens = RegexTokenizer.INSTANCE.apply(left);
- final CharSequence[] rightTokens = RegexTokenizer.INSTANCE.apply(right);
-
- final Map leftVector = Counter.of(leftTokens);
- final Map rightVector = Counter.of(rightTokens);
+ final Map leftVector = Counter.of(RegexTokenizer.INSTANCE.apply(left));
+ final Map rightVector = Counter.of(RegexTokenizer.INSTANCE.apply(right));
final double similarity = CosineSimilarity.INSTANCE.cosineSimilarity(leftVector, rightVector);
return 1.0 - similarity;
}
diff --git a/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java b/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java
index d1adbf2508..2c5a123b72 100644
--- a/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java
+++ b/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java
@@ -34,7 +34,7 @@
public class CosineSimilarity {
/**
- * Singleton instance.
+ * The singleton instance.
*/
static final CosineSimilarity INSTANCE = new CosineSimilarity();
@@ -48,18 +48,15 @@ public CosineSimilarity() {
/**
* Calculates the cosine similarity for two given vectors.
*
- * @param leftVector left vector
- * @param rightVector right vector
- * @return cosine similarity between the two vectors
+ * @param leftVector left vector.
+ * @param rightVector right vector.
+ * @return cosine similarity between the two vectors.
*/
- public Double cosineSimilarity(final Map leftVector,
- final Map rightVector) {
+ public Double cosineSimilarity(final Map leftVector, final Map rightVector) {
if (leftVector == null || rightVector == null) {
throw new IllegalArgumentException("Vectors must not be null");
}
-
final Set intersection = getIntersection(leftVector, rightVector);
-
final double dotProduct = dot(leftVector, rightVector, intersection);
double d1 = 0.0d;
for (final Integer value : leftVector.values()) {
@@ -83,13 +80,12 @@ public Double cosineSimilarity(final Map leftVector,
* that if a vector is longer than other, then a smaller part of it will be used to compute
* the dot product.
*
- * @param leftVector left vector
- * @param rightVector right vector
- * @param intersection common elements
- * @return The dot product
+ * @param leftVector left vector.
+ * @param rightVector right vector.
+ * @param intersection common elements.
+ * @return The dot product.
*/
- private double dot(final Map leftVector, final Map rightVector,
- final Set intersection) {
+ private double dot(final Map leftVector, final Map rightVector, final Set intersection) {
long dotProduct = 0;
for (final CharSequence key : intersection) {
dotProduct += leftVector.get(key) * (long) rightVector.get(key);
@@ -100,15 +96,13 @@ private double dot(final Map leftVector, final Map getIntersection(final Map leftVector,
- final Map rightVector) {
+ private Set getIntersection(final Map leftVector, final Map rightVector) {
final Set intersection = new HashSet<>(leftVector.keySet());
intersection.retainAll(rightVector.keySet());
return intersection;
}
-
}
diff --git a/src/main/java/org/apache/commons/text/similarity/Counter.java b/src/main/java/org/apache/commons/text/similarity/Counter.java
index f38b206e2a..908bf9ed58 100644
--- a/src/main/java/org/apache/commons/text/similarity/Counter.java
+++ b/src/main/java/org/apache/commons/text/similarity/Counter.java
@@ -47,7 +47,7 @@ public static Map of(final CharSequence[] tokens) {
}
/**
- * Hidden constructor.
+ * No instance needed.
*/
private Counter() {
}
diff --git a/src/main/java/org/apache/commons/text/similarity/DamerauLevenshteinDistance.java b/src/main/java/org/apache/commons/text/similarity/DamerauLevenshteinDistance.java
new file mode 100644
index 0000000000..93f4627cc1
--- /dev/null
+++ b/src/main/java/org/apache/commons/text/similarity/DamerauLevenshteinDistance.java
@@ -0,0 +1,322 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text.similarity;
+
+/**
+ * An algorithm for measuring the difference between two character sequences using the
+ * Damerau-Levenshtein Distance.
+ *
+ *
+ * This is the number of changes needed to change one sequence into another, where each change is a single character
+ * modification (deletion, insertion, substitution, or transposition of two adjacent characters).
+ *
+ *
+ * @see Damerau-Levenshtein Distance on Wikipedia
+ * @since 1.15.0
+ */
+public class DamerauLevenshteinDistance implements EditDistance {
+
+ /**
+ * Utility function to ensure distance is valid according to threshold.
+ *
+ * @param distance The distance value.
+ * @param threshold The threshold value.
+ * @return The distance value, or {@code -1} if distance is greater than threshold.
+ */
+ private static int clampDistance(final int distance, final int threshold) {
+ return distance > threshold ? -1 : distance;
+ }
+
+ /**
+ * Finds the Damerau-Levenshtein distance between two CharSequences if it's less than or equal to a given threshold.
+ *
+ * @param left the first SimilarityInput, must not be null.
+ * @param right the second SimilarityInput, must not be null.
+ * @param threshold the target threshold, must not be negative.
+ * @return result distance, or -1 if distance exceeds threshold.
+ */
+ private static int limitedCompare(SimilarityInput left, SimilarityInput right, final int threshold) {
+ if (left == null || right == null) {
+ throw new IllegalArgumentException("Left/right inputs must not be null");
+ }
+
+ // Implementation based on https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
+
+ int leftLength = left.length();
+ int rightLength = right.length();
+
+ if (leftLength == 0) {
+ return clampDistance(rightLength, threshold);
+ }
+
+ if (rightLength == 0) {
+ return clampDistance(leftLength, threshold);
+ }
+
+ // Inspired by LevenshteinDistance impl; swap the input strings to consume less memory
+ if (rightLength > leftLength) {
+ final SimilarityInput tmp = left;
+ left = right;
+ right = tmp;
+ leftLength = rightLength;
+ rightLength = right.length();
+ }
+
+ // If the difference between the lengths of the strings is greater than the threshold, we must at least do
+ // threshold operations so we can return early
+ if (leftLength - rightLength > threshold) {
+ return -1;
+ }
+
+ // Use three arrays of minimum possible size to reduce memory usage. This avoids having to create a 2D
+ // array of size leftLength * rightLength
+ int[] curr = new int[rightLength + 1];
+ int[] prev = new int[rightLength + 1];
+ int[] prevPrev = new int[rightLength + 1];
+ int[] temp; // Temp variable use to shuffle arrays at the end of each iteration
+
+ int rightIndex, leftIndex, cost, minCost;
+
+ // Changing empty sequence to [0..i] requires i insertions
+ for (rightIndex = 0; rightIndex <= rightLength; rightIndex++) {
+ prev[rightIndex] = rightIndex;
+ }
+
+ // Calculate how many operations it takes to change right[0..rightIndex] into left[0..leftIndex]
+ // For each iteration
+ // - curr[i] contains the cost of changing right[0..i] into left[0..leftIndex]
+ // (computed in current iteration)
+ // - prev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 1]
+ // (computed in previous iteration)
+ // - prevPrev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 2]
+ // (computed in iteration before previous)
+ for (leftIndex = 1; leftIndex <= leftLength; leftIndex++) {
+ // For right[0..0] we must insert leftIndex characters, which means the cost is always leftIndex
+ curr[0] = leftIndex;
+
+ minCost = Integer.MAX_VALUE;
+
+ for (rightIndex = 1; rightIndex <= rightLength; rightIndex++) {
+ cost = left.at(leftIndex - 1) == right.at(rightIndex - 1) ? 0 : 1;
+
+ // Select cheapest operation
+ curr[rightIndex] = Math.min(
+ Math.min(
+ prev[rightIndex] + 1, // Delete current character
+ curr[rightIndex - 1] + 1 // Insert current character
+ ),
+ prev[rightIndex - 1] + cost // Replace (or no cost if same character)
+ );
+
+ // Check if adjacent characters are the same -> transpose if cheaper
+ if (leftIndex > 1
+ && rightIndex > 1
+ && left.at(leftIndex - 1) == right.at(rightIndex - 2)
+ && left.at(leftIndex - 2) == right.at(rightIndex - 1)) {
+ // Use cost here, to properly handle two subsequent equal letters
+ curr[rightIndex] = Math.min(curr[rightIndex], prevPrev[rightIndex - 2] + cost);
+ }
+
+ minCost = Math.min(curr[rightIndex], minCost);
+ }
+
+ // If there was no total cost for this entire iteration to transform right to left[0..leftIndex], there
+ // can not be a way to do it below threshold. This is because we have no way to reduce the overall cost
+ // in later operations.
+ if (minCost > threshold) {
+ return -1;
+ }
+
+ // Rotate arrays for next iteration
+ temp = prevPrev;
+ prevPrev = prev;
+ prev = curr;
+ curr = temp;
+ }
+
+ // Prev contains the value computed in the latest iteration
+ return clampDistance(prev[rightLength], threshold);
+ }
+
+ /**
+ * Finds the Damerau-Levenshtein distance between two inputs using optimal string alignment.
+ *
+ * @param left the first CharSequence, must not be null.
+ * @param right the second CharSequence, must not be null.
+ * @return result distance.
+ * @throws IllegalArgumentException if either CharSequence input is {@code null}.
+ */
+ private static int unlimitedCompare(SimilarityInput left, SimilarityInput right) {
+ if (left == null || right == null) {
+ throw new IllegalArgumentException("Left/right inputs must not be null");
+ }
+
+ /*
+ * Implementation based on https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
+ */
+
+ int leftLength = left.length();
+ int rightLength = right.length();
+
+ if (leftLength == 0) {
+ return rightLength;
+ }
+
+ if (rightLength == 0) {
+ return leftLength;
+ }
+
+ // Inspired by LevenshteinDistance impl; swap the input strings to consume less memory
+ if (rightLength > leftLength) {
+ final SimilarityInput tmp = left;
+ left = right;
+ right = tmp;
+ leftLength = rightLength;
+ rightLength = right.length();
+ }
+
+ // Use three arrays of minimum possible size to reduce memory usage. This avoids having to create a 2D
+ // array of size leftLength * rightLength
+ int[] curr = new int[rightLength + 1];
+ int[] prev = new int[rightLength + 1];
+ int[] prevPrev = new int[rightLength + 1];
+ int[] temp; // Temp variable use to shuffle arrays at the end of each iteration
+
+ int rightIndex, leftIndex, cost;
+
+ // Changing empty sequence to [0..i] requires i insertions
+ for (rightIndex = 0; rightIndex <= rightLength; rightIndex++) {
+ prev[rightIndex] = rightIndex;
+ }
+
+ // Calculate how many operations it takes to change right[0..rightIndex] into left[0..leftIndex]
+ // For each iteration
+ // - curr[i] contains the cost of changing right[0..i] into left[0..leftIndex]
+ // (computed in current iteration)
+ // - prev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 1]
+ // (computed in previous iteration)
+ // - prevPrev[i] contains the cost of changing right[0..i] into left[0..leftIndex - 2]
+ // (computed in iteration before previous)
+ for (leftIndex = 1; leftIndex <= leftLength; leftIndex++) {
+ // For right[0..0] we must insert leftIndex characters, which means the cost is always leftIndex
+ curr[0] = leftIndex;
+
+ for (rightIndex = 1; rightIndex <= rightLength; rightIndex++) {
+ cost = left.at(leftIndex - 1) == right.at(rightIndex - 1) ? 0 : 1;
+
+ // Select cheapest operation
+ curr[rightIndex] = Math.min(
+ Math.min(
+ prev[rightIndex] + 1, // Delete current character
+ curr[rightIndex - 1] + 1 // Insert current character
+ ),
+ prev[rightIndex - 1] + cost // Replace (or no cost if same character)
+ );
+
+ // Check if adjacent characters are the same -> transpose if cheaper
+ if (leftIndex > 1
+ && rightIndex > 1
+ && left.at(leftIndex - 1) == right.at(rightIndex - 2)
+ && left.at(leftIndex - 2) == right.at(rightIndex - 1)) {
+ // Use cost here, to properly handle two subsequent equal letters
+ curr[rightIndex] = Math.min(curr[rightIndex], prevPrev[rightIndex - 2] + cost);
+ }
+ }
+
+ // Rotate arrays for next iteration
+ temp = prevPrev;
+ prevPrev = prev;
+ prev = curr;
+ curr = temp;
+ }
+
+ // Prev contains the value computed in the latest iteration
+ return prev[rightLength];
+ }
+
+ /**
+ * Threshold.
+ */
+ private final Integer threshold;
+
+ /**
+ * Constructs a default instance that uses a version of the algorithm that does not use a threshold parameter.
+ */
+ public DamerauLevenshteinDistance() {
+ this(null);
+ }
+
+ /**
+ * Constructs a new instance. If the threshold is not null, distance calculations will be limited to a maximum length.
+ * If the threshold is null, the unlimited version of the algorithm will be used.
+ *
+ * @param threshold If this is null then distances calculations will not be limited. This may not be negative.
+ */
+ public DamerauLevenshteinDistance(final Integer threshold) {
+ if (threshold != null && threshold < 0) {
+ throw new IllegalArgumentException("Threshold must not be negative");
+ }
+ this.threshold = threshold;
+ }
+
+ /**
+ * Computes the Damerau-Levenshtein distance between two Strings.
+ *
+ *
+ * A higher score indicates a greater distance.
+ *
+ *
+ * @param left the first input, must not be null.
+ * @param right the second input, must not be null.
+ * @return result distance, or -1 if threshold is exceeded.
+ * @throws IllegalArgumentException if either String input {@code null}.
+ */
+ @Override
+ public Integer apply(final CharSequence left, final CharSequence right) {
+ return apply(SimilarityInput.input(left), SimilarityInput.input(right));
+ }
+
+ /**
+ * Computes the Damerau-Levenshtein distance between two inputs.
+ *
+ *
+ * A higher score indicates a greater distance.
+ *
+ *
+ * @param The type of similarity score unit.
+ * @param left the first input, must not be null.
+ * @param right the second input, must not be null.
+ * @return result distance, or -1 if threshold is exceeded.
+ * @throws IllegalArgumentException if either String input {@code null}.
+ * @since 1.13.0
+ */
+ public Integer apply(final SimilarityInput left, final SimilarityInput right) {
+ if (threshold != null) {
+ return limitedCompare(left, right, threshold);
+ }
+ return unlimitedCompare(left, right);
+ }
+
+ /**
+ * Gets the distance threshold.
+ *
+ * @return The distance threshold.
+ */
+ public Integer getThreshold() {
+ return threshold;
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/similarity/EditDistance.java b/src/main/java/org/apache/commons/text/similarity/EditDistance.java
index 2b81d8d9c2..77b735dbd2 100644
--- a/src/main/java/org/apache/commons/text/similarity/EditDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/EditDistance.java
@@ -27,10 +27,10 @@
* the set {@code S}:
*
*
- *
{@code d(x,y) >= 0}, non-negativity or separation axiom
- *
{@code d(x,y) == 0}, if and only if, {@code x == y}
- *
{@code d(x,y) == d(y,x)}, symmetry, and
- *
{@code d(x,z) <= d(x,y) + d(y,z)}, the triangle inequality
+ *
{@code d(x, y) >= 0}, non-negativity or separation axiom
+ *
{@code d(x, y) == 0}, if and only if, {@code x == y}
*
*
diff --git a/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java b/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java
index 008ea39c52..ef021dcdd0 100644
--- a/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java
+++ b/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java
@@ -80,8 +80,8 @@ public EditDistanceFrom(final EditDistance editDistance, final CharSequence l
* Compares "left" field against the "right" parameter
* using the "edit distance" implementation.
*
- * @param right the second CharSequence
- * @return The similarity score between two CharSequences
+ * @param right the second CharSequence.
+ * @return The similarity score between two CharSequences.
*/
public R apply(final CharSequence right) {
return editDistance.apply(left, right);
@@ -90,7 +90,7 @@ public R apply(final CharSequence right) {
/**
* Gets the edit distance.
*
- * @return The edit distance
+ * @return The edit distance.
*/
public EditDistance getEditDistance() {
return editDistance;
@@ -99,7 +99,7 @@ public EditDistance getEditDistance() {
/**
* Gets the left parameter.
*
- * @return The left parameter
+ * @return The left parameter.
*/
public CharSequence getLeft() {
return left;
diff --git a/src/main/java/org/apache/commons/text/similarity/FuzzyScore.java b/src/main/java/org/apache/commons/text/similarity/FuzzyScore.java
index 8355fdba38..e1b605da9a 100644
--- a/src/main/java/org/apache/commons/text/similarity/FuzzyScore.java
+++ b/src/main/java/org/apache/commons/text/similarity/FuzzyScore.java
@@ -41,12 +41,10 @@ public class FuzzyScore {
private final Locale locale;
/**
- * This returns a {@link Locale}-specific {@link FuzzyScore}.
+ * Constructs a new instance for a {@link Locale}-specific {@link FuzzyScore}.
*
- * @param locale The string matching logic is case insensitive.
- A {@link Locale} is necessary to normalize both Strings to lower case.
- * @throws IllegalArgumentException
- * This is thrown if the {@link Locale} parameter is {@code null}.
+ * @param locale The string matching logic is case insensitive. A {@link Locale} is necessary to normalize both Strings to lower case.
+ * @throws IllegalArgumentException This is thrown if the {@link Locale} parameter is {@code null}.
*/
public FuzzyScore(final Locale locale) {
if (locale == null) {
@@ -56,13 +54,12 @@ public FuzzyScore(final Locale locale) {
}
/**
- * Find the Fuzzy Score which indicates the similarity score between two
- * Strings.
+ * Computes the Fuzzy Score which indicates the similarity score between two Strings.
*
*
*
- * @param term a full term that should be matched against, must not be null
- * @param query the query that will be matched against a term, must not be
- * null
- * @return result score
- * @throws IllegalArgumentException if the term or query is {@code null}
+ * @param term a full term that should be matched against, must not be null.
+ * @param query the query that will be matched against a term, must not be null.
+ * @return result score.
+ * @throws IllegalArgumentException if the term or query is {@code null}.
*/
public Integer fuzzyScore(final CharSequence term, final CharSequence query) {
if (term == null || query == null) {
throw new IllegalArgumentException("CharSequences must not be null");
}
-
// fuzzy logic is case insensitive. We normalize the Strings to lower
// case right from the start. Turning characters to lower case
// via Character.toLowerCase(char) is unfortunately insufficient
// as it does not accept a locale.
final String termLowerCase = term.toString().toLowerCase(locale);
final String queryLowerCase = query.toString().toLowerCase(locale);
-
// the resulting score
int score = 0;
-
// the position in the term which will be scanned next for potential
// query character matches
int termIndex = 0;
-
// index of the previously matched character in the term
int previousMatchingCharacterIndex = Integer.MIN_VALUE;
-
for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) {
final char queryChar = queryLowerCase.charAt(queryIndex);
-
boolean termCharacterMatchFound = false;
- for (; termIndex < termLowerCase.length()
- && !termCharacterMatchFound; termIndex++) {
+ for (; termIndex < termLowerCase.length() && !termCharacterMatchFound; termIndex++) {
final char termChar = termLowerCase.charAt(termIndex);
-
if (queryChar == termChar) {
// simple character matches result in one point
score++;
-
// subsequent character matches further improve
// the score.
if (previousMatchingCharacterIndex + 1 == termIndex) {
score += 2;
}
-
previousMatchingCharacterIndex = termIndex;
-
// we can leave the nested loop. Every character in the
// query can match at most one character in the term.
termCharacterMatchFound = true;
}
}
}
-
return score;
}
diff --git a/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java b/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java
index 155a772fd3..b55adb3921 100644
--- a/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java
+++ b/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java
@@ -49,11 +49,10 @@ public class IntersectionResult {
/**
* Constructs the results for an intersection between two sets.
*
- * @param sizeA the size of set A ({@code |A|})
- * @param sizeB the size of set B ({@code |B|})
- * @param intersection the size of the intersection of A and B ({@code |A ∩ B|})
- * @throws IllegalArgumentException if the sizes are negative or the intersection is greater
- * than the minimum of the two set sizes
+ * @param sizeA the size of set A ({@code |A|}).
+ * @param sizeB the size of set B ({@code |B|}).
+ * @param intersection the size of the intersection of A and B ({@code |A ∩ B|}).
+ * @throws IllegalArgumentException if the sizes are negative or the intersection is greater than the minimum of the two set sizes.
*/
public IntersectionResult(final int sizeA, final int sizeB, final int intersection) {
if (sizeA < 0) {
@@ -94,7 +93,7 @@ public int getIntersection() {
/**
* Gets the size of set A.
*
- * @return |A|
+ * @return {@code |A|}
*/
public int getSizeA() {
return sizeA;
@@ -103,7 +102,7 @@ public int getSizeA() {
/**
* Gets the size of set B.
*
- * @return |B|
+ * @return {@code |B|}
*/
public int getSizeB() {
return sizeB;
diff --git a/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java b/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java
index 71a31a0094..370b00a296 100644
--- a/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java
+++ b/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java
@@ -82,7 +82,7 @@ private TinyBag(final int initialCapacity) {
/**
* Adds a new element to the bag, incrementing its count in the underlying map.
*
- * @param object the object to add
+ * @param object the object to add.
*/
private void add(final T object) {
map.computeIfAbsent(object, k -> new BagCount()).count++;
@@ -91,7 +91,7 @@ private void add(final T object) {
/**
* Returns a Set view of the mappings contained in this bag.
*
- * @return The Set view
+ * @return The Set view.
*/
private Set> entrySet() {
return map.entrySet();
@@ -101,8 +101,8 @@ private Set> entrySet() {
* Returns the number of occurrence of the given element in this bag by
* looking up its count in the underlying map.
*
- * @param object the object to search for
- * @return The number of occurrences of the object, zero if not found
+ * @param object the object to search for.
+ * @return The number of occurrences of the object, zero if not found.
*/
private int getCount(final Object object) {
return map.getOrDefault(object, BagCount.ZERO).count;
@@ -111,7 +111,7 @@ private int getCount(final Object object) {
/**
* Gets the number of unique elements in the bag.
*
- * @return The unique element size
+ * @return The unique element size.
*/
private int uniqueElementSize() {
return map.size();
@@ -122,10 +122,10 @@ private int uniqueElementSize() {
* Computes the intersection between two sets. This is the count of all the elements
* that are within both sets.
*
- * @param the type of the elements in the set
- * @param setA the set A
- * @param setB the set B
- * @return The intersection
+ * @param the type of the elements in the set.
+ * @param setA the set A.
+ * @param setB the set B.
+ * @return The intersection of A and B.
*/
private static int getIntersection(final Set setA, final Set setB) {
int intersection = 0;
@@ -149,8 +149,8 @@ private static int getIntersection(final Set setA, final Set setB) {
* that will include duplicates in the intersect and union.
*
*
- * @param converter the converter used to create the elements from the characters
- * @throws IllegalArgumentException if the converter is null
+ * @param converter the converter used to create the elements from the characters.
+ * @throws IllegalArgumentException if the converter is null.
*/
public IntersectionSimilarity(final Function> converter) {
if (converter == null) {
@@ -162,10 +162,10 @@ public IntersectionSimilarity(final Function> conver
/**
* Calculates the intersection of two character sequences passed as input.
*
- * @param left first character sequence
- * @param right second character sequence
- * @return The intersection result
- * @throws IllegalArgumentException if either input sequence is {@code null}
+ * @param left first character sequence.
+ * @param right second character sequence.
+ * @return The intersection result.
+ * @throws IllegalArgumentException if either input sequence is {@code null}.
*/
@Override
public IntersectionResult apply(final CharSequence left, final CharSequence right) {
@@ -210,9 +210,9 @@ public IntersectionResult apply(final CharSequence left, final CharSequence righ
* Computes the intersection between two bags. This is the sum of the minimum
* count of each element that is within both sets.
*
- * @param bagA the bag A
- * @param bagB the bag B
- * @return The intersection
+ * @param bagA the bag A.
+ * @param bagB the bag B.
+ * @return The intersection of A and B.
*/
private int getIntersection(final TinyBag bagA, final TinyBag bagB) {
int intersection = 0;
@@ -229,8 +229,8 @@ private int getIntersection(final TinyBag bagA, final TinyBag bagB) {
* Converts the collection to a bag. The bag will contain the count of each element
* in the collection.
*
- * @param objects the objects
- * @return The bag
+ * @param objects the objects.
+ * @return The bag.
*/
private TinyBag toBag(final Collection objects) {
final TinyBag bag = new TinyBag(objects.size());
diff --git a/src/main/java/org/apache/commons/text/similarity/JaccardDistance.java b/src/main/java/org/apache/commons/text/similarity/JaccardDistance.java
index 51c64f4e65..d2042e0659 100644
--- a/src/main/java/org/apache/commons/text/similarity/JaccardDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/JaccardDistance.java
@@ -40,7 +40,7 @@ public JaccardDistance() {
*
* @param left first input sequence.
* @param right second input sequence.
- * @return index
+ * @return The Jaccard distance.
* @throws IllegalArgumentException if either String input {@code null}.
*/
@Override
@@ -54,7 +54,7 @@ public Double apply(final CharSequence left, final CharSequence right) {
* @param The type of similarity score unit.
* @param left first input sequence.
* @param right second input sequence.
- * @return index
+ * @return index.
* @throws IllegalArgumentException if either String input {@code null}.
*/
public Double apply(final SimilarityInput left, final SimilarityInput right) {
diff --git a/src/main/java/org/apache/commons/text/similarity/JaccardSimilarity.java b/src/main/java/org/apache/commons/text/similarity/JaccardSimilarity.java
index 2630728a78..61e2b84319 100644
--- a/src/main/java/org/apache/commons/text/similarity/JaccardSimilarity.java
+++ b/src/main/java/org/apache/commons/text/similarity/JaccardSimilarity.java
@@ -32,7 +32,7 @@
public class JaccardSimilarity implements SimilarityScore {
/**
- * Singleton instance.
+ * The singleton instance.
*/
static final JaccardSimilarity INSTANCE = new JaccardSimilarity();
@@ -48,7 +48,7 @@ public JaccardSimilarity() {
*
* @param left first input sequence.
* @param right second input sequence.
- * @return index.
+ * @return The Jaccard Similarity of two set character sequence passed as input.
* @throws IllegalArgumentException if either String input {@code null}.
*/
@Override
@@ -63,7 +63,7 @@ public Double apply(final CharSequence left, final CharSequence right) {
* @param The type of similarity score unit.
* @param left first input sequence.
* @param right second input sequence.
- * @return index.
+ * @return The Jaccard Similarity of two set character sequence passed as input.
* @since 1.13.0
*/
public Double apply(final SimilarityInput left, final SimilarityInput right) {
diff --git a/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java b/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java
index f15549878f..e2e3d0df3f 100644
--- a/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java
@@ -33,11 +33,11 @@ public class JaroWinklerDistance implements EditDistance {
/**
* Computes the Jaro-Winkler string matches, half transpositions, prefix array.
*
- * @param first the first string to be matched.
+ * @param first the first string to be matched.
* @param second the second string to be matched.
* @return array containing: matches, half transpositions, and prefix
- * @deprecated Deprecated as of 1.7. This method will be removed in 2.0, and moved to a Jaro Winkler similarity
- * class. TODO see TEXT-104.
+ * @deprecated Deprecated as of 1.7, use {@link JaroWinklerSimilarity#matches(CharSequence, CharSequence)}. This method will be removed in 2.0. TODO see
+ * TEXT-104.
*/
@Deprecated
protected static int[] matches(final CharSequence first, final CharSequence second) {
@@ -55,9 +55,9 @@ public JaroWinklerDistance() {
* Computes the Jaro Winkler Distance between two character sequences.
*
*
- * distance.apply(null, null) = IllegalArgumentException
- * distance.apply("foo", null) = IllegalArgumentException
- * distance.apply(null, "foo") = IllegalArgumentException
+ * distance.apply(null, null) = Throws {@link IllegalArgumentException}
+ * distance.apply("foo", null) = Throws {@link IllegalArgumentException}
+ * distance.apply(null, "foo") = Throws {@link IllegalArgumentException}
* distance.apply("", "") = 0.0
* distance.apply("foo", "foo") = 0.0
* distance.apply("foo", "foo ") = 0.06
@@ -81,7 +81,7 @@ public JaroWinklerDistance() {
* @param left the first input, must not be null.
* @param right the second input, must not be null.
* @return result distance.
- * @throws IllegalArgumentException if either CharSequence input is {@code null}
+ * @throws IllegalArgumentException if either CharSequence input is {@code null}.
*/
@Override
public Double apply(final CharSequence left, final CharSequence right) {
@@ -92,9 +92,9 @@ public Double apply(final CharSequence left, final CharSequence right) {
* Computes the Jaro Winkler Distance between two character sequences.
*
*
- * distance.apply(null, null) = IllegalArgumentException
- * distance.apply("foo", null) = IllegalArgumentException
- * distance.apply(null, "foo") = IllegalArgumentException
+ * distance.apply(null, null) = Throws {@link IllegalArgumentException}
+ * distance.apply("foo", null) = Throws {@link IllegalArgumentException}
+ * distance.apply(null, "foo") = Throws {@link IllegalArgumentException}
* distance.apply("", "") = 0.0
* distance.apply("foo", "foo") = 0.0
* distance.apply("foo", "foo ") = 0.06
diff --git a/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java b/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java
index c803bd5a47..5e67595875 100644
--- a/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java
+++ b/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java
@@ -39,7 +39,7 @@
public class JaroWinklerSimilarity implements SimilarityScore {
/**
- * Singleton instance.
+ * The singleton instance.
*/
static final JaroWinklerSimilarity INSTANCE = new JaroWinklerSimilarity();
@@ -130,9 +130,9 @@ public JaroWinklerSimilarity() {
* Computes the Jaro Winkler Similarity between two character sequences.
*
*
- * sim.apply(null, null) = IllegalArgumentException
- * sim.apply("foo", null) = IllegalArgumentException
- * sim.apply(null, "foo") = IllegalArgumentException
+ * sim.apply(null, null) = Throws {@link IllegalArgumentException}
+ * sim.apply("foo", null) = Throws {@link IllegalArgumentException}
+ * sim.apply(null, "foo") = Throws {@link IllegalArgumentException}
* sim.apply("", "") = 1.0
* sim.apply("foo", "foo") = 1.0
* sim.apply("foo", "foo ") = 0.94
diff --git a/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java b/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java
index 0e241efd5f..8ea040098d 100644
--- a/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.commons.text.similarity;
import java.util.Arrays;
@@ -22,9 +23,8 @@
* An algorithm for measuring the difference between two character sequences.
*
*
- * This is the number of changes needed to change one sequence into another,
- * where each change is a single character modification (deletion, insertion
- * or substitution).
+ * This is the number of changes needed to change one sequence into another, where each change is a single character modification (deletion, insertion or
+ * substitution).
*
*
* @since 1.0
@@ -32,44 +32,34 @@
public class LevenshteinDetailedDistance implements EditDistance {
/**
- * Singleton instance.
+ * The singleton instance.
*/
private static final LevenshteinDetailedDistance INSTANCE = new LevenshteinDetailedDistance();
/**
- * Finds count for each of the three [insert, delete, substitute] operations
- * needed. This is based on the matrix formed based on the two character
- * sequence.
+ * Finds count for each of the three [insert, delete, substitute] operations needed. This is based on the matrix formed based on the two character sequence.
*
- * @param The type of similarity score unit.
- * @param left character sequence which need to be converted from
- * @param right character sequence which need to be converted to
- * @param matrix two dimensional array containing
- * @param swapped tells whether the value for left character sequence and right
- * character sequence were swapped to save memory
- * @return result object containing the count of insert, delete and substitute and total count needed
+ * @param The type of similarity score unit.
+ * @param left character sequence which need to be converted from.
+ * @param right character sequence which need to be converted to.
+ * @param matrix two dimensional array containing.
+ * @param swapped tells whether the value for left character sequence and right character sequence were swapped to save memory.
+ * @return result object containing the count of insert, delete and substitute and total count needed.
*/
- private static LevenshteinResults findDetailedResults(final SimilarityInput left,
- final SimilarityInput right,
- final int[][] matrix,
- final boolean swapped) {
-
+ private static LevenshteinResults findDetailedResults(final SimilarityInput left, final SimilarityInput right, final int[][] matrix,
+ final boolean swapped) {
int delCount = 0;
int addCount = 0;
int subCount = 0;
-
int rowIndex = right.length();
int columnIndex = left.length();
-
int dataAtLeft = 0;
int dataAtTop = 0;
int dataAtDiagonal = 0;
int data = 0;
boolean deleted = false;
boolean added = false;
-
while (rowIndex >= 0 && columnIndex >= 0) {
-
if (columnIndex == 0) {
dataAtLeft = -1;
} else {
@@ -89,7 +79,6 @@ private static LevenshteinResults findDetailedResults(final SimilarityInput<
break;
}
data = matrix[rowIndex][columnIndex];
-
// case in which the character at left and right are the same,
// in this case none of the counters will be incremented.
if (columnIndex > 0 && rowIndex > 0 && left.at(columnIndex - 1).equals(right.at(rowIndex - 1))) {
@@ -97,12 +86,10 @@ private static LevenshteinResults findDetailedResults(final SimilarityInput<
rowIndex--;
continue;
}
-
// handling insert and delete cases.
deleted = false;
added = false;
- if (data - 1 == dataAtLeft && data <= dataAtDiagonal && data <= dataAtTop
- || dataAtDiagonal == -1 && dataAtTop == -1) { // NOPMD
+ if (data - 1 == dataAtLeft && data <= dataAtDiagonal && data <= dataAtTop || dataAtDiagonal == -1 && dataAtTop == -1) { // NOPMD
columnIndex--;
if (swapped) {
addCount++;
@@ -111,8 +98,7 @@ private static LevenshteinResults findDetailedResults(final SimilarityInput<
delCount++;
deleted = true;
}
- } else if (data - 1 == dataAtTop && data <= dataAtDiagonal && data <= dataAtLeft
- || dataAtDiagonal == -1 && dataAtLeft == -1) { // NOPMD
+ } else if (data - 1 == dataAtTop && data <= dataAtDiagonal && data <= dataAtLeft || dataAtDiagonal == -1 && dataAtLeft == -1) { // NOPMD
rowIndex--;
if (swapped) {
delCount++;
@@ -122,7 +108,6 @@ private static LevenshteinResults findDetailedResults(final SimilarityInput<
added = true;
}
}
-
// substituted case
if (!added && !deleted) {
subCount++;
@@ -143,21 +128,17 @@ public static LevenshteinDetailedDistance getDefaultInstance() {
}
/**
- * Finds the Levenshtein distance between two CharSequences if it's less than or
- * equal to a given threshold.
+ * Finds the Levenshtein distance between two CharSequences if it's less than or equal to a given threshold.
*
*
- * This implementation follows from Algorithms on Strings, Trees and
- * Sequences by Dan Gusfield and Chas Emerick's implementation of the
- * Levenshtein distance algorithm from http://www.merriampark.com/ld.htm
+ * This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield and Chas Emerick's implementation of the Levenshtein distance
+ * algorithm.
*
*
- * @param The type of similarity score unit.
- * @param left the first CharSequence, must not be null
- * @param right the second CharSequence, must not be null
- * @param threshold the target threshold, must not be negative
- * @return result distance, or -1
+ * @param The type of similarity score unit.
+ * @param left the first CharSequence, must not be null.
+ * @param right the second CharSequence, must not be null.
+ * @param threshold the target threshold, must not be negative.
+ * @return result distance, or -1.
*/
- private static LevenshteinResults limitedCompare(SimilarityInput left, SimilarityInput right, final int threshold) { //NOPMD
+ private static LevenshteinResults limitedCompare(SimilarityInput left, SimilarityInput right, final int threshold) { // NOPMD
if (left == null || right == null) {
throw new IllegalArgumentException("CharSequences must not be null");
}
- if (threshold < 0) {
- throw new IllegalArgumentException("Threshold must not be negative");
- }
/*
- * This implementation only computes the distance if it's less than or
- * equal to the threshold value, returning -1 if it's greater. The
- * advantage is performance: unbounded distance is O(nm), but a bound of
- * k allows us to reduce it to O(km) time by only computing a diagonal
- * stripe of width 2k + 1 of the cost table. It is also possible to use
- * this to compute the unbounded Levenshtein distance by starting the
- * threshold at 1 and doubling each time until the distance is found;
- * this is O(dm), where d is the distance.
+ * This implementation only computes the distance if it's less than or equal to the threshold value, returning -1 if it's greater. The advantage is
+ * performance: unbounded distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only computing a diagonal stripe of width 2k + 1
+ * of the cost table. It is also possible to use this to compute the unbounded Levenshtein distance by starting the threshold at 1 and doubling each
+ * time until the distance is found; this is O(dm), where d is the distance.
*
- * One subtlety comes from needing to ignore entries on the border of
- * our stripe eg. p[] = |#|#|#|* d[] = *|#|#|#| We must ignore the entry
- * to the left of the leftmost member We must ignore the entry above the
- * rightmost member
+ * One subtlety comes from needing to ignore entries on the border of our stripe, for example,
+ * p[] = |#|#|#|* d[] = *|#|#|#| We must ignore the entry to the left
+ * of the leftmost member We must ignore the entry above the rightmost member
*
- * Another subtlety comes from our stripe running off the matrix if the
- * strings aren't of the same size. Since string s is always swapped to
- * be the shorter of the two, the stripe will always run off to the
- * upper right instead of the lower left of the matrix.
+ * Another subtlety comes from our stripe running off the matrix if the strings aren't of the same size. Since string s is always swapped to be the
+ * shorter of the two, the stripe will always run off to the upper right instead of the lower left of the matrix.
*
- * As a concrete example, suppose s is of length 5, t is of length 7,
- * and our threshold is 1. In this case we're going to walk a stripe of
- * length 3. The matrix would look like so:
+ * As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1. In this case we're going to walk a stripe of length 3. The
+ * matrix would look like so:
*
- *
*
- * Note how the stripe leads off the table as there is no possible way
- * to turn a string of length 5 into one of length 7 in edit distance of
- * 1.
+ * Note how the stripe leads off the table as there is no possible way to turn a string of length 5 into one of length 7 in edit distance of 1.
*
- * Additionally, this implementation decreases memory usage by using two
- * single-dimensional arrays and swapping them back and forth instead of
- * allocating an entire n by m matrix. This requires a few minor
- * changes, such as immediately returning when it's detected that the
- * stripe has run off the matrix and initially filling the arrays with
- * large values so that entries we don't compute are ignored.
+ * Additionally, this implementation decreases memory usage by using two single-dimensional arrays and swapping them back and forth instead of
+ * allocating an entire n by m matrix. This requires a few minor changes, such as immediately returning when it's detected that the stripe has run off
+ * the matrix and initially filling the arrays with large values so that entries we don't compute are ignored.
*
- * See Algorithms on Strings, Trees and Sequences by Dan Gusfield for
- * some discussion.
+ * See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion.
*/
-
int n = left.length(); // length of left
int m = right.length(); // length of right
-
// if one string is empty, the edit distance is necessarily the length of the other
if (n == 0) {
return m <= threshold ? new LevenshteinResults(m, m, 0, 0) : new LevenshteinResults(-1, 0, 0, 0);
@@ -242,7 +195,6 @@ private static LevenshteinResults limitedCompare(SimilarityInput left, Si
if (m == 0) {
return n <= threshold ? new LevenshteinResults(n, 0, n, 0) : new LevenshteinResults(-1, 0, 0, 0);
}
-
boolean swapped = false;
if (n > m) {
// swap the two strings to consume less memory
@@ -253,20 +205,17 @@ private static LevenshteinResults limitedCompare(SimilarityInput left, Si
m = right.length();
swapped = true;
}
-
int[] p = new int[n + 1]; // 'previous' cost array, horizontally
int[] d = new int[n + 1]; // cost array, horizontally
int[] tempD; // placeholder to assist in swapping p and d
final int[][] matrix = new int[m + 1][n + 1];
-
- //filling the first row and first column values in the matrix
+ // filling the first row and first column values in the matrix
for (int index = 0; index <= n; index++) {
matrix[0][index] = index;
}
for (int index = 0; index <= m; index++) {
matrix[index][0] = index;
}
-
// fill in starting table values
final int boundary = Math.min(n, threshold) + 1;
for (int i = 0; i < boundary; i++) {
@@ -276,27 +225,21 @@ private static LevenshteinResults limitedCompare(SimilarityInput left, Si
// stripe will be ignored in following loop iterations
Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
Arrays.fill(d, Integer.MAX_VALUE);
-
// iterates through t
for (int j = 1; j <= m; j++) {
final E rightJ = right.at(j - 1); // jth character of right
d[0] = j;
-
// compute stripe indices, constrain to array size
final int min = Math.max(1, j - threshold);
- final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(
- n, j + threshold);
-
+ final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold);
// the stripe may lead off of the table if s and t are of different sizes
if (min > max) {
return new LevenshteinResults(-1, 0, 0, 0);
}
-
// ignore entry left of leftmost
if (min > 1) {
d[min - 1] = Integer.MAX_VALUE;
}
-
// iterates through [min, max] in s
for (int i = min; i <= max; i++) {
if (left.at(i - 1).equals(rightJ)) {
@@ -308,13 +251,11 @@ private static LevenshteinResults limitedCompare(SimilarityInput left, Si
}
matrix[j][i] = d[i];
}
-
// copy current distance counts to 'previous row' distance counts
tempD = p;
p = d;
d = tempD;
}
-
// if p[n] is greater than the threshold, there's no guarantee on it being the correct distance
if (p[n] <= threshold) {
return findDetailedResults(left, right, matrix, swapped);
@@ -325,19 +266,18 @@ private static LevenshteinResults limitedCompare(SimilarityInput left, Si
/**
* Finds the Levenshtein distance between two Strings.
*
- *
+ * A higher score indicates a greater distance.
+ *
*
- *
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
- * which can occur when my Java implementation is used with very large strings.
- * This implementation of the Levenshtein distance algorithm
- * is from http://www.merriampark.com/ldjava.htm
+ *
+ * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
+ * strings.
+ *
*
- * @param The type of similarity score unit.
- * @param left the first CharSequence, must not be null
- * @param right the second CharSequence, must not be null
- * @return result distance, or -1
- * @throws IllegalArgumentException if either CharSequence input is {@code null}
+ * @param The type of similarity score unit.
+ * @param left the first CharSequence, must not be null.
+ * @param right the second CharSequence, must not be null.
+ * @return result distance, or -1.
+ * @throws IllegalArgumentException if either CharSequence input is {@code null}.
*/
private static LevenshteinResults unlimitedCompare(SimilarityInput left, SimilarityInput right) {
if (left == null || right == null) {
throw new IllegalArgumentException("CharSequences must not be null");
}
-
/*
- The difference between this impl. and the previous is that, rather
- than creating and retaining a matrix of size s.length() + 1 by t.length() + 1,
- we maintain two single-dimensional arrays of length s.length() + 1. The first, d,
- is the 'current working' distance array that maintains the newest distance cost
- counts as we iterate through the characters of String s. Each time we increment
- the index of String t we are comparing, d is copied to p, the second int[]. Doing so
- allows us to retain the previous cost counts as required by the algorithm (taking
- the minimum of the cost count to the left, up one, and diagonally up and to the left
- of the current cost count being calculated). (Note that the arrays aren't really
- copied anymore, just switched...this is clearly much better than cloning an array
- or doing a System.arraycopy() each time through the outer loop.)
-
- Effectively, the difference between the two implementations is this one does not
- cause an out of memory condition when calculating the LD over two very large strings.
+ * The difference between this impl. and the previous is that, rather than creating and retaining a matrix of size s.length() + 1 by t.length() + 1, we
+ * maintain two single-dimensional arrays of length s.length() + 1. The first, d, is the 'current working' distance array that maintains the newest
+ * distance cost counts as we iterate through the characters of String s. Each time we increment the index of String t we are comparing, d is copied to
+ * p, the second int[]. Doing so allows us to retain the previous cost counts as required by the algorithm (taking the minimum of the cost count to the
+ * left, up one, and diagonally up and to the left of the current cost count being calculated). (Note that the arrays aren't really copied anymore, just
+ * switched...this is clearly much better than cloning an array or doing a System.arraycopy() each time through the outer loop.)
+ *
+ * Effectively, the difference between the two implementations is this one does not cause an out of memory condition when calculating the LD over two
+ * very large strings.
*/
-
int n = left.length(); // length of left
int m = right.length(); // length of right
-
if (n == 0) {
return new LevenshteinResults(m, m, 0, 0);
}
@@ -396,12 +328,10 @@ allows us to retain the previous cost counts as required by the algorithm (takin
m = right.length();
swapped = true;
}
-
int[] p = new int[n + 1]; // 'previous' cost array, horizontally
int[] d = new int[n + 1]; // cost array, horizontally
- int[] tempD; //placeholder to assist in swapping p and d
+ int[] tempD; // placeholder to assist in swapping p and d
final int[][] matrix = new int[m + 1][n + 1];
-
// filling the first row and first column values in the matrix
for (int index = 0; index <= n; index++) {
matrix[0][index] = index;
@@ -409,30 +339,24 @@ allows us to retain the previous cost counts as required by the algorithm (takin
for (int index = 0; index <= m; index++) {
matrix[index][0] = index;
}
-
// indexes into strings left and right
int i; // iterates through left
int j; // iterates through right
-
E rightJ; // jth character of right
-
int cost; // cost
for (i = 0; i <= n; i++) {
p[i] = i;
}
-
for (j = 1; j <= m; j++) {
rightJ = right.at(j - 1);
d[0] = j;
-
for (i = 1; i <= n; i++) {
cost = left.at(i - 1).equals(rightJ) ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
- //filling the matrix
+ // filling the matrix
matrix[j][i] = d[i];
}
-
// copy current distance counts to 'previous row' distance counts
tempD = p;
p = d;
@@ -447,10 +371,7 @@ allows us to retain the previous cost counts as required by the algorithm (takin
private final Integer threshold;
/**
- *
- * This returns the default instance that uses a version
- * of the algorithm that does not use a threshold parameter.
- *
+ * Constructs a new instance that uses a version of the algorithm that does not use a threshold parameter.
*
* @see LevenshteinDetailedDistance#getDefaultInstance()
* @deprecated Use {@link #getDefaultInstance()}.
@@ -461,9 +382,13 @@ public LevenshteinDetailedDistance() {
}
/**
+ * Constructs a new instance for a threshold.
+ *
* If the threshold is not null, distance calculations will be limited to a maximum length.
- *
- *
If the threshold is null, the unlimited version of the algorithm will be used.
+ *
+ *
+ * If the threshold is null, the unlimited version of the algorithm will be used.
+ *
*
* @param threshold If this is null then distances calculations will not be limited. This may not be negative.
*/
@@ -477,19 +402,18 @@ public LevenshteinDetailedDistance(final Integer threshold) {
/**
* Computes the Levenshtein distance between two Strings.
*
- *
+ * A higher score indicates a greater distance.
+ *
*
- *
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
- * which can occur when my Java implementation is used with very large strings.
- * This implementation of the Levenshtein distance algorithm
- * is from http://www.merriampark.com/ldjava.htm
+ *
+ * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
+ * strings.
+ *
*
- * @param left the first input, must not be null
- * @param right the second input, must not be null
- * @return result distance, or -1
- * @throws IllegalArgumentException if either String input {@code null}
+ * @param left the first input, must not be null.
+ * @param right the second input, must not be null.
+ * @return result distance, or -1.
+ * @throws IllegalArgumentException if either String input {@code null}.
*/
@Override
public LevenshteinResults apply(final CharSequence left, final CharSequence right) {
@@ -514,19 +438,18 @@ public LevenshteinResults apply(final CharSequence left, final CharSequence righ
/**
* Computes the Levenshtein distance between two Strings.
*
- *
+ * A higher score indicates a greater distance.
+ *
*
- *
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
- * which can occur when my Java implementation is used with very large strings.
- * This implementation of the Levenshtein distance algorithm
- * is from http://www.merriampark.com/ldjava.htm
+ *
+ * Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
+ * strings.
+ *
*
- * @param The type of similarity score unit.
- * @param left the first input, must not be null
- * @param right the second input, must not be null
- * @return result distance, or -1
- * @throws IllegalArgumentException if either String input {@code null}
+ * @param The type of similarity score unit.
+ * @param left the first input, must not be null.
+ * @param right the second input, must not be null.
+ * @return result distance, or -1.
+ * @throws IllegalArgumentException if either String input {@code null}.
* @since 1.13.0
*/
public LevenshteinResults apply(final SimilarityInput left, final SimilarityInput right) {
@@ -555,7 +478,7 @@ public LevenshteinResults apply(final SimilarityInput left, final Similar
/**
* Gets the distance threshold.
*
- * @return The distance threshold
+ * @return The distance threshold.
*/
public Integer getThreshold() {
return threshold;
diff --git a/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java b/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java
index cbfbe6d099..479b3fadea 100644
--- a/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java
@@ -19,7 +19,8 @@
import java.util.Arrays;
/**
- * An algorithm for measuring the difference between two character sequences.
+ * An algorithm for measuring the difference between two character sequences using the Levenshtein
+ * Distance.
*
*
* This is the number of changes needed to change one sequence into another, where each change is a single character modification (deletion, insertion or
@@ -30,35 +31,37 @@
*
*
* @since 1.0
+ * @see Levenshtein Distance on Wikipedia
+ * @see Levenshtein Distance on NIST
*/
public class LevenshteinDistance implements EditDistance {
/**
- * Singleton instance.
+ * The singleton instance.
*/
private static final LevenshteinDistance INSTANCE = new LevenshteinDistance();
/**
* Gets the default instance.
*
- * @return The default instance
+ * @return The default instance.
*/
public static LevenshteinDistance getDefaultInstance() {
return INSTANCE;
}
/**
- * Find the Levenshtein distance between two CharSequences if it's less than or equal to a given threshold.
+ * Finds the Levenshtein distance between two CharSequences if it's less than or equal to a given threshold.
*
*
* This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield and Chas Emerick's implementation of the Levenshtein distance
- * algorithm from http://www.merriampark.com/ld.htm
+ * algorithm.
*
*
- * @param left the first SimilarityInput, must not be null
- * @param right the second SimilarityInput, must not be null
- * @param threshold the target threshold, must not be negative
+ * @param left the first SimilarityInput, must not be null.
+ * @param right the second SimilarityInput, must not be null.
+ * @param threshold the target threshold, must not be negative.
* @return result distance, or -1
*/
private static int limitedCompare(SimilarityInput left, SimilarityInput right, final int threshold) { // NOPMD
if (left == null || right == null) {
throw new IllegalArgumentException("CharSequences must not be null");
}
- if (threshold < 0) {
- throw new IllegalArgumentException("Threshold must not be negative");
- }
/*
* This implementation only computes the distance if it's less than or equal to the threshold value, returning -1 if it's greater. The advantage is
@@ -88,7 +88,8 @@ private static int limitedCompare(SimilarityInput left, SimilarityInput int limitedCompare(SimilarityInput left, SimilarityInput
*
*
*
- * @param left the first CharSequence, must not be null
- * @param right the second CharSequence, must not be null
- * @return result distance, or -1
- * @throws IllegalArgumentException if either CharSequence input is {@code null}
+ * @param left the first CharSequence, must not be null.
+ * @param right the second CharSequence, must not be null.
+ * @return result distance, or -1.
+ * @throws IllegalArgumentException if either CharSequence input is {@code null}.
*/
private static int unlimitedCompare(SimilarityInput left, SimilarityInput right) {
if (left == null || right == null) {
@@ -288,7 +283,7 @@ private static int unlimitedCompare(SimilarityInput left, SimilarityInput
private final Integer threshold;
/**
- * This returns the default instance that uses a version of the algorithm that does not use a threshold parameter.
+ * Constructs a default instance that uses a version of the algorithm that does not use a threshold parameter.
*
* @see LevenshteinDistance#getDefaultInstance()
* @deprecated Use {@link #getDefaultInstance()}.
@@ -299,8 +294,8 @@ public LevenshteinDistance() {
}
/**
- * If the threshold is not null, distance calculations will be limited to a maximum length. If the threshold is null, the unlimited version of the algorithm
- * will be used.
+ * Constructs a new instance. If the threshold is not null, distance calculations will be limited to a maximum length. If the threshold is null, the
+ * unlimited version of the algorithm will be used.
*
* @param threshold If this is null then distances calculations will not be limited. This may not be negative.
*/
@@ -319,20 +314,13 @@ public LevenshteinDistance(final Integer threshold) {
*
*
*
* Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large
- * strings.
- * This implementation of the Levenshtein distance algorithm is from
- * http://www.merriampark.com/ldjava.htm
+ * strings.
*
*
- * @param left the first input, must not be null
- * @param right the second input, must not be null
- * @return result distance, or -1
- * @throws IllegalArgumentException if either String input {@code null}
+ * @param left the first input, must not be null.
+ * @param right the second input, must not be null.
+ * @return result distance, or -1.
+ * @throws IllegalArgumentException if either String input {@code null}.
*/
@Override
public Integer apply(final CharSequence left, final CharSequence right) {
@@ -362,8 +350,8 @@ public Integer apply(final CharSequence left, final CharSequence right) {
*
*
*
- * distance.apply(null, *) = IllegalArgumentException
- * distance.apply(*, null) = IllegalArgumentException
+ * distance.apply(null, *) = Throws {@link IllegalArgumentException}
+ * distance.apply(*, null) = Throws {@link IllegalArgumentException}
* distance.apply("","") = 0
* distance.apply("","a") = 1
* distance.apply("aaapppp", "") = 7
@@ -392,7 +380,7 @@ public Integer apply(final SimilarityInput left, final SimilarityInput
/**
* Gets the distance threshold.
*
- * @return The distance threshold
+ * @return The distance threshold.
*/
public Integer getThreshold() {
return threshold;
diff --git a/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java b/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java
index 796019077d..37b547798b 100644
--- a/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java
+++ b/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java
@@ -54,9 +54,9 @@ public class LevenshteinResults {
* Constructs the results for a detailed Levenshtein distance.
*
* @param distance distance between two character sequences.
- * @param insertCount insert character count
- * @param deleteCount delete character count
- * @param substituteCount substitute character count
+ * @param insertCount insert character count.
+ * @param deleteCount delete character count.
+ * @param substituteCount substitute character count.
*/
public LevenshteinResults(final Integer distance, final Integer insertCount, final Integer deleteCount,
final Integer substituteCount) {
@@ -83,7 +83,7 @@ public boolean equals(final Object o) {
/**
* Gets the number of character deletion needed to change one character sequence to other.
*
- * @return delete character count
+ * @return delete character count.
*/
public Integer getDeleteCount() {
return deleteCount;
@@ -92,7 +92,7 @@ public Integer getDeleteCount() {
/**
* Gets the distance between two character sequences.
*
- * @return distance between two character sequence
+ * @return distance between two character sequence.
*/
public Integer getDistance() {
return distance;
@@ -101,7 +101,7 @@ public Integer getDistance() {
/**
* Gets the number of insertion needed to change one character sequence into another.
*
- * @return insert character count
+ * @return insert character count.
*/
public Integer getInsertCount() {
return insertCount;
@@ -110,7 +110,7 @@ public Integer getInsertCount() {
/**
* Gets the number of character substitution needed to change one character sequence into another.
*
- * @return substitute character count
+ * @return substitute character count.
*/
public Integer getSubstituteCount() {
return substituteCount;
diff --git a/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java b/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java
index 86288d4872..ac6d8d36f0 100644
--- a/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java
+++ b/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java
@@ -52,7 +52,7 @@
public class LongestCommonSubsequence implements SimilarityScore {
/**
- * Singleton instance.
+ * The singleton instance.
*/
static final LongestCommonSubsequence INSTANCE = new LongestCommonSubsequence();
@@ -65,7 +65,7 @@ public class LongestCommonSubsequence implements SimilarityScore {
*
* @param left first input sequence.
* @param right second input sequence.
- * @return last row of the dynamic-programming (DP) table for calculating the LCS of {@code left} and {@code right}
+ * @return last row of the dynamic-programming (DP) table for calculating the LCS of {@code left} and {@code right}.
* @since 1.10.0
*/
private static int[] algorithmB(final CharSequence left, final CharSequence right) {
@@ -104,7 +104,7 @@ private static int[] algorithmB(final CharSequence left, final CharSequence righ
*
* @param left first input sequence.
* @param right second input sequence.
- * @return the LCS of {@code left} and {@code right}
+ * @return the LCS of {@code left} and {@code right}.
* @since 1.10.0
*/
private static String algorithmC(final CharSequence left, final CharSequence right) {
@@ -144,7 +144,9 @@ private static String algorithmC(final CharSequence left, final CharSequence rig
return out.toString();
}
- // An auxiliary method for CharSequence reversal
+ /*
+ * A method for CharSequence reversal.
+ */
private static String reverse(final CharSequence s) {
return new StringBuilder(s).reverse().toString();
}
@@ -170,10 +172,10 @@ public LongestCommonSubsequence() {
* An evaluation using JMH revealed that this method is almost two times faster than its previous version.
*
*
- * @param left first character sequence
- * @param right second character sequence
- * @return length of the longest common subsequence of {@code left} and {@code right}
- * @throws IllegalArgumentException if either String input {@code null}
+ * @param left first character sequence.
+ * @param right second character sequence.
+ * @return length of the longest common subsequence of {@code left} and {@code right}.
+ * @throws IllegalArgumentException if either String input {@code null}.
*/
@Override
public Integer apply(final CharSequence left, final CharSequence right) {
@@ -211,10 +213,10 @@ public Integer apply(final CharSequence left, final CharSequence right) {
* elements.
*
*
- * @param left first character sequence
- * @param right second character sequence
- * @return the longest common subsequence found
- * @throws IllegalArgumentException if either String input {@code null}
+ * @param left first character sequence.
+ * @param right second character sequence.
+ * @return the longest common subsequence found.
+ * @throws IllegalArgumentException if either String input {@code null}.
* @deprecated Deprecated as of 1.2 due to a typo in the method name.
* Use {@link #longestCommonSubsequence(CharSequence, CharSequence)} instead.
* This method will be removed in 2.0.
@@ -247,10 +249,10 @@ public CharSequence logestCommonSubsequence(final CharSequence left, final CharS
* elements.
*
*
- * @param left first character sequence
- * @param right second character sequence
- * @return the longest common subsequence found
- * @throws IllegalArgumentException if either String input {@code null}
+ * @param left first character sequence.
+ * @param right second character sequence.
+ * @return the longest common subsequence found.
+ * @throws IllegalArgumentException if either String input {@code null}.
* @since 1.2
*/
public CharSequence longestCommonSubsequence(final CharSequence left, final CharSequence right) {
@@ -279,9 +281,9 @@ public CharSequence longestCommonSubsequence(final CharSequence left, final Char
* dynamic programming portion of the algorithm, and is the reason for the runtime complexity being
* O(m*n), where m=left.length() and n=right.length().
*
- * @param left first character sequence
- * @param right second character sequence
- * @return lcsLengthArray
+ * @param left first character sequence.
+ * @param right second character sequence.
+ * @return longest common substring length array.
* @deprecated Deprecated as of 1.10. A more efficient implementation for calculating LCS is now available.
* Use {@link #longestCommonSubsequence(CharSequence, CharSequence)} instead to directly calculate the LCS.
* This method will be removed in 2.0.
diff --git a/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistance.java b/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistance.java
index f6ce1e53f5..ed33437ac2 100644
--- a/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistance.java
@@ -44,15 +44,14 @@ public LongestCommonSubsequenceDistance() {
}
/**
- * Calculates an edit distance between two {@code CharSequence}'s {@code left} and
- * {@code right} as: {@code left.length() + right.length() - 2 * LCS(left, right)}, where
- * {@code LCS} is given in {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
+ * Calculates an edit distance between two {@code CharSequence}'s {@code left} and {@code right} as:
+ * {@code left.length() + right.length() - 2 * LCS(left, right)}, where {@code LCS} is given in
+ * {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
*
- * @param left first character sequence
- * @param right second character sequence
- * @return distance
- * @throws IllegalArgumentException
- * if either String input {@code null}
+ * @param left first character sequence.
+ * @param right second character sequence.
+ * @return distance.
+ * @throws IllegalArgumentException if either String input {@code null}.
*/
@Override
public Integer apply(final CharSequence left, final CharSequence right) {
diff --git a/src/main/java/org/apache/commons/text/similarity/ObjectSimilarityScore.java b/src/main/java/org/apache/commons/text/similarity/ObjectSimilarityScore.java
index 393518aed7..21ce3afbcb 100644
--- a/src/main/java/org/apache/commons/text/similarity/ObjectSimilarityScore.java
+++ b/src/main/java/org/apache/commons/text/similarity/ObjectSimilarityScore.java
@@ -30,8 +30,8 @@
* A similarity score is the function {@code d: [X * X] -> [0, INFINITY)} with the following properties:
*
*