Package org.bct.api

Class Utils

java.lang.Object
org.bct.api.Utils

class Utils extends Object
Utility class providing common helper methods for testing operations.

This class contains static utility methods that support various testing scenarios including:

  • String formatting and messaging: Methods for formatting messages with parameters
  • Object comparison and validation: Equality checking and argument validation
  • Pattern matching: Wildcard to regex pattern conversion
  • Data conversion: Array to list conversion and Java string escaping
  • Exception handling: Safe execution wrappers and assertion utilities
Usage Examples:

import static org.apache.juneau.junit.bct.Utils.*; // String formatting String msg = f("User {0} has {1} items", "Alice", 5); // String formatting with supplier Supplier<String> msg = fs("User {0} has {1} items", "Alice", 5); // Object validation String validated = assertArgNotNull("username", username); // Pattern matching Pattern pattern = getGlobMatchPattern("user_*_temp");

Thread Safety: All methods in this class are thread-safe as they are stateless static methods.

  • Method Details

    • arrayToList

      public static List<Object> arrayToList(Object o)
      Converts an array to a List of objects.

      This method uses reflection to iterate through array elements and convert them to a list. It works with arrays of any type including primitive arrays.

      Example:

      int[] array = {1, 2, 3}; List<Object> list = arrayToList(array); // list contains [1, 2, 3] as Objects

      Parameters:
      o - The array object to convert. Must be an actual array.
      Returns:
      A new ArrayList containing all array elements as objects.
      Throws:
      IllegalArgumentException - If the object is not an array.
      NullPointerException - If the array parameter is null.
    • assertArg

      public static final void assertArg(boolean expression, String msg, Object... args) throws IllegalArgumentException
      Validates a boolean expression and throws an IllegalArgumentException if false.

      This method provides a convenient way to validate method arguments with descriptive error messages. The message template supports MessageFormat syntax for parameter substitution.

      Example:

      assertArg(age >= 0, "Age must be non-negative but was {0}", age); assertArg(name != null && !name.isEmpty(), "Name cannot be null or empty");

      Parameters:
      expression - The boolean expression to validate.
      msg - The error message template using MessageFormat syntax.
      args - Optional parameters for the message template.
      Throws:
      IllegalArgumentException - If the expression evaluates to false.
    • assertArgNotNull

      public static final <T> T assertArgNotNull(String name, T o) throws IllegalArgumentException
      Validates that an argument is not null and throws an IllegalArgumentException if it is.

      This method provides fluent argument validation by returning the validated argument, allowing it to be used inline in assignment statements.

      Example:

      public void setUsername(String username) { this.username = assertArgNotNull("username", username); }

      Type Parameters:
      T - The argument data type.
      Parameters:
      name - The argument name for error reporting.
      o - The object to validate.
      Returns:
      The same argument if not null.
      Throws:
      IllegalArgumentException - If the argument is null.
    • assertEqualsFailed

      public static org.opentest4j.AssertionFailedError assertEqualsFailed(Object expected, Object actual, Supplier<String> messageSupplier)
      Creates an AssertionFailedError for failed equality assertions.

      This method constructs a properly formatted assertion failure with expected and actual values for use in test frameworks. The message follows JUnit's standard format for assertion failures.

      Example:

      if (ne(expected, actual)) { throw assertEqualsFailed(expected, actual, () -> "Custom context message with arg {0}", arg); }

      Parameters:
      expected - The expected value.
      actual - The actual value that was encountered.
      messageSupplier - Optional supplier for additional context message.
      Returns:
      A new AssertionFailedError with formatted message and values.
    • eq

      public static <T, U> boolean eq(T o1, U o2, BiPredicate<T,U> test)
      Tests two objects for equality using the provided test predicate.

      This method provides null-safe equality testing with custom comparison logic. It handles null values appropriately and checks for reference equality before applying the custom test predicate. This method is primarily designed for implementing equals(Object) methods in a concise and safe manner.

      Example:

      // Implementing equals() method @Override public boolean equals(Object obj) { return (obj instanceof Token other) && eq(this, other, (x,y) -> eq(x.value, y.value) && eq(x.nested, y.nested)); } // Case-insensitive string comparison boolean equal = eq(str1, str2, (s1, s2) -> s1.equalsIgnoreCase(s2));

      Type Parameters:
      T - The type of the first object.
      U - The type of the second object.
      Parameters:
      o1 - The first object to compare.
      o2 - The second object to compare.
      test - The custom equality test predicate.
      Returns:
      true if the objects are equal according to the test predicate.
    • eq

      public static <T> boolean eq(T o1, T o2)
      Tests two objects for equality using Objects.equals(Object, Object).

      This method provides null-safe equality testing using the standard Java equals contract. It's a convenience wrapper around <jsm>Objects.equals</jsm>().

      Example:

      boolean equal = eq("hello", "hello"); // true boolean equal = eq(null, null); // true boolean equal = eq("hello", null); // false

      Type Parameters:
      T - The type of objects to compare.
      Parameters:
      o1 - The first object to compare.
      o2 - The second object to compare.
      Returns:
      true if the objects are equal according to Objects.equals(Object, Object).
    • escapeForJava

      public static String escapeForJava(String s)
      Escapes a string for safe inclusion in Java source code.

      This method converts special characters to their Java escape sequences and converts non-printable ASCII characters to Unicode escape sequences.

      Escape mappings:
      • "\"
      • \\\
      • \n\\n
      • \r\\r
      • \t\\t
      • \f\\f
      • \b\\b
      • Non-printable characters → \\uXXXX
      Example:

      var escaped = escapeForJava("Hello\nWorld\"Test\""); // Returns: "Hello\\nWorld\\\"Test\\\""

      Parameters:
      s - The string to escape.
      Returns:
      The escaped string safe for Java source code.
      Throws:
      NullPointerException - If the string parameter is null.
    • f

      public static String f(String msg, Object... args)
      Formats a message template with parameters using MessageFormat.

      This method provides convenient message formatting with support for various parameter types. If no arguments are provided, the message is returned as-is. Otherwise, it uses MessageFormat.format(String, Object...) for parameter substitution.

      Example:

      var msg = f("User {0} has {1} items", "Alice", 5); // Returns: "User Alice has 5 items" var simple = f("No parameters"); // Returns: "No parameters"

      Parameters:
      msg - The message template with MessageFormat placeholders.
      args - Optional parameters for template substitution.
      Returns:
      The formatted message string.
      Throws:
      IllegalArgumentException - If the message format is invalid.
    • fs

      public static Supplier<String> fs(String msg, Object... args)
      Creates a Supplier that formats a message template with parameters.

      This method returns a supplier that, when called, will format the message using the f(String, Object...) method. This is useful for lazy evaluation of expensive formatting operations.

      Example:

      Supplier<String> msgSupplier = fs("Processing {0} records", recordCount); // Later, when needed: String msg = msgSupplier.get(); // "Processing 150 records"

      Parameters:
      msg - The message template with MessageFormat placeholders.
      args - Optional parameters for template substitution.
      Returns:
      A Supplier that produces the formatted message when called.
    • getGlobMatchPattern

      public static Pattern getGlobMatchPattern(String s)
      Converts a string containing glob-style wildcard characters to a regular expression Pattern.

      This method converts glob-style patterns to regular expressions with the following mappings:

      • * matches any sequence of characters (including none)
      • ? matches exactly one character
      • All other characters are treated literally
      Example:

      var pattern = getGlobMatchPattern("user_*_temp"); boolean matches = pattern.matcher("user_alice_temp").matches(); // true matches = pattern.matcher("user_bob_temp").matches(); // true matches = pattern.matcher("admin_alice_temp").matches(); // false

      Parameters:
      s - The glob-style wildcard pattern string.
      Returns:
      A compiled Pattern object, or null if the input string is null.
    • getGlobMatchPattern

      public static Pattern getGlobMatchPattern(String s, int flags)
      Converts a string containing glob-style wildcard characters to a regular expression Pattern with flags.

      This method converts glob-style patterns to regular expressions with the following mappings:

      • * matches any sequence of characters (including none)
      • ? matches exactly one character
      • All other characters are treated literally
      Example:

      // Case-insensitive matching var pattern = getGlobMatchPattern("USER_*", Pattern.CASE_INSENSITIVE); boolean matches = pattern.matcher("user_alice").matches(); // true

      Parameters:
      s - The glob-style wildcard pattern string.
      flags - Regular expression flags (see Pattern constants).
      Returns:
      A compiled Pattern object, or null if the input string is null.
    • ne

      public static <T> boolean ne(T o1, T o2)
      Tests two objects for inequality using Objects.equals(Object, Object).

      This method is the logical negation of eq(Object, Object). It provides null-safe inequality testing using the standard Java equals contract.

      Example:

      boolean notEqual = ne("hello", "world"); // true boolean notEqual = ne("hello", "hello"); // false boolean notEqual = ne(null, null); // false

      Type Parameters:
      T - The type of objects to compare.
      Parameters:
      o1 - The first object to compare.
      o2 - The second object to compare.
      Returns:
      true if the objects are not equal according to Objects.equals(Object, Object).
    • safe

      public static <T> T safe(ThrowingSupplier<T> s)
      Safely executes a ThrowingSupplier and wraps checked exceptions as RuntimeException.

      This method allows checked exceptions to be handled uniformly by converting them to runtime exceptions. RuntimeExceptions are re-thrown as-is, while checked exceptions are wrapped in a new RuntimeException. Typically used in situations where you want to embed code that throws checked exceptions inside fluent chained method calls.

      Example:

      // Safe file reading without explicit exception handling var content = safe(() -> Files.readString(Paths.get("file.txt"))); // Safe URL connection var response = safe(() -> { URL url = new URL("http://example.com"); return url.openConnection().getInputStream().readAllBytes(); });

      Type Parameters:
      T - The return type of the supplier.
      Parameters:
      s - The ThrowingSupplier to execute safely.
      Returns:
      The result of the supplier execution.
      Throws:
      RuntimeException - If the supplier throws any checked exception.
    • t

      public static String t(Object o)
      Returns the simple class name of an object, or null if the object is null.

      This method provides a safe way to get type information for debugging and logging. It handles null values gracefully by returning null instead of throwing an exception.

      Example:

      var type = t("hello"); // "String" type = vart(new ArrayList()); // "ArrayList" type = t(null); // null

      Parameters:
      o - The object to get the type name for.
      Returns:
      The simple class name of the object, or null if the object is null.
    • tokenize

      public static List<NestedTokenizer.Token> tokenize(String fields)
      Tokenizes a string into a list of NestedTokenizer.Token objects.

      This method delegates to NestedTokenizer.tokenize(String) to parse structured field strings into tokens. It's commonly used for parsing field lists and nested property expressions.

      Example:

      var tokens = tokenize("name,address{street,city},age"); // Parses nested field expressions

      Parameters:
      fields - The field string to tokenize.
      Returns:
      A list of parsed tokens.
      See Also:
    • safeToString

      public static String safeToString(Object o)
      Safely converts an object to its string representation, handling any exceptions that may occur.

      This method provides a fail-safe way to call toString() on any object, ensuring that exceptions thrown by problematic toString() implementations don't propagate up the call stack. Instead, it returns a descriptive error message containing the exception type and message.

      Exception Handling:

      If the object's toString() method throws any Throwable, this method catches it and returns a formatted string in the form: "<ExceptionType>: <exception message>".

      Examples:

      // Normal case - returns object's toString() result String result = safeToString("Hello"); // result = "Hello" // Exception case - returns formatted error message Object problematic = new Object() { @Override public String toString() { throw new RuntimeException("Cannot convert"); } }; String result = safeToString(problematic); // result = "RuntimeException: Cannot convert"

      Use Cases:
      • Object stringification in converters: Safe conversion of arbitrary objects to strings
      • Debugging and logging: Ensures log statements never fail due to toString() exceptions
      • Error handling: Graceful degradation when objects have problematic string representations
      • Third-party object integration: Safe handling of objects from external libraries
      Parameters:
      o - The object to convert to a string. May be any object including null.
      Returns:
      The string representation of the object, or a formatted error message if toString() throws an exception. Returns "null" if the object is null.