You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by kr...@apache.org on 2026/09/30 23:17:38 UTC

(opennlp) branch feat/OPENNLP-1935-regex-guard updated (b53d6a3b9 -> 28f4a68f2)

This is an automated email from the ASF dual-hosted git repository.

krickert pushed a change to branch feat/OPENNLP-1935-regex-guard
in repository https://gitbox.apache.org/repos/asf/opennlp.git


    from b53d6a3b9 OPENNLP-1989: Regex removal (5b/10): Preserve feature identities in event parsing (#1321)
     new 3e1138bb3 OPENNLP-1935: Forbid java.util.regex in production code with forbiddenapis
     new 96091141e OPENNLP-1935: Share one non-empty split loop in StringUtil
     new da06e6abc OPENNLP-1935: Test that whitespace runs in a token sample line produce no empty token
     new 28f4a68f2 OPENNLP-1935: Move the remaining String.split calls to the StringUtil helpers

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .github/CONTRIBUTING.md                            |  4 ++
 dev/forbidden-regex.txt                            | 30 +++++++++++++
 .../opennlp/tools/commons/SuppressForbidden.java   | 51 +++++++++++++++++++++
 .../tools/tokenize/lattice/MecabDictionary.java    | 28 ++----------
 .../main/java/opennlp/tools/util/StringUtil.java   | 52 +++++++++++++---------
 .../opennlp/tools/formats/conllu/ConlluStream.java |  3 +-
 .../tools/formats/masc/MascIdentifiers.java        | 40 +----------------
 .../java/opennlp/tools/ml/model/EventFields.java   | 27 +----------
 .../opennlp/tools/namefind/RegexNameFinder.java    |  8 ++++
 .../tools/namefind/RegexNameFinderFactory.java     |  7 +++
 .../tools/stemmer/hunspell/HunspellDictionary.java | 28 ++----------
 .../tools/tokenize/lang/en/TokenSampleStream.java  |  3 +-
 .../main/java/opennlp/tools/util/DownloadUtil.java |  2 +-
 .../tools/tokenize/TokenSampleStreamTest.java      | 22 +++++++++
 .../java/opennlp/tools/util/StringUtilTest.java    | 40 +++++++++++++++++
 pom.xml                                            | 19 ++++++++
 16 files changed, 228 insertions(+), 136 deletions(-)
 create mode 100644 dev/forbidden-regex.txt
 create mode 100644 opennlp-api/src/main/java/opennlp/tools/commons/SuppressForbidden.java


(opennlp) 02/04: OPENNLP-1935: Share one non-empty split loop in StringUtil

Posted by kr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

krickert pushed a commit to branch feat/OPENNLP-1935-regex-guard
in repository https://gitbox.apache.org/repos/asf/opennlp.git

commit 96091141ee19dac7253bb9144a26820a23837991
Author: Kristian Rickert <kr...@apache.org>
AuthorDate: Wed Sep 30 18:55:33 2026 -0400

    OPENNLP-1935: Share one non-empty split loop in StringUtil
    
    EventFields, MascIdentifiers, MecabDictionary and HunspellDictionary each had the same
    split loop with a different character test. StringUtil has it as one private loop behind
    splitNonEmpty, splitOnUnicodeWhitespace and the new mode-aware splitOnWhitespace, and the
    four classes call those.
---
 .../tools/tokenize/lattice/MecabDictionary.java    | 28 ++----------
 .../main/java/opennlp/tools/util/StringUtil.java   | 52 +++++++++++++---------
 .../tools/formats/masc/MascIdentifiers.java        | 40 +----------------
 .../java/opennlp/tools/ml/model/EventFields.java   | 27 +----------
 .../tools/stemmer/hunspell/HunspellDictionary.java | 28 ++----------
 .../java/opennlp/tools/util/StringUtilTest.java    | 40 +++++++++++++++++
 6 files changed, 82 insertions(+), 133 deletions(-)

diff --git a/opennlp-api/src/main/java/opennlp/tools/tokenize/lattice/MecabDictionary.java b/opennlp-api/src/main/java/opennlp/tools/tokenize/lattice/MecabDictionary.java
index ebd7c9f34..190424a2d 100644
--- a/opennlp-api/src/main/java/opennlp/tools/tokenize/lattice/MecabDictionary.java
+++ b/opennlp-api/src/main/java/opennlp/tools/tokenize/lattice/MecabDictionary.java
@@ -236,7 +236,7 @@ public final class MecabDictionary {
       if (headerLine.isEmpty()) {
         throw new IOException("empty " + MATRIX_DEF + " under " + directory);
       }
-      final String[] header = splitWhitespace(headerLine);
+      final String[] header = StringUtil.splitOnWhitespace(headerLine);
       if (header.length != 2) {
         throw new IOException("malformed " + MATRIX_DEF + " header: " + headerLine);
       }
@@ -273,7 +273,7 @@ public final class MecabDictionary {
         if (line.isEmpty()) {
           continue;
         }
-        final String[] fields = splitWhitespace(line);
+        final String[] fields = StringUtil.splitOnWhitespace(line);
         if (fields.length != 3) {
           throw new IOException("malformed " + MATRIX_DEF + " line " + lineNumber);
         }
@@ -437,7 +437,7 @@ public final class MecabDictionary {
         if (line.isEmpty()) {
           continue;
         }
-        final String[] fields = splitWhitespace(line);
+        final String[] fields = StringUtil.splitOnWhitespace(line);
         if (fields[0].regionMatches(true, 0, HEX_PREFIX, 0, HEX_PREFIX.length())) {
           final int rangeSeparator = fields[0].indexOf(RANGE_SEPARATOR);
           final int from;
@@ -616,28 +616,6 @@ public final class MecabDictionary {
     return fields;
   }
 
-  /**
-   * Splits a line into its whitespace-separated fields.
-   *
-   * @param line The line to split.
-   * @return The non-empty fields in order. Never {@code null}.
-   */
-  private static String[] splitWhitespace(String line) {
-    final List<String> parts = new ArrayList<>();
-    int start = -1;
-    for (int i = 0; i <= line.length(); i++) {
-      if (i == line.length() || StringUtil.isWhitespace(line.charAt(i))) {
-        if (start >= 0) {
-          parts.add(line.substring(start, i));
-          start = -1;
-        }
-      } else if (start < 0) {
-        start = i;
-      }
-    }
-    return parts.toArray(new String[0]);
-  }
-
   /**
    * Parses a decimal integer field, reporting the file and line on failure.
    *
diff --git a/opennlp-api/src/main/java/opennlp/tools/util/StringUtil.java b/opennlp-api/src/main/java/opennlp/tools/util/StringUtil.java
index b1c772d51..144b9e7e6 100644
--- a/opennlp-api/src/main/java/opennlp/tools/util/StringUtil.java
+++ b/opennlp-api/src/main/java/opennlp/tools/util/StringUtil.java
@@ -21,6 +21,7 @@ import java.nio.CharBuffer;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
+import java.util.function.IntPredicate;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -129,26 +130,22 @@ public class StringUtil {
    */
   public static String[] splitOnUnicodeWhitespace(CharSequence input) {
     requireNonNullArg(input, "input");
-    final List<String> terms = new ArrayList<>();
-    final int n = input.length();
-    int start = -1;
-    int i = 0;
-    while (i < n) {
-      final int cp = Character.codePointAt(input, i);
-      if (isUnicodeWhitespace(cp)) {
-        if (start >= 0) {
-          terms.add(input.subSequence(start, i).toString());
-          start = -1;
-        }
-      } else if (start < 0) {
-        start = i;
-      }
-      i += Character.charCount(cp);
-    }
-    if (start >= 0) {
-      terms.add(input.subSequence(start, n).toString());
-    }
-    return terms.toArray(new String[0]);
+    return splitNonEmpty(input, StringUtil::isUnicodeWhitespace);
+  }
+
+  /**
+   * Splits {@code input} on runs of whitespace under the active {@link WhitespaceMode}, see
+   * {@link #isWhitespace(char)}. Leading and trailing runs are ignored, so whitespace-only
+   * input yields an empty array. Use {@link #splitOnUnicodeWhitespace(CharSequence)} where
+   * the Unicode definition should apply regardless of the mode.
+   *
+   * @param input The text to split. Must not be {@code null}.
+   * @return The non-whitespace fields in order.
+   * @throws IllegalArgumentException If {@code input} is {@code null}.
+   */
+  public static String[] splitOnWhitespace(CharSequence input) {
+    requireNonNullArg(input, "input");
+    return splitNonEmpty(input, StringUtil::isWhitespace);
   }
 
   /**
@@ -281,11 +278,24 @@ public class StringUtil {
         throw new IllegalArgumentException("separators must not contain a surrogate");
       }
     }
+    return splitNonEmpty(input, c -> isAnyOf((char) c, separators));
+  }
+
+  /**
+   * Splits {@code input} on runs of the UTF-16 code units that {@code separator} accepts and
+   * drops the empty fields that leading, trailing or adjacent separators would produce. The
+   * one loop behind every non-empty split of this class.
+   *
+   * @param input The text to split, not {@code null}.
+   * @param separator Accepts a code unit that separates fields.
+   * @return The non-empty fields in order.
+   */
+  private static String[] splitNonEmpty(CharSequence input, IntPredicate separator) {
     final List<String> fields = new ArrayList<>();
     final int length = input.length();
     int start = -1;
     for (int i = 0; i < length; i++) {
-      if (isAnyOf(input.charAt(i), separators)) {
+      if (separator.test(input.charAt(i))) {
         if (start >= 0) {
           fields.add(input.subSequence(start, i).toString());
           start = -1;
diff --git a/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/masc/MascIdentifiers.java b/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/masc/MascIdentifiers.java
index 2ecb689f9..be6e8f83e 100644
--- a/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/masc/MascIdentifiers.java
+++ b/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/masc/MascIdentifiers.java
@@ -17,9 +17,6 @@
 
 package opennlp.tools.formats.masc;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import opennlp.tools.util.Span;
 import opennlp.tools.util.StringUtil;
 
@@ -99,7 +96,7 @@ final class MascIdentifiers {
     if (ids == null) {
       throw new IllegalArgumentException("MASC identifier list must not be null");
     }
-    String[] items = splitOnXmlWhitespace(ids);
+    String[] items = StringUtil.splitNonEmpty(ids, SPACE, TAB, CARRIAGE_RETURN, LINE_FEED);
     if (items.length == 0) {
       throw new IllegalArgumentException("MASC identifier list must name at least one identifier");
     }
@@ -110,29 +107,6 @@ final class MascIdentifiers {
     return numbers;
   }
 
-  /**
-   * Splits an attribute value on runs of XML whitespace. Leading, trailing, and repeated separators
-   * produce no empty item.
-   *
-   * @param value The attribute value. Must not be {@code null}.
-   * @return The non-empty items in order; empty for a value without one.
-   */
-  private static String[] splitOnXmlWhitespace(String value) {
-    List<String> items = new ArrayList<>();
-    int start = -1;
-    for (int i = 0; i <= value.length(); i++) {
-      if (i == value.length() || isXmlWhitespace(value.charAt(i))) {
-        if (start >= 0) {
-          items.add(value.substring(start, i));
-          start = -1;
-        }
-      } else if (start < 0) {
-        start = i;
-      }
-    }
-    return items.toArray(new String[0]);
-  }
-
   /**
    * Parses the two ordered, nonnegative offsets of a contiguous text region, each written in
    * ASCII digits only, as {@link #parseId(String, String)} reads an identifier number.
@@ -146,7 +120,7 @@ final class MascIdentifiers {
     if (anchors == null) {
       throw new IllegalArgumentException("MASC region anchors must not be null");
     }
-    String[] items = splitOnXmlWhitespace(anchors);
+    String[] items = StringUtil.splitNonEmpty(anchors, SPACE, TAB, CARRIAGE_RETURN, LINE_FEED);
     if (items.length != 2) {
       throw new IllegalArgumentException("MASC region anchors must contain exactly two offsets: " + anchors);
     }
@@ -176,14 +150,4 @@ final class MascIdentifiers {
     return Integer.parseInt(text, from, end, 10);
   }
 
-  /**
-   * Tests for <a href="https://www.w3.org/TR/xml/#NT-S">XML whitespace</a>: space, tab,
-   * carriage return or line feed.
-   *
-   * @param c The character to test.
-   * @return {@code true} if {@code c} is XML whitespace, {@code false} otherwise.
-   */
-  private static boolean isXmlWhitespace(char c) {
-    return c == SPACE || c == TAB || c == CARRIAGE_RETURN || c == LINE_FEED;
-  }
 }
diff --git a/opennlp-core/opennlp-ml/opennlp-ml-commons/src/main/java/opennlp/tools/ml/model/EventFields.java b/opennlp-core/opennlp-ml/opennlp-ml-commons/src/main/java/opennlp/tools/ml/model/EventFields.java
index f5bfd2b89..85c4c0713 100644
--- a/opennlp-core/opennlp-ml/opennlp-ml-commons/src/main/java/opennlp/tools/ml/model/EventFields.java
+++ b/opennlp-core/opennlp-ml/opennlp-ml-commons/src/main/java/opennlp/tools/ml/model/EventFields.java
@@ -16,8 +16,7 @@
  */
 package opennlp.tools.ml.model;
 
-import java.util.ArrayList;
-import java.util.List;
+import opennlp.tools.util.StringUtil;
 
 /**
  * Field delimiters and messages shared by {@link FileEventStream},
@@ -51,28 +50,6 @@ final class EventFields {
    * @return The fields in order.
    */
   static String[] split(String text) {
-    final List<String> fields = new ArrayList<>();
-    int start = -1;
-    for (int i = 0; i <= text.length(); i++) {
-      if (i == text.length() || isSeparator(text.charAt(i))) {
-        if (start >= 0) {
-          fields.add(text.substring(start, i));
-          start = -1;
-        }
-      } else if (start < 0) {
-        start = i;
-      }
-    }
-    return fields.toArray(new String[0]);
-  }
-
-  /**
-   * Tests the delimiter set of the textual event formats.
-   *
-   * @param c The character to test.
-   * @return Whether the character separates event fields.
-   */
-  private static boolean isSeparator(char c) {
-    return c == SPACE || c == TAB || c == CARRIAGE_RETURN || c == LINE_FEED || c == FORM_FEED;
+    return StringUtil.splitNonEmpty(text, SPACE, TAB, CARRIAGE_RETURN, LINE_FEED, FORM_FEED);
   }
 }
diff --git a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/stemmer/hunspell/HunspellDictionary.java b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/stemmer/hunspell/HunspellDictionary.java
index 94aa308a8..9b52ebd8b 100644
--- a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/stemmer/hunspell/HunspellDictionary.java
+++ b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/stemmer/hunspell/HunspellDictionary.java
@@ -2320,7 +2320,7 @@ public final class HunspellDictionary {
       final String trimmed = trim(line);
       if (trimmed.startsWith(SET_PREFIX) || trimmed.startsWith(SET_TAB_PREFIX)) {
         // the encoding is the first field after the directive; later fields are ignored
-        final String name = split(trimmed.substring(SET_PREFIX.length()))[0];
+        final String name = StringUtil.splitOnWhitespace(trimmed.substring(SET_PREFIX.length()))[0];
         try {
           return Charset.forName(name);
         } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
@@ -2407,7 +2407,7 @@ public final class HunspellDictionary {
     final String[] lines = splitLines(withoutByteOrderMark(content));
     final String[][] fieldsByLine = new String[lines.length][];
     for (int i = 0; i < lines.length; i++) {
-      fieldsByLine[i] = split(lines[i]);
+      fieldsByLine[i] = StringUtil.splitOnWhitespace(lines[i]);
     }
     result.flagMode = readFlagMode(fieldsByLine);
     result.flagAliases.addAll(readFlagAliases(fieldsByLine, result.flagMode));
@@ -2793,7 +2793,8 @@ public final class HunspellDictionary {
         flags = parseAliasedFlags(flagRun, affix.flagMode, affix.flagAliases, i + 1).clone();
       }
       if (morphology >= 0) {
-        affix.entryMorphology.put(flags, parseMorphology(split(line.substring(morphology)),
+        affix.entryMorphology.put(flags,
+            parseMorphology(StringUtil.splitOnWhitespace(line.substring(morphology)),
             affix.morphologyAliases, i + 1));
       }
       entries.computeIfAbsent(removeIgnored(word.replace("\\/", "/"), affix.ignoredCharacters),
@@ -3194,25 +3195,4 @@ public final class HunspellDictionary {
     return parts.toArray(new String[0]);
   }
 
-  /**
-   * Splits a line on whitespace with a single character scan.
-   *
-   * @param line The line to split.
-   * @return The whitespace-separated fields, without empty ones. Never {@code null}.
-   */
-  private static String[] split(String line) {
-    final List<String> parts = new ArrayList<>();
-    int start = -1;
-    for (int i = 0; i <= line.length(); i++) {
-      if (i == line.length() || StringUtil.isWhitespace(line.charAt(i))) {
-        if (start >= 0) {
-          parts.add(line.substring(start, i));
-          start = -1;
-        }
-      } else if (start < 0) {
-        start = i;
-      }
-    }
-    return parts.toArray(new String[0]);
-  }
 }
diff --git a/opennlp-tools/src/test/java/opennlp/tools/util/StringUtilTest.java b/opennlp-tools/src/test/java/opennlp/tools/util/StringUtilTest.java
index 7acdc8847..1cd2eaccf 100644
--- a/opennlp-tools/src/test/java/opennlp/tools/util/StringUtilTest.java
+++ b/opennlp-tools/src/test/java/opennlp/tools/util/StringUtilTest.java
@@ -530,6 +530,46 @@ public class StringUtilTest {
         StringUtil.splitOnUnicodeWhitespace(withInfo));
   }
 
+  @Test
+  void testSplitOnWhitespaceNullThrows() {
+    Assertions.assertThrows(IllegalArgumentException.class, () -> StringUtil.splitOnWhitespace(null));
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", " ", " \t\n ", "\u00A0\u3000"})
+  void testSplitOnWhitespaceBlankYieldsEmpty(String input) {
+    Assertions.assertArrayEquals(new String[0], StringUtil.splitOnWhitespace(input));
+  }
+
+  @Test
+  void testSplitOnWhitespaceCollapsesRunsAndIgnoresEnds() {
+    Assertions.assertArrayEquals(new String[] {"a", "b", "c"},
+        StringUtil.splitOnWhitespace("  a \t\u00A0b\u3000\r\nc  "));
+    Assertions.assertArrayEquals(new String[] {"a\u200Bb", "\uD83D\uDE00"},
+        StringUtil.splitOnWhitespace("a\u200Bb \uD83D\uDE00"));
+  }
+
+  @Test
+  void testSplitOnWhitespaceFollowsTheWhitespaceMode() {
+    // U+0085 has the White_Space property but is not Character.isWhitespace; U+001C is the
+    // reverse. The mode-aware split follows the active mode, the Unicode split does not.
+    final String withNel = "a\u0085b";
+    final String withInfo = "a\u001Cb";
+    Assertions.assertArrayEquals(new String[] {"a", "b"}, StringUtil.splitOnWhitespace(withNel));
+    Assertions.assertArrayEquals(new String[] {"a\u001Cb"}, StringUtil.splitOnWhitespace(withInfo));
+
+    WhitespaceMode.setActive(WhitespaceMode.LEGACY);
+    Assertions.assertArrayEquals(new String[] {"a\u0085b"}, StringUtil.splitOnWhitespace(withNel));
+    Assertions.assertArrayEquals(new String[] {"a", "b"}, StringUtil.splitOnWhitespace(withInfo));
+  }
+
+  @Test
+  void testSplitOnWhitespaceAgreesWithTheUnicodeSplitInCurrentMode() {
+    final String input = " t0\u2003t1\u0085t2 \u3000 t3\uD801\uDC12 ";
+    Assertions.assertArrayEquals(StringUtil.splitOnUnicodeWhitespace(input),
+        StringUtil.splitOnWhitespace(input));
+  }
+
   @Test
   void testSplitOnUnicodeWhitespaceAllTwentyFiveAsMixedSeparators() {
     // Build "t0 <ws0> t1 <ws1> ... t24 <ws24> t25" using every White_Space code point.


(opennlp) 04/04: OPENNLP-1935: Move the remaining String.split calls to the StringUtil helpers

Posted by kr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

krickert pushed a commit to branch feat/OPENNLP-1935-regex-guard
in repository https://gitbox.apache.org/repos/asf/opennlp.git

commit 28f4a68f2ed653e49105027b09704f5a22184c70
Author: Kristian Rickert <kr...@apache.org>
AuthorDate: Wed Sep 30 18:55:51 2026 -0400

    OPENNLP-1935: Move the remaining String.split calls to the StringUtil helpers
    
    ConlluStream splits a range id on the literal dash. TokenSampleStream and DownloadUtil split
    on whitespace runs under the active whitespace mode. The forbidden list message names the
    helpers that exist now. BasicContextGenerator's call is replaced by #1280.
---
 dev/forbidden-regex.txt                                                | 2 +-
 .../src/main/java/opennlp/tools/formats/conllu/ConlluStream.java       | 3 ++-
 .../main/java/opennlp/tools/tokenize/lang/en/TokenSampleStream.java    | 3 ++-
 .../opennlp-runtime/src/main/java/opennlp/tools/util/DownloadUtil.java | 2 +-
 4 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/dev/forbidden-regex.txt b/dev/forbidden-regex.txt
index 0306a7315..3eecc2937 100644
--- a/dev/forbidden-regex.txt
+++ b/dev/forbidden-regex.txt
@@ -20,7 +20,7 @@
 # @opennlp.tools.commons.SuppressForbidden and is exempt. Only production classes are
 # checked; tests may use regular expressions.
 
-@defaultMessage Use a code-point scan or a StringUtil helper (splitOnUnicodeWhitespace, split(CharSequence, char), splitNonEmpty once OPENNLP-1955 is merged) instead of java.util.regex; a member with a user-supplied pattern as its public contract is marked @opennlp.tools.commons.SuppressForbidden (OPENNLP-1935)
+@defaultMessage Use a code-point scan or a StringUtil helper (splitOnUnicodeWhitespace, splitOnWhitespace, split(CharSequence, char), splitNonEmpty) instead of java.util.regex; a member with a user-supplied pattern as its public contract is marked @opennlp.tools.commons.SuppressForbidden (OPENNLP-1935)
 java.util.regex.**
 java.lang.String#split(java.lang.String)
 java.lang.String#split(java.lang.String,int)
diff --git a/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluStream.java b/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluStream.java
index 9a2e63336..d87c285ab 100644
--- a/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluStream.java
+++ b/opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluStream.java
@@ -37,6 +37,7 @@ import opennlp.tools.util.InvalidFormatException;
 import opennlp.tools.util.ObjectStream;
 import opennlp.tools.util.ParagraphStream;
 import opennlp.tools.util.PlainTextByLineStream;
+import opennlp.tools.util.StringUtil;
 
 /**
  * The CoNNL-U Format is specified
@@ -166,7 +167,7 @@ public class ConlluStream implements ObjectStream<ConlluSentence> {
     for (ConlluWordLine line : lines) {
       if (line.getId().contains("-")) {
         List<String> expandedContractions = new ArrayList<>();
-        String[] ids = line.getId().split("-");
+        String[] ids = StringUtil.split(line.getId(), '-');
         int start = Integer.parseInt(ids[0]);
         int end = Integer.parseInt(ids[1]);
         for (long j = start; j <= end; j++) {
diff --git a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/lang/en/TokenSampleStream.java b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/lang/en/TokenSampleStream.java
index 951fca5b5..e68b0c65f 100644
--- a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/lang/en/TokenSampleStream.java
+++ b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/lang/en/TokenSampleStream.java
@@ -31,6 +31,7 @@ import org.slf4j.LoggerFactory;
 
 import opennlp.tools.tokenize.TokenSample;
 import opennlp.tools.util.Span;
+import opennlp.tools.util.StringUtil;
 
 /**
  * Class which produces an Iterator&lt;TokenSample&gt; from a file of space delimited token.
@@ -55,7 +56,7 @@ public class TokenSampleStream implements Iterator<TokenSample> {
   }
 
   public TokenSample next() {
-    String[] tokens = line.split("\\s+");
+    String[] tokens = StringUtil.splitOnWhitespace(line);
     if (tokens.length == 0) {
       evenq = true;
     }
diff --git a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/util/DownloadUtil.java b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/util/DownloadUtil.java
index 0f6f6800d..fa0426b15 100644
--- a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/util/DownloadUtil.java
+++ b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/util/DownloadUtil.java
@@ -262,7 +262,7 @@ public class DownloadUtil {
       return null;
     }
     final String trimmed = checksumFileContent.trim();
-    return trimmed.isEmpty() ? null : trimmed.split("\\s")[0];
+    return trimmed.isEmpty() ? null : StringUtil.splitOnWhitespace(trimmed)[0];
   }
 
   private static void verifyChecksum(Path model, String expectedChecksum) throws IOException {


(opennlp) 03/04: OPENNLP-1935: Test that whitespace runs in a token sample line produce no empty token

Posted by kr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

krickert pushed a commit to branch feat/OPENNLP-1935-regex-guard
in repository https://gitbox.apache.org/repos/asf/opennlp.git

commit da06e6abcf21c205d5ab86a8574c7d6e1e43ee2a
Author: Kristian Rickert <kr...@apache.org>
AuthorDate: Wed Sep 30 18:55:42 2026 -0400

    OPENNLP-1935: Test that whitespace runs in a token sample line produce no empty token
    
    A leading run of spaces and a tab between tokens separate the tokens like a single space.
---
 .../tools/tokenize/TokenSampleStreamTest.java      | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/opennlp-core/opennlp-runtime/src/test/java/opennlp/tools/tokenize/TokenSampleStreamTest.java b/opennlp-core/opennlp-runtime/src/test/java/opennlp/tools/tokenize/TokenSampleStreamTest.java
index 22769a4c6..661ab3c4e 100644
--- a/opennlp-core/opennlp-runtime/src/test/java/opennlp/tools/tokenize/TokenSampleStreamTest.java
+++ b/opennlp-core/opennlp-runtime/src/test/java/opennlp/tools/tokenize/TokenSampleStreamTest.java
@@ -54,6 +54,28 @@ public class TokenSampleStreamTest {
     Assertions.assertEquals("wage", tokenSpans[3].getCoveredText(sampleTokens));
   }
 
+  /**
+   * Tests that runs of whitespace, including a leading run and a tab, separate tokens
+   * without producing an empty token.
+   */
+  @Test
+  void testParsingWhitespaceRunsSeparateTokens() throws IOException {
+    String sampleTokens = "  Slave\tto  the wage ";
+
+    ObjectStream<TokenSample> sampleTokenStream = new TokenSampleStream(
+        ObjectStreamUtils.createObjectStream(sampleTokens));
+
+    TokenSample tokenSample = sampleTokenStream.read();
+    Span[] tokenSpans = tokenSample.getTokenSpans();
+    String text = tokenSample.getText();
+
+    Assertions.assertEquals(4, tokenSpans.length);
+    Assertions.assertEquals("Slave", tokenSpans[0].getCoveredText(text));
+    Assertions.assertEquals("to", tokenSpans[1].getCoveredText(text));
+    Assertions.assertEquals("the", tokenSpans[2].getCoveredText(text));
+    Assertions.assertEquals("wage", tokenSpans[3].getCoveredText(text));
+  }
+
   /**
    * Tests if the {@link TokenSample} correctly tokenizes tokens which
    * are separated by the split chars.


(opennlp) 01/04: OPENNLP-1935: Forbid java.util.regex in production code with forbiddenapis

Posted by kr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

krickert pushed a commit to branch feat/OPENNLP-1935-regex-guard
in repository https://gitbox.apache.org/repos/asf/opennlp.git

commit 3e1138bb341d9dcfb9529ffe13bffb233e40deca
Author: Kristian Rickert <kr...@apache.org>
AuthorDate: Mon Sep 28 23:49:37 2026 -0400

    OPENNLP-1935: Forbid java.util.regex in production code with forbiddenapis
    
    Add a forbiddenapis check for production classes in every module. Reject
    java.util.regex and regex-based String and Scanner methods at
    process-classes, before tests run. Exclude test classes and point error
    messages to the StringUtil replacements.
    
    Add SuppressForbidden for documented APIs that accept user-supplied
    regular expressions. Require a reason for each exception and apply it
    to RegexNameFinder and RegexNameFinderFactory.
    
    Document the rule, dev/forbidden-regex.txt and allowed exceptions in
    CONTRIBUTING.md. The build will fail until the remaining production
    regex uses are removed by the related PRs.
    
    Assisted-by: Claude Code 2.1.281
    Co-authored-by: Kristian Rickert <kr...@apache.org>
    Co-authored-by: Claude <no...@anthropic.com>
    Reviewed-by: Kristian Rickert <kr...@apache.org>
    Signed-off-by: Kristian Rickert <kr...@apache.org>
---
 .github/CONTRIBUTING.md                            |  4 ++
 dev/forbidden-regex.txt                            | 30 +++++++++++++
 .../opennlp/tools/commons/SuppressForbidden.java   | 51 ++++++++++++++++++++++
 .../opennlp/tools/namefind/RegexNameFinder.java    |  8 ++++
 .../tools/namefind/RegexNameFinderFactory.java     |  7 +++
 pom.xml                                            | 19 ++++++++
 6 files changed, 119 insertions(+)

diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 577eb1615..ac52a4a9d 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -9,3 +9,7 @@ To make the process smooth for the project *committers* (those who review and ac
 Please check out the [How to get involved](http://opennlp.apache.org/get-involved.html) to understand how contributions are made. 
 A detailed list of coding standards can be found at [Apache OpenNLP Code Conventions](http://opennlp.apache.org/code-conventions.html) which also contains a list of coding guidelines that you should follow.
 For pull requests, there is a [check list](PULL_REQUEST_TEMPLATE.md) with criteria for acceptable contributions.
+
+## Regular expressions in production code
+
+OpenNLP production code scans text with code-point loops and the helpers in `opennlp.tools.util.StringUtil` (for example `splitOnUnicodeWhitespace` and `split(CharSequence, char)`) instead of `java.util.regex`. The build enforces this with forbiddenapis: `dev/forbidden-regex.txt` lists the forbidden signatures, and the `forbidden-regex-main` execution in the root `pom.xml` checks production classes in the `process-classes` phase (tests are not checked). An exception exists only for a mem [...]
diff --git a/dev/forbidden-regex.txt b/dev/forbidden-regex.txt
new file mode 100644
index 000000000..0306a7315
--- /dev/null
+++ b/dev/forbidden-regex.txt
@@ -0,0 +1,30 @@
+# 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
+#
+#     http://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.
+
+# forbiddenapis signatures for the forbidden-regex-main execution in the root pom.xml.
+# Production code scans text with code-point loops and the opennlp.tools.util.StringUtil
+# helpers instead of java.util.regex (OPENNLP-1935). A member with a public contract that is
+# a user-supplied pattern (RegexNameFinder, the tokenizer factories) is marked with
+# @opennlp.tools.commons.SuppressForbidden and is exempt. Only production classes are
+# checked; tests may use regular expressions.
+
+@defaultMessage Use a code-point scan or a StringUtil helper (splitOnUnicodeWhitespace, split(CharSequence, char), splitNonEmpty once OPENNLP-1955 is merged) instead of java.util.regex; a member with a user-supplied pattern as its public contract is marked @opennlp.tools.commons.SuppressForbidden (OPENNLP-1935)
+java.util.regex.**
+java.lang.String#split(java.lang.String)
+java.lang.String#split(java.lang.String,int)
+java.lang.String#matches(java.lang.String)
+java.lang.String#replaceAll(java.lang.String,java.lang.String)
+java.lang.String#replaceFirst(java.lang.String,java.lang.String)
+java.util.Scanner#useDelimiter(java.lang.String)
diff --git a/opennlp-api/src/main/java/opennlp/tools/commons/SuppressForbidden.java b/opennlp-api/src/main/java/opennlp/tools/commons/SuppressForbidden.java
new file mode 100644
index 000000000..8bde26a2a
--- /dev/null
+++ b/opennlp-api/src/main/java/opennlp/tools/commons/SuppressForbidden.java
@@ -0,0 +1,51 @@
+/*
+ * 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
+ *
+ *     http://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 opennlp.tools.commons;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a member with a public contract that is a user-supplied regular expression,
+ * for example the patterns given to {@code RegexNameFinder} or the alphanumeric
+ * {@link java.util.regex.Pattern} accepted by the tokenizer factories.
+ * <p>
+ * Production code scans text with code-point loops and the
+ * {@code opennlp.tools.util.StringUtil} helpers instead of {@code java.util.regex}.
+ * The build enforces this rule with forbiddenapis, using the signatures in
+ * {@code dev/forbidden-regex.txt} (OPENNLP-1935). An annotated member is exempt
+ * from that check. Apply it to the narrowest member (field, constructor, or method)
+ * that needs it rather than to the enclosing class, so a regular expression added to
+ * another member of the same class is still reported.
+ * <p>
+ * The annotation is kept in class files and read by the build only; it has no
+ * effect at runtime.
+ */
+@Documented
+@Retention(RetentionPolicy.CLASS)
+@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
+public @interface SuppressForbidden {
+
+  /**
+   * @return The public contract that requires the regular expression.
+   */
+  String value();
+}
diff --git a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinder.java b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinder.java
index c62841ebd..8a9da60e6 100644
--- a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinder.java
+++ b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinder.java
@@ -25,6 +25,7 @@ import java.util.Objects;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import opennlp.tools.commons.SuppressForbidden;
 import opennlp.tools.util.Span;
 
 /**
@@ -35,6 +36,7 @@ import opennlp.tools.util.Span;
  */
 public final class RegexNameFinder implements TokenNameFinder {
 
+  @SuppressForbidden("user-supplied name finder patterns")
   private Pattern[] mPatterns;
   private String sType;
   private Map<String, Pattern[]> regexMap;
@@ -58,6 +60,7 @@ public final class RegexNameFinder implements TokenNameFinder {
    *
    * @throws IllegalArgumentException Thrown if {@code patterns} were {@code null} or empty.
    */
+  @SuppressForbidden("user-supplied name finder patterns")
   public RegexNameFinder(Pattern[] patterns, String type) {
     if (patterns == null || patterns.length == 0) {
       throw new IllegalArgumentException("patterns must not be null or empty!");
@@ -67,6 +70,7 @@ public final class RegexNameFinder implements TokenNameFinder {
     sType = type;
   }
 
+  @SuppressForbidden("user-supplied name finder patterns")
   @Override
   public Span[] find(String[] tokens) {
     Map<Integer, Integer> sentencePosTokenMap = new HashMap<>();
@@ -133,10 +137,12 @@ public final class RegexNameFinder implements TokenNameFinder {
    * @param text The text to use.
    * @return A {@link Span[]} representing the annotations.
    */
+  @SuppressForbidden("user-supplied name finder patterns")
   public Span[] find(String text) {
     return getAnnotations(text);
   }
 
+  @SuppressForbidden("user-supplied name finder patterns")
   private Span[] getAnnotations(String text) {
     Collection<Span> annotations = new LinkedList<>();
     if (regexMap != null) {
@@ -170,6 +176,7 @@ public final class RegexNameFinder implements TokenNameFinder {
   /**
    * @return Retrieves the {@link Pattern matching patterns} used.
    */
+  @SuppressForbidden("user-supplied name finder patterns")
   public Pattern[] getMatchingPatterns() {
     return mPatterns;
   }
@@ -177,6 +184,7 @@ public final class RegexNameFinder implements TokenNameFinder {
   /**
    * @param mPatterns The {@link Pattern matching patterns} to be set.
    */
+  @SuppressForbidden("user-supplied name finder patterns")
   public void setMatchingPatterns(Pattern[] mPatterns) {
     this.mPatterns = mPatterns;
   }
diff --git a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinderFactory.java b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinderFactory.java
index 003d94512..b92219e78 100644
--- a/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinderFactory.java
+++ b/opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/namefind/RegexNameFinderFactory.java
@@ -22,6 +22,8 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.regex.Pattern;
 
+import opennlp.tools.commons.SuppressForbidden;
+
 /**
  *
  * Returns a {@link RegexNameFinder} based on a selection of
@@ -89,6 +91,7 @@ public class RegexNameFinderFactory {
 
     USA_PHONE_NUM {
       @Override
+      @SuppressForbidden("default patterns of the regex name finder")
       public Map<String, Pattern[]> getRegexMap() {
         Pattern[] p = new Pattern[1];
         // p[0] = Pattern.compile("([\\+(]?(\\d){2,}[)]?[- \\.]?(\\d){2,}[- \\.]?(\\d){2,}[- \\.]?
@@ -108,6 +111,7 @@ public class RegexNameFinderFactory {
     },
     EMAIL {
       @Override
+      @SuppressForbidden("default patterns of the regex name finder")
       public Map<String, Pattern[]> getRegexMap() {
         Pattern[] p = new Pattern[1];
         // Every quantifier is bounded by a constant, which removes both the exponential
@@ -134,6 +138,7 @@ public class RegexNameFinderFactory {
     },
     URL {
       @Override
+      @SuppressForbidden("default patterns of the regex name finder")
       public Map<String, Pattern[]> getRegexMap() {
         Pattern[] p = new Pattern[1];
         // Flattened to single-level groups and every quantifier bounded by a constant.
@@ -161,6 +166,7 @@ public class RegexNameFinderFactory {
     },
     MGRS {
       @Override
+      @SuppressForbidden("default patterns of the regex name finder")
       public Map<String, Pattern[]> getRegexMap() {
         Pattern[] p = new Pattern[1];
         p[0] = Pattern.compile("\\d{1,2}[A-Za-z]\\s*[A-Za-z]{2}\\s*\\d{1,5}\\s*\\d{1,5}",
@@ -177,6 +183,7 @@ public class RegexNameFinderFactory {
     },
     DEGREES_MIN_SEC_LAT_LON {
       @Override
+      @SuppressForbidden("default patterns of the regex name finder")
       public Map<String, Pattern[]> getRegexMap() {
         Pattern[] p = new Pattern[1];
         p[0] = Pattern.compile("([-|\\+]?\\d{1,3}[d|D|\\u00B0|\\s](\\s*\\d{1,2}['|\\u2019|\\s])" +
diff --git a/pom.xml b/pom.xml
index c16ba104d..d4e389e55 100644
--- a/pom.xml
+++ b/pom.xml
@@ -440,6 +440,25 @@ org.xml.sax.helpers.XMLReaderFactory#createXMLReader(**)
 								<goal>testCheck</goal>
 							</goals>
 						</execution>
+						<execution>
+							<!-- Production classes only: no java.util.regex outside members marked
+							     @opennlp.tools.commons.SuppressForbidden (OPENNLP-1935). -->
+							<id>forbidden-regex-main</id>
+							<phase>process-classes</phase>
+							<goals>
+								<goal>check</goal>
+							</goals>
+							<configuration>
+								<bundledSignatures combine.self="override" />
+								<signatures combine.self="override" />
+								<signaturesFiles>
+									<signaturesFile>${maven.multiModuleProjectDirectory}/dev/forbidden-regex.txt</signaturesFile>
+								</signaturesFiles>
+								<suppressAnnotations>
+									<suppressAnnotation>opennlp.tools.commons.SuppressForbidden</suppressAnnotation>
+								</suppressAnnotations>
+							</configuration>
+						</execution>
 					</executions>
 				</plugin>
 			</plugins>