You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2026/07/01 01:48:00 UTC
(juneau) branch master updated: Add resource-level RestAuthenticator; SonarQube, regex, and TestUtils cleanup
This is an automated email from the ASF dual-hosted git repository.
jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git
The following commit(s) were added to refs/heads/master by this push:
new f925cfecd6 Add resource-level RestAuthenticator; SonarQube, regex, and TestUtils cleanup
f925cfecd6 is described below
commit f925cfecd6ad9e4fbcb5677a839302fdac3550bc
Author: James Bognar <ja...@apache.org>
AuthorDate: Tue Jun 30 21:47:53 2026 -0400
Add resource-level RestAuthenticator; SonarQube, regex, and TestUtils cleanup
- Add RestAuthenticator SPI and @Rest(authenticator) with AuthResult merge modes (ADD/REPLACE), docs, and full test coverage.
- Consolidate duplicated TestUtils helpers into a shared XmlTestUtils and remove dead helper methods across modules.
- Fix or suppress a large batch of SonarQube issues across core, rest, microservice, and bean modules.
- Replace backtracking regexes with linear state machines in Iso8601Utils (parseDuration/parsePeriod), HttpPartSchema validators, DurationFormat, and Hjson/Hocon/Ini number parsing; cache compiled SVL Patterns.
- Fix MockRestClient default parser gap, EphemeralJettyServerConfig stop timeout, and update perf baselines.
- Documentation cleanup (Marshalling overview, SVL variables, sidebar ordering).
---
.../src/test/java/org/apache/juneau/TestUtils.java | 312 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 313 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 313 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 316 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 302 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 302 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 316 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 313 ----------------
.../src/test/java/org/apache/juneau/TestUtils.java | 302 +---------------
.../src/test/java/org/apache/juneau/TestUtils.java | 294 +--------------
.../juneau/assertions/FluentDateAssertion.java | 3 +-
.../src/test/java/org/apache/juneau/TestUtils.java | 293 +--------------
.../org/apache/juneau/commons/runtime/Args.java | 4 +-
.../commons/settings/RelaxedPropertySource.java | 6 +-
.../svl/functions/ConditionalFunctions.java | 10 +-
.../commons/svl/functions/RegexFunctions.java | 12 +-
.../apache/juneau/commons/utils/StringUtils.java | 69 +++-
.../org/apache/juneau/commons/io/Console_Test.java | 8 +-
.../juneau/commons/utils/DateUtils_Test.java | 3 +-
.../src/test/java/org/apache/juneau/TestUtils.java | 282 +--------------
.../src/test/java/org/apache/juneau/TestUtils.java | 306 +---------------
.../apache/juneau/a/rttests/RoundTrip_Tester.java | 1 +
.../juneau/marshaller/CharRdfMarshallers_Test.java | 6 +
.../org/apache/juneau/marshall/DurationFormat.java | 62 +++-
.../marshall/MarshalledConfigAnnotation.java | 3 +
.../juneau/marshall/hjson/HjsonTokenizer.java | 11 +-
.../juneau/marshall/hocon/HoconTokenizer.java | 11 +-
.../marshall/html/HtmlSerializerSession.java | 21 +-
.../juneau/marshall/httppart/HttpPartSchema.java | 398 +++++++++++++++++++--
.../juneau/marshall/ini/IniParserSession.java | 36 +-
.../juneau/marshall/ini/IniSerializerSession.java | 4 +-
.../juneau/marshall/jcs/JcsSerializerSession.java | 15 +-
.../juneau/marshall/json5l/Json5lSerializer.java | 3 +-
.../marshall/markdown/MarkdownParserSession.java | 8 +-
.../marshall/parquet/SnappyBlockDecompressor.java | 4 +
.../marshall/protobuf/ProtobufClassMeta.java | 3 +
.../marshall/protobuf/ProtobufFieldEntry.java | 3 +
.../marshall/protobuf/ProtobufParserSession.java | 3 +-
.../marshall/protobuf/ProtobufSerializer.java | 3 +-
.../protobuf/ProtobufSerializerSession.java | 3 +-
.../marshall/serializer/SerializerSession.java | 3 +-
.../juneau/marshall/uon/UonParserSession.java | 1 +
.../apache/juneau/marshall/utils/Iso8601Utils.java | 154 +++++++-
.../juneau/marshall/xml/XmlParserSession.java | 2 +-
.../src/test/java/org/apache/juneau/TestUtils.java | 195 +---------
.../apache/juneau/a/rttests/RoundTrip_Tester.java | 1 +
.../java/org/apache/juneau/cp/FileFinder_Test.java | 136 +++----
.../markdown/MarkdownParserSession_Test.java | 4 +-
.../juneau/marshall/AnnotationWorkList_Test.java | 4 +-
.../marshall/BeanCtorApplyAnnotation_Test.java | 3 +-
.../marshall/BeanIgnoreApplyAnnotation_Test.java | 3 +-
.../marshall/BeanTypeApplyAnnotation_Test.java | 3 +-
.../marshall/ExampleApplyAnnotation_Test.java | 3 +-
.../marshall/MarshalledApplyAnnotation_Test.java | 3 +-
.../MarshalledIgnoreApplyAnnotation_Test.java | 3 +-
.../MarshalledPropApplyAnnotation_Test.java | 3 +-
.../juneau/marshall/SwapApplyAnnotation_Test.java | 3 +-
.../juneau/marshall/UriApplyAnnotation_Test.java | 3 +-
.../marshall/bson/BsonApplyAnnotation_Test.java | 3 +-
.../marshall/cbor/CborApplyAnnotation_Test.java | 3 +-
.../marshall/collections/JsonPointer_Test.java | 6 +-
.../marshall/collections/MarshalledNode_Test.java | 21 +-
.../marshall/csv/CsvApplyAnnotation_Test.java | 3 +-
.../marshall/hjson/HjsonApplyAnnotation_Test.java | 3 +-
.../marshall/hocon/HoconApplyAnnotation_Test.java | 3 +-
.../marshall/html/HtmlApplyAnnotation_Test.java | 3 +-
.../html/HtmlLinkApplyAnnotation_Test.java | 3 +-
.../marshall/html/HtmlParserSession_Test.java | 2 +-
.../marshall/ini/IniApplyAnnotation_Test.java | 3 +-
.../marshall/internal/DelegateList_Test.java | 6 +-
.../marshall/json/JsonApplyAnnotation_Test.java | 3 +-
.../json/JsonTokenReaderCoverage_Test.java | 8 +-
.../json/JsonTokenReaderSupplemental_Test.java | 8 +-
.../jsonschema/SchemaApplyAnnotation_Test.java | 3 +-
.../markdown/MarkdownApplyAnnotation_Test.java | 3 +-
.../markdown/MarkdownParserSession_Test.java | 81 ++---
.../marshall/markdown/MarkdownSerializer_Test.java | 28 +-
.../marshaller/MarshallerStreamShortcuts_Test.java | 3 +-
.../msgpack/MsgPackApplyAnnotation_Test.java | 3 +-
.../marshall/msgpack/MsgPackConformance_Test.java | 2 +-
.../marshall/oapi/OpenApiApplyAnnotation_Test.java | 3 +-
.../marshall/parquet/ParquetColumnReader_Test.java | 5 +-
.../plaintext/PlainTextApplyAnnotation_Test.java | 3 +-
.../protobuf/ProtobufApplyAnnotation_Test.java | 3 +-
.../marshall/protobuf/ProtobufCoverage_Test.java | 14 +-
.../marshall/protobuf/ProtobufEdgeCases_Test.java | 4 +-
.../marshall/protobuf/ProtobufRoundTrip_Test.java | 2 +-
.../marshall/protobuf/ProtobufSwap_Test.java | 2 +-
.../prototext/PrototextApplyAnnotation_Test.java | 3 +-
.../prototext/PrototextTokenizer_Test.java | 9 +-
.../marshall/soap/SoapXmlApplyAnnotation_Test.java | 3 +-
.../marshall/stream/ArrayRecordStream_Test.java | 9 +-
.../BinaryNativeKind_GenericConsumer_Test.java | 6 +-
.../stream/FormatStreamingCapability_Test.java | 2 +-
.../juneau/marshall/stream/RecordStream_Test.java | 6 +-
.../marshall/stream/StreamInternals_Test.java | 26 +-
.../juneau/marshall/toml/TomlTokenizer_Test.java | 54 ++-
.../marshall/uon/UonApplyAnnotation_Test.java | 3 +-
.../UrlEncodingApplyAnnotation_Test.java | 3 +-
.../juneau/marshall/utils/Iso8601Utils_Test.java | 128 +++++++
.../marshall/xml/XmlApplyAnnotation_Test.java | 3 +-
.../main/java/org/apache/juneau/XmlTestUtils.java | 141 ++++++++
.../src/test/java/org/apache/juneau/TestUtils.java | 295 +--------------
.../apache/juneau/a/rttests/RoundTrip_Tester.java | 1 +
.../RestContext_ValueAgainstConfig_Test.java | 20 +-
.../microservice/jetty/JettyServerComponent.java | 4 +
.../jetty/JettyGracefulShutdown_Test.java | 2 +-
.../test/EphemeralJettyServerConfig.java | 21 ++
.../src/main/resources/htdocs/petstore-ui.html | 6 +-
.../juneau/rest/client/remote/RemoteClient.java | 3 +
.../src/test/java/org/apache/juneau/TestUtils.java | 293 +--------------
.../juneau/http/remote/RrpcInterfaceMeta.java | 5 +-
.../src/test/java/org/apache/juneau/TestUtils.java | 302 +---------------
.../apache/juneau/rest/mock/MockRestClient.java | 42 ++-
.../org/apache/juneau/rest/server/RestSession.java | 30 +-
.../juneau/rest/server/arg/TokenWriterArg.java | 4 +-
.../apache/juneau/rest/server/auth/AuthFilter.java | 18 -
.../src/test/java/org/apache/juneau/TestUtils.java | 17 -
.../rest/server/arg/RestArgResolvers_Test.java | 37 +-
.../rest/server/auth/AuthFilterChain_Test.java | 20 +-
.../rest/server/auth/RestAuthenticator_Test.java | 11 +-
perf-baseline.txt | 15 +-
122 files changed, 1491 insertions(+), 5492 deletions(-)
diff --git a/juneau-bean/juneau-bean-atom/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-atom/src/test/java/org/apache/juneau/TestUtils.java
index 5f29a3e730..cebb4611ac 100644
--- a/juneau-bean/juneau-bean-atom/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-atom/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,310 +27,12 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
public static String json(Object o) {
return json5(o);
}
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-common/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-common/src/test/java/org/apache/juneau/TestUtils.java
index b0dc9c0409..5f4a3316d4 100644
--- a/juneau-bean/juneau-bean-common/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-common/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,307 +27,8 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-hal/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-hal/src/test/java/org/apache/juneau/TestUtils.java
index b0dc9c0409..5f4a3316d4 100644
--- a/juneau-bean/juneau-bean-hal/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-hal/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,307 +27,8 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-html5/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-html5/src/test/java/org/apache/juneau/TestUtils.java
index 5f29a3e730..5f4a3316d4 100644
--- a/juneau-bean/juneau-bean-html5/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-html5/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,310 +27,8 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-jsonapi/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-jsonapi/src/test/java/org/apache/juneau/TestUtils.java
index 6ddeb0f405..5f4a3316d4 100644
--- a/juneau-bean/juneau-bean-jsonapi/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-jsonapi/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,296 +27,8 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked" // BeanTester cast and generic type handling in test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(String expectedSubstring, T t) {
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-jsonpatch/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-jsonpatch/src/test/java/org/apache/juneau/TestUtils.java
index 6ddeb0f405..5f4a3316d4 100644
--- a/juneau-bean/juneau-bean-jsonpatch/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-jsonpatch/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,296 +27,8 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked" // BeanTester cast and generic type handling in test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(String expectedSubstring, T t) {
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-jsonschema/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-jsonschema/src/test/java/org/apache/juneau/TestUtils.java
index 5f29a3e730..5f4a3316d4 100644
--- a/juneau-bean/juneau-bean-jsonschema/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-jsonschema/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,310 +27,8 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-mcp/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-mcp/src/test/java/org/apache/juneau/TestUtils.java
index b0dc9c0409..5f4a3316d4 100644
--- a/juneau-bean/juneau-bean-mcp/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-mcp/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,10 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,307 +27,8 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
public static String assertJson(String expected, Object value) {
assertEquals(expected, json5(value));
return expected;
diff --git a/juneau-bean/juneau-bean-openapi-v3/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-openapi-v3/src/test/java/org/apache/juneau/TestUtils.java
index 742a36e973..7d3196482e 100644
--- a/juneau-bean/juneau-bean-openapi-v3/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-openapi-v3/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,22 +17,12 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
import org.junit.jupiter.api.*;
/**
@@ -42,47 +32,13 @@ import org.junit.jupiter.api.*;
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
+ "unchecked" // BeanTester cast and generic type handling in test utilities
})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
}
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
@@ -92,261 +48,11 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
public static final <T> BeanTester<T> testBean(T bean) {
return (BeanTester<T>) new BeanTester<>().bean(bean);
}
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
- }
}
diff --git a/juneau-bean/juneau-bean-swagger-v2/src/test/java/org/apache/juneau/TestUtils.java b/juneau-bean/juneau-bean-swagger-v2/src/test/java/org/apache/juneau/TestUtils.java
index 742a36e973..ca0f9e76a8 100644
--- a/juneau-bean/juneau-bean-swagger-v2/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-bean/juneau-bean-swagger-v2/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,22 +17,12 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
import org.junit.jupiter.api.*;
/**
@@ -42,47 +32,13 @@ import org.junit.jupiter.api.*;
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
+ "unchecked" // BeanTester cast and generic type handling in test utilities
})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
}
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
@@ -92,131 +48,10 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
public static String json(Object o) {
return json5(o);
}
@@ -225,128 +60,7 @@ public class TestUtils extends Utils {
return safe(()->json5(o, c));
}
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
public static final <T> BeanTester<T> testBean(T bean) {
return (BeanTester<T>) new BeanTester<>().bean(bean);
}
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
- }
}
diff --git a/juneau-core/juneau-assertions/src/main/java/org/apache/juneau/assertions/FluentDateAssertion.java b/juneau-core/juneau-assertions/src/main/java/org/apache/juneau/assertions/FluentDateAssertion.java
index ea2339d466..31d60a2c66 100644
--- a/juneau-core/juneau-assertions/src/main/java/org/apache/juneau/assertions/FluentDateAssertion.java
+++ b/juneau-core/juneau-assertions/src/main/java/org/apache/juneau/assertions/FluentDateAssertion.java
@@ -122,7 +122,8 @@ import org.apache.juneau.marshall.serializer.*;
*/
@SuppressWarnings({
"java:S115", // Constants use UPPER_snakeCase convention
- "java:S6350" // Public assertion API is built on java.util.Date by design (all method signatures take/return Date); cannot swap to java.time without breaking API.
+ "java:S6350", // Public assertion API is built on java.util.Date by design (all method signatures take/return Date); cannot swap to java.time without breaking API.
+ "java:S2143" // Public assertion API is built on java.util.Date by design (signatures take/return Date, extends FluentComparableAssertion<Date,R>); cannot swap to java.time without breaking the assertion API.
})
public class FluentDateAssertion<R> extends FluentComparableAssertion<Date,R> {
diff --git a/juneau-core/juneau-assertions/src/test/java/org/apache/juneau/TestUtils.java b/juneau-core/juneau-assertions/src/test/java/org/apache/juneau/TestUtils.java
index d742ff594a..b7dc904e6e 100644
--- a/juneau-core/juneau-assertions/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-core/juneau-assertions/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,22 +17,13 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
import org.junit.jupiter.api.*;
/**
@@ -41,48 +32,11 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
}
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
@@ -92,121 +46,6 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112", // Generic exception throw required; checked exception wrapping would obscure test intent.
- "java:S5852" // Regex backtracking: patterns are bounded by XML line structure; catastrophic backtracking is not possible in practice.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
@@ -218,136 +57,10 @@ public class TestUtils extends Utils {
return new ByteArrayInputStream(in.getBytes());
}
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
/**
* Creates a reader from the specified string.
*/
public static final StringReader reader(String in) {
return new StringReader(in);
}
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
- }
}
diff --git a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/runtime/Args.java b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/runtime/Args.java
index 60c8061c55..b785cbbe42 100644
--- a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/runtime/Args.java
+++ b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/runtime/Args.java
@@ -22,6 +22,8 @@ import static org.apache.juneau.commons.utils.Utils.*;
import java.util.*;
+import org.apache.juneau.commons.utils.Utils;
+
/**
* Lean parser for command-line arguments passed in through a {@code main(String[] args)} method.
*
@@ -379,7 +381,7 @@ public class Args {
if (allowShortFlags)
p.add("-");
}
- p.removeIf(x -> e(x));
+ p.removeIf(Utils::e);
p.sort((a,b) -> Integer.compare(b.length(), a.length()));
return p;
}
diff --git a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/settings/RelaxedPropertySource.java b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/settings/RelaxedPropertySource.java
index e7100904ee..0349ba7b43 100644
--- a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/settings/RelaxedPropertySource.java
+++ b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/settings/RelaxedPropertySource.java
@@ -113,13 +113,13 @@ public class RelaxedPropertySource implements PropertySource {
var c = name.charAt(i);
if (! Character.isLetterOrDigit(c)) {
// Separator (., -, /, _, space, …): flush the current token.
- if (sb.length() > 0) {
+ if (! sb.isEmpty()) {
tokens.add(sb.toString());
sb.setLength(0);
}
} else {
// camelCase boundary: lower/digit followed by upper starts a new token.
- if (sb.length() > 0 && Character.isUpperCase(c) && (Character.isLowerCase(prev) || Character.isDigit(prev))) {
+ if (! sb.isEmpty() && Character.isUpperCase(c) && (Character.isLowerCase(prev) || Character.isDigit(prev))) {
tokens.add(sb.toString());
sb.setLength(0);
}
@@ -127,7 +127,7 @@ public class RelaxedPropertySource implements PropertySource {
}
prev = c;
}
- if (sb.length() > 0)
+ if (! sb.isEmpty())
tokens.add(sb.toString());
return tokens;
}
diff --git a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/ConditionalFunctions.java b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/ConditionalFunctions.java
index 7f35da6117..042909c591 100644
--- a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/ConditionalFunctions.java
+++ b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/ConditionalFunctions.java
@@ -18,6 +18,9 @@ package org.apache.juneau.commons.svl.functions;
import static org.apache.juneau.commons.utils.StringUtils.*;
+import java.util.regex.*;
+
+import org.apache.juneau.commons.collections.*;
import org.apache.juneau.commons.svl.*;
/**
@@ -78,6 +81,11 @@ public final class ConditionalFunctions {
* </ul>
*/
public static class Switch extends TypedFunction {
+
+ // Compiled glob-derived regexes are cached and reused. Bounded (entire cache cleared past maxSize) to guard
+ // against unbounded growth from arbitrary user-supplied glob patterns. Pattern is immutable/thread-safe.
+ private static final Cache<String,Pattern> PATTERN_CACHE = Cache.of(String.class, Pattern.class).maxSize(1000).supplier(Pattern::compile).build();
+
@Override public String name() { return "switch"; }
public String invoke(String[] args) {
if (args.length == 0) return "";
@@ -107,7 +115,7 @@ public final class ConditionalFunctions {
default -> sb.append(c);
}
}
- return java.util.regex.Pattern.compile(sb.toString()).matcher(value).matches();
+ return PATTERN_CACHE.get(sb.toString()).matcher(value).matches();
}
}
diff --git a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/RegexFunctions.java b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/RegexFunctions.java
index b52052f59e..a1982113ae 100644
--- a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/RegexFunctions.java
+++ b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/svl/functions/RegexFunctions.java
@@ -18,6 +18,7 @@ package org.apache.juneau.commons.svl.functions;
import java.util.regex.*;
+import org.apache.juneau.commons.collections.*;
import org.apache.juneau.commons.svl.*;
/**
@@ -35,6 +36,11 @@ public final class RegexFunctions {
private RegexFunctions() {}
+ // User-supplied regexes are compiled once and reused. Bounded (entire cache cleared past maxSize) to guard
+ // against unbounded growth from arbitrary user input. Pattern is immutable/thread-safe; a fresh Matcher is
+ // created per invocation, so behavior is identical to compiling on every call.
+ private static final Cache<String,Pattern> PATTERN_CACHE = Cache.of(String.class, Pattern.class).maxSize(1000).supplier(Pattern::compile).build();
+
/** All function classes in this category. */
@SuppressWarnings({
"unchecked", // Cast is safe: type verified by caller context.
@@ -49,7 +55,7 @@ public final class RegexFunctions {
@Override public String name() { return "match"; }
public String invoke(String s, String regex) {
if (s == null || regex == null) return "false";
- return String.valueOf(Pattern.compile(regex).matcher(s).find());
+ return String.valueOf(PATTERN_CACHE.get(regex).matcher(s).find());
}
}
@@ -63,7 +69,7 @@ public final class RegexFunctions {
public String invoke(String s, String regex) { return invoke(s, regex, 0); }
public String invoke(String s, String regex, int group) {
if (s == null || regex == null) return "";
- var m = Pattern.compile(regex).matcher(s);
+ var m = PATTERN_CACHE.get(regex).matcher(s);
if (!m.find()) return "";
if (group < 0 || group > m.groupCount()) return "";
var v = m.group(group);
@@ -77,7 +83,7 @@ public final class RegexFunctions {
public String invoke(String s, String regex, String replacement) {
if (s == null) return "";
if (regex == null) return s;
- return Pattern.compile(regex).matcher(s).replaceAll(replacement == null ? "" : replacement);
+ return PATTERN_CACHE.get(regex).matcher(s).replaceAll(replacement == null ? "" : replacement);
}
}
}
diff --git a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/utils/StringUtils.java b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/utils/StringUtils.java
index 27bb2b5d72..39cb4b0b14 100644
--- a/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/utils/StringUtils.java
+++ b/juneau-core/juneau-commons/src/main/java/org/apache/juneau/commons/utils/StringUtils.java
@@ -1794,7 +1794,7 @@ public class StringUtils {
var result = new ArrayList<String>();
// Email regex pattern (same as isEmail but without ^ and $ anchors)
- var pattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
+ var pattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z]{2,}");
var matcher = pattern.matcher(str);
while (matcher.find()) {
result.add(matcher.group());
@@ -3234,6 +3234,71 @@ public class StringUtils {
return true;
}
+ /**
+ * Scans the longest prefix of the specified string that matches the JSON-style number grammar.
+ *
+ * <p>
+ * Hand-written equivalent (greedy, anchored at the start of the string) of one of:
+ * <ul>
+ * <li>{@code -?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?} when {@code allowLeadingZeros} is <jk>false</jk>
+ * (integer part restricted to {@code 0} or a non-zero-leading run), or
+ * <li>{@code -?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?} when {@code allowLeadingZeros} is <jk>true</jk>
+ * (integer part is any run of one or more digits).
+ * </ul>
+ *
+ * <p>
+ * {@code \d} matches ASCII {@code [0-9]} only. To emulate a {@code matches()} (whole-string) check, test the
+ * return value against {@code s.length()}.
+ *
+ * @param s The string to scan. Must not be <jk>null</jk>.
+ * @param allowLeadingZeros Whether the integer part may contain leading zeros.
+ * @return The length of the matched prefix, or {@code -1} if the string does not start with a valid number.
+ */
+ public static int matchNumberPrefix(String s, boolean allowLeadingZeros) {
+ var len = s.length();
+ var i = 0;
+ if (i < len && s.charAt(i) == '-')
+ i++;
+ // Integer part (required).
+ if (i >= len)
+ return -1;
+ var c = s.charAt(i);
+ if (allowLeadingZeros) {
+ if (c < '0' || c > '9')
+ return -1;
+ i++;
+ while (i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9')
+ i++;
+ } else if (c == '0') {
+ i++;
+ } else if (c >= '1' && c <= '9') {
+ i++;
+ while (i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9')
+ i++;
+ } else {
+ return -1;
+ }
+ // Optional fraction (?:\.\d+)? - the '.' requires at least one following digit, else not consumed.
+ if (i < len && s.charAt(i) == '.' && i + 1 < len && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') {
+ i += 2;
+ while (i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9')
+ i++;
+ }
+ // Optional exponent (?:[eE][+-]?\d+)? - consumed only when a digit follows e/E and the optional sign.
+ if (i < len && (s.charAt(i) == 'e' || s.charAt(i) == 'E')) {
+ var j = i + 1;
+ if (j < len && (s.charAt(j) == '+' || s.charAt(j) == '-'))
+ j++;
+ if (j < len && s.charAt(j) >= '0' && s.charAt(j) <= '9') {
+ j++;
+ while (j < len && s.charAt(j) >= '0' && s.charAt(j) <= '9')
+ j++;
+ i = j;
+ }
+ }
+ return i;
+ }
+
/**
* Checks if a string contains only digit characters (0-9).
*
@@ -3283,7 +3348,7 @@ public class StringUtils {
// Basic email regex: local@domain
// Allows letters, digits, dots, underscores, hyphens, and plus signs in local part
// Domain must have at least one dot and valid TLD
- return str.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
+ return str.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z]{2,}$");
}
/**
diff --git a/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/io/Console_Test.java b/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/io/Console_Test.java
index 50a9894d88..ef9c450051 100644
--- a/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/io/Console_Test.java
+++ b/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/io/Console_Test.java
@@ -116,7 +116,7 @@ class Console_Test extends TestBase {
var output = outCapture.toString();
assertTrue(output.contains("Value:"), output);
// MessageFormat may add locale-specific formatting (e.g., commas), so check for digits
- assertTrue(output.matches("(?s).*Value:.*[0-9].*"),
+ assertTrue(output.contains("Value:") && output.chars().anyMatch(Character::isDigit),
"Output should contain 'Value:' and at least one digit. Actual: " + output);
}
@@ -133,7 +133,7 @@ class Console_Test extends TestBase {
var output = outCapture.toString();
assertTrue(output.contains("Number:"), output);
// MessageFormat may add locale-specific formatting (e.g., commas), so check for digits
- assertTrue(output.matches("(?s).*Number:.*[0-9].*"),
+ assertTrue(output.contains("Number:") && output.chars().anyMatch(Character::isDigit),
"Output should contain 'Number:' and at least one digit. Actual: " + output);
}
@@ -204,7 +204,7 @@ class Console_Test extends TestBase {
var output = errCapture.toString();
assertTrue(output.contains("Error:"), output);
// MessageFormat may add locale-specific formatting (e.g., commas), so check for digits
- assertTrue(output.matches("(?s).*Error:.*[0-9].*"),
+ assertTrue(output.contains("Error:") && output.chars().anyMatch(Character::isDigit),
"Output should contain 'Error:' and at least one digit. Actual: " + output);
}
@@ -221,7 +221,7 @@ class Console_Test extends TestBase {
var output = errCapture.toString();
assertTrue(output.contains("Number:"), output);
// MessageFormat may add locale-specific formatting (e.g., commas), so check for digits
- assertTrue(output.matches("(?s).*Number:.*[0-9].*"),
+ assertTrue(output.contains("Number:") && output.chars().anyMatch(Character::isDigit),
"Output should contain 'Number:' and at least one digit. Actual: " + output);
}
diff --git a/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/utils/DateUtils_Test.java b/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/utils/DateUtils_Test.java
index de0ff1c22c..cfc55e424d 100644
--- a/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/utils/DateUtils_Test.java
+++ b/juneau-core/juneau-commons/src/test/java/org/apache/juneau/commons/utils/DateUtils_Test.java
@@ -18,6 +18,7 @@ package org.apache.juneau.commons.utils;
import static org.junit.jupiter.api.Assertions.*;
+import java.time.Month;
import java.time.format.*;
import org.apache.juneau.commons.*;
@@ -61,7 +62,7 @@ class DateUtils_Test extends TestBase {
var fmt = DateUtils.getDateTimeFormatter("yyyy-MM-dd");
assertNotNull(fmt);
// Verify it actually formats a date without throwing
- var formatted = fmt.format(java.time.LocalDate.of(2024, 1, 15).atStartOfDay(java.time.ZoneOffset.UTC));
+ var formatted = fmt.format(java.time.LocalDate.of(2024, Month.JANUARY, 15).atStartOfDay(java.time.ZoneOffset.UTC));
assertTrue(formatted.startsWith("2024-01-15"), "Expected formatted date to start with '2024-01-15' but was: " + formatted);
}
diff --git a/juneau-core/juneau-config/src/test/java/org/apache/juneau/TestUtils.java b/juneau-core/juneau-config/src/test/java/org/apache/juneau/TestUtils.java
index 35a32a45396..a1e381a0c8 100644
--- a/juneau-core/juneau-config/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-core/juneau-config/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,22 +17,15 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
import java.io.*;
-import java.lang.reflect.*;
import java.net.*;
import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
import org.junit.jupiter.api.*;
/**
@@ -41,39 +34,11 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172", // Parameters kept for consistent method signatures across test utilities
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
}
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
@@ -90,141 +55,12 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
+ public static String pipedLines(Object value) {
+ return r(value).replaceAll("\\r?\\n", "|");
}
/**
@@ -234,118 +70,10 @@ public class TestUtils extends Utils {
return new StringReader(in);
}
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
/**
* Constructs a {@link URL} object from a string.
*/
public static URL url(String value) {
return safe(()->new URI(value).toURL());
}
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
- }
-
- public static String pipedLines(Object value) {
- return r(value).replaceAll("\\r?\\n", "|");
- }
}
diff --git a/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/TestUtils.java b/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/TestUtils.java
index 57f39a4083..f7b7cac18d 100644
--- a/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/TestUtils.java
@@ -16,24 +16,11 @@
*/
package org.apache.juneau;
-import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
-import java.util.stream.*;
-
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
import org.apache.juneau.marshall.xml.*;
-import org.junit.jupiter.api.*;
/**
* Test utilities for the juneau-marshall module.
@@ -41,238 +28,11 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172", // Parameters kept for consistent method signatures across test utilities
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return exception;
- }
-
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^\\s/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^\\s>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>[^<]*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
- private static String getMessages(Throwable t) {
- return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
- }
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
}
/**
@@ -284,64 +44,6 @@ public class TestUtils extends Utils {
public static final void validateXml(Object o, XmlSerializer s) throws Exception {
s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
+ XmlTestUtils.checkXmlWhitespace(xml);
}
}
diff --git a/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java b/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
index 0f9642e3b9..263f5f9945 100644
--- a/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
+++ b/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
@@ -18,6 +18,7 @@ package org.apache.juneau.a.rttests;
import static java.util.Collections.*;
import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.XmlTestUtils.*;
import static org.apache.juneau.commons.utils.CollectionUtils.*;
import static org.apache.juneau.commons.utils.StringUtils.*;
import java.lang.reflect.*;
diff --git a/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/marshaller/CharRdfMarshallers_Test.java b/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/marshaller/CharRdfMarshallers_Test.java
index c36aa44249..ea1dec2a7e 100644
--- a/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/marshaller/CharRdfMarshallers_Test.java
+++ b/juneau-core/juneau-marshall-rdf/src/test/java/org/apache/juneau/marshaller/CharRdfMarshallers_Test.java
@@ -105,6 +105,8 @@ class CharRdfMarshallers_Test extends TestBase {
@Test void a12_nquads_of_string_writer() throws Exception {
var sw = new StringWriter();
NQuads.DEFAULT.of("foo", sw);
+ // NQuads embeds a random blank-node id, so assert on the stable value triple rather than comparing two independent serializations.
+ assertTrue(sw.toString().contains("<http://www.apache.org/juneau/value> \"foo\" ."), sw.toString());
}
@Test void a13_nquads_roundtrip_string() throws Exception {
@@ -267,6 +269,7 @@ class CharRdfMarshallers_Test extends TestBase {
@Test void a37_trig_of_string_writer() throws Exception {
var sw = new StringWriter();
TriG.DEFAULT.of("foo", sw);
+ assertEquals(TriG.DEFAULT.of("foo"), sw.toString());
}
@Test void a38_trig_roundtrip_string() throws Exception {
@@ -297,6 +300,9 @@ class CharRdfMarshallers_Test extends TestBase {
@Test void a42_trix_of_string_writer() throws Exception {
var sw = new StringWriter();
TriX.DEFAULT.of("foo", sw);
+ // TriX embeds a random <id> per triple, so assert on the stable uri/plainLiteral content rather than comparing two independent serializations.
+ var out = sw.toString();
+ assertTrue(out.contains("<uri>http://www.apache.org/juneau/value</uri>") && out.contains("<plainLiteral>foo</plainLiteral>"), out);
}
@Test void a43_trix_roundtrip_string() throws Exception {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/DurationFormat.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/DurationFormat.java
index 4223ebb47d..00b105239a 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/DurationFormat.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/DurationFormat.java
@@ -18,7 +18,6 @@ package org.apache.juneau.marshall;
import java.math.*;
import java.time.*;
-import java.util.regex.*;
/**
* Supported wire formats for {@link Duration} values.
@@ -33,7 +32,6 @@ public enum DurationFormat {
SECONDS,
HOCON;
- private static final Pattern HOCON_PATTERN = Pattern.compile("^([+-]?\\d+(?:\\.\\d+)?)(ns|us|ms|s|m|h|d)$", Pattern.CASE_INSENSITIVE);
private static final BigDecimal NANOS_PER_SECOND = BigDecimal.valueOf(1_000_000_000L);
/**
@@ -132,7 +130,7 @@ public enum DurationFormat {
if (minutes > 0)
sb.append(minutes).append('M');
if (seconds > 0 || nanos > 0 || (hours == 0 && minutes == 0))
- sb.append(seconds).append(nanos == 0 ? "" : "." + String.format("%09d", nanos).replaceAll("0++$", "")).append('S');
+ sb.append(seconds).append(nanos == 0 ? "" : "." + trimTrailingZeros(String.format("%09d", nanos))).append('S');
}
return sb.toString();
}
@@ -154,21 +152,51 @@ public enum DurationFormat {
}
private static Duration parseHocon(String s) {
- Matcher m = HOCON_PATTERN.matcher(s);
- if (! m.matches())
+ // Programmatic equivalent of full match ^([+-]?\d++(?:\.\d++)?)(ns|us|ms|s|m|h|d)$ (CASE_INSENSITIVE) to avoid per-parse matching.
+ // Group 1 = the numeric part, group 2 = the (case-insensitive) unit suffix. \d = ASCII [0-9].
+ var len = s.length();
+ var i = 0;
+ if (i < len && (s.charAt(i) == '+' || s.charAt(i) == '-'))
+ i++;
+ var digitsStart = i;
+ while (i < len && isAsciiDigit(s.charAt(i)))
+ i++;
+ var valid = i > digitsStart;
+ if (valid && i < len && s.charAt(i) == '.') {
+ i++;
+ var fracStart = i;
+ while (i < len && isAsciiDigit(s.charAt(i)))
+ i++;
+ valid = i > fracStart;
+ }
+ BigDecimal nanos = null;
+ if (valid) {
+ var value = new BigDecimal(s.substring(0, i));
+ nanos = switch (s.substring(i).toLowerCase()) {
+ case "d" -> value.multiply(BigDecimal.valueOf(86_400_000_000_000L));
+ case "h" -> value.multiply(BigDecimal.valueOf(3_600_000_000_000L));
+ case "m" -> value.multiply(BigDecimal.valueOf(60_000_000_000L));
+ case "s" -> value.multiply(BigDecimal.valueOf(1_000_000_000L));
+ case "ms" -> value.multiply(BigDecimal.valueOf(1_000_000L));
+ case "us" -> value.multiply(BigDecimal.valueOf(1_000L));
+ case "ns" -> value;
+ default -> null;
+ };
+ }
+ if (nanos == null)
throw new IllegalArgumentException("Invalid HOCON duration: " + s);
- BigDecimal value = new BigDecimal(m.group(1));
- String unit = m.group(2).toLowerCase();
- BigDecimal nanos = switch (unit) {
- case "d" -> value.multiply(BigDecimal.valueOf(86_400_000_000_000L));
- case "h" -> value.multiply(BigDecimal.valueOf(3_600_000_000_000L));
- case "m" -> value.multiply(BigDecimal.valueOf(60_000_000_000L));
- case "s" -> value.multiply(BigDecimal.valueOf(1_000_000_000L));
- case "ms" -> value.multiply(BigDecimal.valueOf(1_000_000L));
- case "us" -> value.multiply(BigDecimal.valueOf(1_000L));
- case "ns" -> value;
- default -> throw new IllegalArgumentException("Invalid HOCON duration unit: " + unit);
- };
return Duration.ofNanos(nanos.longValue());
}
+
+ private static boolean isAsciiDigit(char c) {
+ return c >= '0' && c <= '9';
+ }
+
+ // Removes trailing '0' characters. Equivalent of replaceAll("0++$", ""); returns "" if the input is all zeros.
+ private static String trimTrailingZeros(String s) {
+ var end = s.length();
+ while (end > 0 && s.charAt(end - 1) == '0')
+ end--;
+ return s.substring(0, end);
+ }
}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/MarshalledConfigAnnotation.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/MarshalledConfigAnnotation.java
index 18b802042d..3533f23005 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/MarshalledConfigAnnotation.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/MarshalledConfigAnnotation.java
@@ -48,6 +48,9 @@ public class MarshalledConfigAnnotation {
}
@Override
+ @SuppressWarnings({
+ "java:S3776" // Cognitive complexity acceptable for the flat per-attribute config-applier sequence.
+ })
public void apply(AnnotationInfo<MarshalledConfig> ai, MarshallingContext.Builder b) {
MarshalledConfig a = ai.inner();
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hjson/HjsonTokenizer.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hjson/HjsonTokenizer.java
index fe2c2da8d5..8cf206f77a 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hjson/HjsonTokenizer.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hjson/HjsonTokenizer.java
@@ -16,8 +16,9 @@
*/
package org.apache.juneau.marshall.hjson;
+import static org.apache.juneau.commons.utils.StringUtils.*;
+
import java.io.*;
-import java.util.regex.*;
/**
* Tokenizer for Hjson format.
@@ -126,8 +127,6 @@ public class HjsonTokenizer {
}
}
- private static final Pattern NUMBER_PATTERN = Pattern.compile("^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?");
-
private final PushbackReader reader;
private Token peeked;
private int line = 1;
@@ -314,9 +313,9 @@ public class HjsonTokenizer {
if (raw.equals("false")) return Token.of(TokenType.FALSE);
if (raw.equals("null")) return Token.of(TokenType.NULL);
- var numMatcher = NUMBER_PATTERN.matcher(raw);
- if (numMatcher.matches()) {
- var numStr = numMatcher.group();
+ // Whole-string JSON-number match (leading-zero-restricted grammar); span equals the full token on a match.
+ if (matchNumberPrefix(raw, false) == raw.length()) {
+ var numStr = raw;
try {
if (numStr.contains(".") || numStr.toLowerCase().contains("e"))
return Token.number(Double.parseDouble(numStr));
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hocon/HoconTokenizer.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hocon/HoconTokenizer.java
index c7163d7082..9ae4c19d88 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hocon/HoconTokenizer.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/hocon/HoconTokenizer.java
@@ -16,8 +16,9 @@
*/
package org.apache.juneau.marshall.hocon;
+import static org.apache.juneau.commons.utils.StringUtils.*;
+
import java.io.*;
-import java.util.regex.*;
/**
* Tokenizer for HOCON (Human-Optimized Config Object Notation) format.
@@ -147,8 +148,6 @@ public class HoconTokenizer {
}
}
- private static final Pattern NUMBER_PATTERN = Pattern.compile("^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?");
-
private final PushbackReader reader;
private Token peeked;
private int line = 1;
@@ -437,9 +436,9 @@ public class HoconTokenizer {
if (raw.equals("false")) return Token.of(TokenType.FALSE);
if (raw.equals("null")) return Token.of(TokenType.NULL);
- var numMatcher = NUMBER_PATTERN.matcher(raw);
- if (numMatcher.matches()) {
- var numStr = numMatcher.group();
+ // Whole-string JSON-number match (leading-zero-restricted grammar); span equals the full token on a match.
+ if (matchNumberPrefix(raw, false) == raw.length()) {
+ var numStr = raw;
try {
if (numStr.contains(".") || numStr.toLowerCase().contains("e"))
return Token.number(Double.parseDouble(numStr));
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/html/HtmlSerializerSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/html/HtmlSerializerSession.java
index 1d05f251c1..0a243da6e9 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/html/HtmlSerializerSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/html/HtmlSerializerSession.java
@@ -224,7 +224,6 @@ public class HtmlSerializerSession extends XmlSerializerSession {
private final boolean detectLinksInStrings;
private final String labelParameter;
private final AnchorText uriAnchorText;
- private final Pattern urlPattern = Pattern.compile("https?\\:\\/\\/.*");
private final Pattern labelPattern;
/**
@@ -301,7 +300,25 @@ public class HtmlSerializerSession extends XmlSerializerSession {
*/
public boolean isUri(ClassMeta<?> cm, BeanPropertyMeta pMeta, Object o) {
return (cm.isUri() || (nn(pMeta) && pMeta.isUri()))
- || (isDetectLinksInStrings() && o instanceof CharSequence && urlPattern.matcher(o.toString()).matches());
+ || (isDetectLinksInStrings() && o instanceof CharSequence && isHttpUrl(o.toString()));
+ }
+
+ // Programmatic equivalent of the full match https?\:\/\/.* (Pattern.matcher(s).matches()).
+ // The trailing .* does not cross a line terminator under matches(), so the remainder must contain none.
+ private static boolean isHttpUrl(String s) {
+ int start;
+ if (s.startsWith("http://"))
+ start = 7;
+ else if (s.startsWith("https://"))
+ start = 8;
+ else
+ return false;
+ for (var i = start; i < s.length(); i++) {
+ var c = s.charAt(i);
+ if (c == '\n' || c == '\r' || c == '\u0085' || c == '\u2028' || c == '\u2029')
+ return false;
+ }
+ return true;
}
/**
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/httppart/HttpPartSchema.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/httppart/HttpPartSchema.java
index fa65dc4fea..f754ad358a 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/httppart/HttpPartSchema.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/httppart/HttpPartSchema.java
@@ -4336,28 +4336,138 @@ public class HttpPartSchema {
}
private static boolean isValidDate(String x) {
- // RFC 3339 full-date: YYYY-MM-DD (relaxed to allow various date formats)
- return x.matches("^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}.*");
+ // RFC 3339 full-date: YYYY-MM-DD (relaxed to allow various date formats) (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors prefix match ^\d{4}[-/]\d{1,2}[-/]\d{1,2}.* (\d = ASCII [0-9]; trailing .* is a non-line-terminator prefix check, not a full match).
+ if (x.length() < 4)
+ return false;
+ for (var i = 0; i < 4; i++)
+ if (! isAsciiDigit(x.charAt(i)))
+ return false;
+ var i = scanSepAnd1or2Digits(x, 4);
+ if (i < 0)
+ return false;
+ i = scanSepAnd1or2Digits(x, i);
+ if (i < 0)
+ return false;
+ return hasNoLineTerminator(x, i);
}
private static boolean isValidDateTime(String x) {
- // RFC 3339 date-time (relaxed to allow various datetime formats)
- return x.matches("^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}[T\\s]\\d{1,2}:\\d{1,2}.*");
+ // RFC 3339 date-time (relaxed to allow various datetime formats) (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors prefix match ^\d{4}[-/]\d{1,2}[-/]\d{1,2}[T\s]\d{1,2}:\d{1,2}.* (\s = ASCII whitespace; trailing .* is a non-line-terminator prefix check).
+ if (x.length() < 4)
+ return false;
+ for (var i = 0; i < 4; i++)
+ if (! isAsciiDigit(x.charAt(i)))
+ return false;
+ var i = scanSepAnd1or2Digits(x, 4);
+ if (i < 0)
+ return false;
+ i = scanSepAnd1or2Digits(x, i);
+ if (i < 0)
+ return false;
+ if (i >= x.length() || ! (x.charAt(i) == 'T' || isRegexWhitespace(x.charAt(i))))
+ return false;
+ i = scan1or2Digits(x, i + 1);
+ if (i < 0)
+ return false;
+ if (! charIs(x, i, ':'))
+ return false;
+ i = scan1or2Digits(x, i + 1);
+ if (i < 0)
+ return false;
+ return hasNoLineTerminator(x, i);
}
private static boolean isValidDateTimeZone(String x) {
- // RFC 3339 date-time with time zone
- return x.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?[+-]\\d{2}:\\d{2}$");
+ // RFC 3339 date-time with time zone (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors full match ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?[+-]\d{2}:\d{2}$ (\d = ASCII [0-9]).
+ var len = x.length();
+ var i = scanDigits(x, 0, 4);
+ if (i < 0 || ! charIs(x, i, '-'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0 || ! charIs(x, i, '-'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0 || ! charIs(x, i, 'T'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0 || ! charIs(x, i, ':'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0 || ! charIs(x, i, ':'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0)
+ return false;
+ if (i < len && x.charAt(i) == '.') { // (\.\d+)? - the '.' requires at least one following digit
+ var f = i + 1;
+ i = f;
+ while (i < len && isAsciiDigit(x.charAt(i)))
+ i++;
+ if (i == f)
+ return false;
+ }
+ if (i >= len || (x.charAt(i) != '+' && x.charAt(i) != '-'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0 || ! charIs(x, i, ':'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ return i == len;
}
private static boolean isValidDuration(String x) {
- // RFC 3339 Appendix A duration (ISO 8601)
- return x.matches("^P(?:\\d+Y)?(?:\\d+M)?(?:\\d+D)?(?:T(?:\\d+H)?(?:\\d+M)?(?:\\d+(?:\\.\\d+)?S)?)?$");
+ // RFC 3339 Appendix A duration (ISO 8601) (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors full match ^P(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$ (\d = ASCII [0-9]).
+ var len = x.length();
+ if (len == 0 || x.charAt(0) != 'P')
+ return false;
+ var i = scanDurationUnit(x, 1, 'Y');
+ i = scanDurationUnit(x, i, 'M');
+ i = scanDurationUnit(x, i, 'D');
+ if (i < len && x.charAt(i) == 'T') {
+ i = scanDurationUnit(x, i + 1, 'H');
+ i = scanDurationUnit(x, i, 'M');
+ i = scanDurationSeconds(x, i);
+ }
+ return i == len;
}
private static boolean isValidEmail(String x) {
- // RFC 5321 simplified email validation
- return x.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
+ // RFC 5321 simplified email validation (programmatic to avoid regex super-linear backtracking on large inputs).
+ // Mirrors ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
+ var at = x.indexOf('@');
+ if (at < 1 || at != x.lastIndexOf('@'))
+ return false;
+ for (var i = 0; i < at; i++)
+ if (! isEmailLocalChar(x.charAt(i)))
+ return false;
+ var dot = x.lastIndexOf('.');
+ if (dot < at + 2) // Need at least one domain-body char between '@' and the final '.'.
+ return false;
+ for (var i = at + 1; i < dot; i++)
+ if (! isEmailDomainChar(x.charAt(i)))
+ return false;
+ if (x.length() - dot - 1 < 2) // TLD must be 2+ characters.
+ return false;
+ for (var i = dot + 1; i < x.length(); i++)
+ if (! isAsciiLetter(x.charAt(i)))
+ return false;
+ return true;
+ }
+
+ private static boolean isEmailLocalChar(char c) {
+ return isAsciiAlphanumeric(c) || c == '.' || c == '_' || c == '%' || c == '+' || c == '-';
+ }
+
+ private static boolean isEmailDomainChar(char c) {
+ return isAsciiAlphanumeric(c) || c == '.' || c == '-';
+ }
+
+ private static boolean isAsciiLetter(char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
private boolean isValidEnum(String x) {
@@ -4438,9 +4548,202 @@ public class HttpPartSchema {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
+ private static boolean isAsciiDigit(char c) {
+ // Java regex \d (ASCII [0-9] only).
+ return c >= '0' && c <= '9';
+ }
+
+ private static boolean isAsciiHexDigit(char c) {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
+ }
+
+ private static boolean isUriSchemeChar(char c) {
+ // Matches the regex class [a-zA-Z0-9+.-].
+ return isAsciiAlphanumeric(c) || c == '+' || c == '.' || c == '-';
+ }
+
+ private static boolean isRegexLineTerminator(char c) {
+ // Chars NOT matched by regex '.' in default (non-DOTALL) mode.
+ return c == '\n' || c == '\r' || c == '\u0085' || c == '\u2028' || c == '\u2029';
+ }
+
+ private static boolean charIs(String x, int i, char c) {
+ return i < x.length() && x.charAt(i) == c;
+ }
+
+ // Returns the index after consuming exactly n ASCII digits starting at i, or -1 if fewer than n digits are present.
+ private static int scanDigits(String x, int i, int n) {
+ if (i < 0 || i + n > x.length())
+ return -1;
+ for (var k = 0; k < n; k++)
+ if (! isAsciiDigit(x.charAt(i + k)))
+ return -1;
+ return i + n;
+ }
+
+ // Mirrors \d{1,2} - consumes 1 mandatory then 1 optional ASCII digit (greedy). Returns new index or -1.
+ private static int scan1or2Digits(String x, int i) {
+ var len = x.length();
+ if (i < 0 || i >= len || ! isAsciiDigit(x.charAt(i)))
+ return -1;
+ i++;
+ if (i < len && isAsciiDigit(x.charAt(i)))
+ i++;
+ return i;
+ }
+
+ // Mirrors [-/]\d{1,2}. Returns new index or -1.
+ private static int scanSepAnd1or2Digits(String x, int i) {
+ if (i < 0 || i >= x.length() || (x.charAt(i) != '-' && x.charAt(i) != '/'))
+ return -1;
+ return scan1or2Digits(x, i + 1);
+ }
+
+ // Mirrors '.*' / '.+' tail consumption: returns true iff every char from i onward is a non-line-terminator (i.e. matchable by regex '.').
+ private static boolean hasNoLineTerminator(String x, int i) {
+ for (var j = i; j < x.length(); j++)
+ if (isRegexLineTerminator(x.charAt(j)))
+ return false;
+ return true;
+ }
+
+ // Mirrors the optional group (?:\d+<unit>)?: consumes a run of >=1 ASCII digits followed by the unit char if present; otherwise leaves i unchanged.
+ private static int scanDurationUnit(String x, int i, char unit) {
+ var len = x.length();
+ var j = i;
+ while (j < len && isAsciiDigit(x.charAt(j)))
+ j++;
+ if (j > i && j < len && x.charAt(j) == unit)
+ return j + 1;
+ return i;
+ }
+
+ // Mirrors the optional group (?:\d+(?:\.\d+)?S)?: consumes seconds (with optional fraction) followed by 'S' if present; otherwise leaves i unchanged.
+ private static int scanDurationSeconds(String x, int i) {
+ var len = x.length();
+ var j = i;
+ while (j < len && isAsciiDigit(x.charAt(j)))
+ j++;
+ if (j == i)
+ return i; // \d+ requires at least one digit
+ if (j < len && x.charAt(j) == '.') {
+ var f = j + 1;
+ var k = f;
+ while (k < len && isAsciiDigit(x.charAt(k)))
+ k++;
+ if (k == f)
+ return i; // '.' with no following digit -> group cannot match -> consume nothing
+ j = k;
+ }
+ if (j < len && x.charAt(j) == 'S')
+ return j + 1;
+ return i; // no 'S' -> group matches empty
+ }
+
+ // Mirrors ^[a-zA-Z][a-zA-Z0-9+.-]*:<rest> where <rest> is .+ (nonEmptyRest=true) or .* (nonEmptyRest=false), all non-line-terminators.
+ private static boolean isValidScheme(String x, boolean nonEmptyRest) {
+ var len = x.length();
+ if (len == 0 || ! isAsciiLetter(x.charAt(0)))
+ return false;
+ var i = 1;
+ while (i < len && isUriSchemeChar(x.charAt(i)))
+ i++;
+ if (i >= len || x.charAt(i) != ':')
+ return false;
+ i++;
+ if (nonEmptyRest && i >= len)
+ return false;
+ return hasNoLineTerminator(x, i);
+ }
+
+ // Consumes up to 4 ASCII hex digits starting at i (bounded by end). Mirrors [0-9a-fA-F]{0,4}.
+ private static int scanHex4(String x, int i, int end) {
+ var n = 0;
+ while (i < end && n < 4 && isAsciiHexDigit(x.charAt(i))) {
+ i++;
+ n++;
+ }
+ return i;
+ }
+
+ // Mirrors ^([0-9a-fA-F]{0,4}+:){7}[0-9a-fA-F]{0,4}$ - exactly 8 hextet groups separated by 7 colons.
+ private static boolean isIpv6Full(String x) {
+ var len = x.length();
+ var i = 0;
+ for (var g = 0; g < 7; g++) {
+ i = scanHex4(x, i, len);
+ if (i >= len || x.charAt(i) != ':')
+ return false;
+ i++;
+ }
+ i = scanHex4(x, i, len);
+ return i == len;
+ }
+
+ // Mirrors ^::([0-9a-fA-F]{0,4}+:){0,6}[0-9a-fA-F]{0,4}$.
+ private static boolean isIpv6LeadingDoubleColon(String x) {
+ var len = x.length();
+ if (len < 2 || x.charAt(0) != ':' || x.charAt(1) != ':')
+ return false;
+ var i = 2;
+ var groups = 0;
+ while (groups < 6) {
+ var j = scanHex4(x, i, len);
+ if (j < len && x.charAt(j) == ':') {
+ i = j + 1;
+ groups++;
+ } else {
+ break;
+ }
+ }
+ i = scanHex4(x, i, len);
+ return i == len;
+ }
+
+ // Mirrors ^([0-9a-fA-F]{0,4}+:){1,7}:$ - every such match ends in ':', and the body (minus the final ':') is 1..7 hextet+colon groups.
+ private static boolean isIpv6TrailingColon(String x) {
+ var len = x.length();
+ if (len == 0 || x.charAt(len - 1) != ':')
+ return false;
+ var body = len - 1;
+ var i = 0;
+ var groups = 0;
+ while (i < body) {
+ var j = scanHex4(x, i, body);
+ if (j < body && x.charAt(j) == ':') {
+ i = j + 1;
+ groups++;
+ } else {
+ return false;
+ }
+ }
+ return groups >= 1 && groups <= 7 && i == body;
+ }
+
private static boolean isValidIdnEmail(String x) {
- // RFC 6531 - allows international characters
- return x.matches("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$");
+ // RFC 6531 - allows international characters (programmatic to avoid regex super-linear backtracking on large inputs).
+ // Mirrors ^[^@\s]+@[^@\s]+\.[^@\s]+$
+ var at = x.indexOf('@');
+ if (at < 1 || at != x.lastIndexOf('@'))
+ return false;
+ for (var i = 0; i < at; i++)
+ if (isRegexWhitespace(x.charAt(i)))
+ return false;
+ var len = x.length();
+ var interiorDot = false;
+ for (var i = at + 1; i < len; i++) {
+ var c = x.charAt(i);
+ if (isRegexWhitespace(c))
+ return false;
+ if (c == '.' && i > at + 1 && i < len - 1)
+ interiorDot = true;
+ }
+ return interiorDot;
+ }
+
+ private static boolean isRegexWhitespace(char c) {
+ // Matches Java regex \s (ASCII whitespace only).
+ return c == ' ' || c == '\t' || c == '\n' || c == '\u000B' || c == '\f' || c == '\r';
}
private static boolean isValidIdnHostname(String x) {
@@ -4471,13 +4774,16 @@ public class HttpPartSchema {
}
private static boolean isValidIpv6(String x) {
- // RFC 4291 IPv6 validation (simplified)
- return x.matches("^([0-9a-fA-F]{0,4}+:){7}[0-9a-fA-F]{0,4}$|^::([0-9a-fA-F]{0,4}+:){0,6}[0-9a-fA-F]{0,4}$|^([0-9a-fA-F]{0,4}+:){1,7}:$");
+ // RFC 4291 IPv6 validation (simplified) (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors the three full-match alternatives:
+ // ^([0-9a-fA-F]{0,4}+:){7}[0-9a-fA-F]{0,4}$ | ^::([0-9a-fA-F]{0,4}+:){0,6}[0-9a-fA-F]{0,4}$ | ^([0-9a-fA-F]{0,4}+:){1,7}:$
+ return isIpv6Full(x) || isIpv6LeadingDoubleColon(x) || isIpv6TrailingColon(x);
}
private static boolean isValidIri(String x) {
- // RFC 3987 IRI validation (allows international characters)
- return x.matches("^[a-zA-Z][a-zA-Z0-9+.-]*:.+");
+ // RFC 3987 IRI validation (allows international characters) (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors prefix match ^[a-zA-Z][a-zA-Z0-9+.-]*:.+ (.+ requires at least one trailing non-line-terminator char).
+ return isValidScheme(x, true);
}
private static boolean isValidIriReference(String x) {
@@ -4639,8 +4945,37 @@ public class HttpPartSchema {
}
private static boolean isValidTime(String x) {
- // RFC 3339 time
- return x.matches("^\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?$");
+ // RFC 3339 time (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors full match ^\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?$ (\d = ASCII [0-9]).
+ var len = x.length();
+ var i = scanDigits(x, 0, 2);
+ if (i < 0 || ! charIs(x, i, ':'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0 || ! charIs(x, i, ':'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0)
+ return false;
+ if (i < len && x.charAt(i) == '.') { // (\.\d+)? - the '.' requires at least one following digit
+ var f = i + 1;
+ i = f;
+ while (i < len && isAsciiDigit(x.charAt(i)))
+ i++;
+ if (i == f)
+ return false;
+ }
+ if (i == len)
+ return true; // (Z|[+-]\d{2}:\d{2})? matched empty
+ if (x.charAt(i) == 'Z')
+ return i + 1 == len;
+ if (x.charAt(i) != '+' && x.charAt(i) != '-')
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ if (i < 0 || ! charIs(x, i, ':'))
+ return false;
+ i = scanDigits(x, i + 1, 2);
+ return i == len;
}
private boolean isValidUniqueItems(Collection<?> x) {
@@ -4672,7 +5007,8 @@ public class HttpPartSchema {
// RFC 3986 URI validation
try {
new java.net.URI(x);
- return x.matches("^[a-zA-Z][a-zA-Z0-9+.-]*:.*");
+ // Mirrors prefix match ^[a-zA-Z][a-zA-Z0-9+.-]*:.* (.* permits an empty trailing, non-line-terminator part).
+ return isValidScheme(x, false);
} catch (Exception e) {
return false;
}
@@ -4692,13 +5028,29 @@ public class HttpPartSchema {
}
private static boolean isValidUriTemplate(String x) {
- // RFC 6570 URI Template validation (simplified)
- return x.matches("^[^\\s]*$");
+ // RFC 6570 URI Template validation (simplified) (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors full match ^[^\s]*$ - every char must be a non-whitespace char (\s = ASCII whitespace).
+ for (var i = 0; i < x.length(); i++)
+ if (isRegexWhitespace(x.charAt(i)))
+ return false;
+ return true;
}
private static boolean isValidUuid(String x) {
- // RFC 4122 UUID validation
- return x.matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
+ // RFC 4122 UUID validation (programmatic to avoid regex recompilation per HTTP-part value).
+ // Mirrors full match ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$.
+ if (x.length() != 36)
+ return false;
+ for (var i = 0; i < 36; i++) {
+ var c = x.charAt(i);
+ if (i == 8 || i == 13 || i == 18 || i == 23) {
+ if (c != '-')
+ return false;
+ } else if (! isAsciiHexDigit(c)) {
+ return false;
+ }
+ }
+ return true;
}
private static boolean resolve(Boolean b) {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniParserSession.java
index 681369c828..7ca3ca6c8a 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniParserSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniParserSession.java
@@ -47,9 +47,6 @@ public class IniParserSession extends ReaderParserSession implements RecordReada
private static final String ARG_ctx = "ctx";
- /** Pattern for key=value or key = value. */
- private static final Pattern KV_PATTERN = Pattern.compile("^([^=#\\s][^=]*)\\s*[=:]\\s*(.*)$", Pattern.DOTALL);
-
/** Delimiter for nested section names (e.g. {@code address/street}). */
private static final String SECTION_PATH_DELIMITER = "/";
@@ -139,10 +136,10 @@ public class IniParserSession extends ReaderParserSession implements RecordReada
current = sections.computeIfAbsent(sectionName, k -> new LinkedHashMap<>());
continue;
}
- var m = KV_PATTERN.matcher(line);
- if (m.matches()) {
- var key = m.group(1).trim();
- var value = m.group(2).trim();
+ var kv = splitKeyValue(line);
+ if (kv != null) {
+ var key = kv[0].trim();
+ var value = kv[1].trim();
// Strip inline comment (# ...) from value (when not inside quotes)
value = stripInlineComment(value);
current.put(key, value);
@@ -151,6 +148,31 @@ public class IniParserSession extends ReaderParserSession implements RecordReada
return sections;
}
+ /**
+ * Splits an INI {@code key=value} / {@code key:value} line into its key and raw-value parts.
+ *
+ * <p>
+ * Behavior mirrors the former {@code ^([^=#\s][^=]*)\s*[=:]\s*(.*)$} regex but without its super-linear
+ * backtracking: an {@code '='} delimiter (if present) binds to the first {@code '='}; otherwise the last
+ * {@code ':'} is used. Surrounding whitespace is left in place (callers trim).
+ *
+ * @param line The (already-trimmed) candidate line.
+ * @return A two-element array of {raw-key, raw-value}, or <jk>null</jk> if the line is not a key/value pair.
+ */
+ private static String[] splitKeyValue(String line) {
+ if (line.isEmpty())
+ return null;
+ var first = line.charAt(0);
+ if (first == '=' || first == '#' || Character.isWhitespace(first))
+ return null;
+ var idx = line.indexOf('=');
+ if (idx < 0)
+ idx = line.lastIndexOf(':');
+ if (idx < 1)
+ return null;
+ return new String[] { line.substring(0, idx), line.substring(idx + 1) };
+ }
+
private void populateBean(BeanMap<?> bm, Map<String, Map<String, String>> sections, String sectionPath) throws ParseException, ExecutableException {
var defaultSection = sections.get(sectionPath);
if (defaultSection != null) {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniSerializerSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniSerializerSession.java
index a63f56c3ac..5d53779f8f 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniSerializerSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/ini/IniSerializerSession.java
@@ -27,6 +27,7 @@ import java.util.*;
import java.util.function.*;
import org.apache.juneau.commons.bean.*;
+import org.apache.juneau.commons.utils.*;
import org.apache.juneau.marshall.*;
import org.apache.juneau.marshall.json.*;
import org.apache.juneau.marshall.json5.*;
@@ -306,7 +307,8 @@ public class IniSerializerSession extends WriterSerializerSession implements Rec
return true;
if (s.equals("null") || s.equalsIgnoreCase("true") || s.equalsIgnoreCase("false"))
return true;
- if (s.matches("-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?"))
+ // Whole-string numeric check; mirrors -?\d+(\.\d+)?([eE][+-]?\d+)? (integer part allows leading zeros).
+ if (StringUtils.matchNumberPrefix(s, true) == s.length())
return true;
if (s.contains("=") || s.contains("[") || s.contains("]") || s.contains("#") || s.contains("\n"))
return true;
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/jcs/JcsSerializerSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/jcs/JcsSerializerSession.java
index 848f496be2..015dcfe796 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/jcs/JcsSerializerSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/jcs/JcsSerializerSession.java
@@ -147,12 +147,15 @@ public class JcsSerializerSession extends JsonSerializerSession {
}
private static String stripTrailingZeros(String s) {
- if (s.contains(".")) {
- s = s.replaceAll("0++$", "");
- if (s.endsWith("."))
- s = s.substring(0, s.length() - 1);
- }
- return s;
+ // Non-regex char scan avoids regex backtracking (java:S8786) while preserving exact semantics.
+ if (s.indexOf('.') < 0)
+ return s;
+ var end = s.length();
+ while (end > 0 && s.charAt(end - 1) == '0')
+ end--;
+ if (end > 0 && s.charAt(end - 1) == '.')
+ end--;
+ return s.substring(0, end);
}
private static String formatDoubleScientific(double d) {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/json5l/Json5lSerializer.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/json5l/Json5lSerializer.java
index 17bc08015f..c88ce81065 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/json5l/Json5lSerializer.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/json5l/Json5lSerializer.java
@@ -72,7 +72,8 @@ import org.apache.juneau.marshall.jsonl.*;
* </ul>
*/
@SuppressWarnings({
- "java:S110" // Inheritance depth acceptable
+ "java:S110", // Inheritance depth acceptable
+ "java:S115" // Constants use UPPER_camelCase convention (e.g., ARG_copyFrom)
})
public class Json5lSerializer extends JsonlSerializer {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/markdown/MarkdownParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/markdown/MarkdownParserSession.java
index 916a840642..d14dc21b1e 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/markdown/MarkdownParserSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/markdown/MarkdownParserSession.java
@@ -779,7 +779,13 @@ public class MarkdownParserSession extends ReaderParserSession implements Record
var trimmed = line.trim();
if (!trimmed.startsWith("|"))
return false;
- return trimmed.replaceAll("[|\\-: ]", "").isEmpty();
+ // Equivalent of trimmed.replaceAll("[|\\-: ]", "").isEmpty(): true iff every char is one of | - : space.
+ for (var i = 0; i < trimmed.length(); i++) {
+ var c = trimmed.charAt(i);
+ if (c != '|' && c != '-' && c != ':' && c != ' ')
+ return false;
+ }
+ return true;
}
/**
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/parquet/SnappyBlockDecompressor.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/parquet/SnappyBlockDecompressor.java
index 5b05eb63b3..cb49a99dc2 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/parquet/SnappyBlockDecompressor.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/parquet/SnappyBlockDecompressor.java
@@ -53,6 +53,10 @@ final class SnappyBlockDecompressor {
* @return The decompressed bytes.
* @throws IOException If the block is malformed or its declared length disagrees with {@code expectedSize}.
*/
+ @SuppressWarnings({
+ "java:S3776" // Cognitive complexity inherent to the Snappy block-codec decode loop; splitting the tag/literal/copy
+ // branches into helpers would fragment the tightly-coupled cursor/bounds logic and risk decoder bugs.
+ })
static byte[] decompress(byte[] input, int expectedSize) throws IOException {
var in = new int[]{0}; // boxed read cursor
int uncompressedLen = readVarint(input, in);
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufClassMeta.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufClassMeta.java
index 8c94ad1c96..e2c41688c4 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufClassMeta.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufClassMeta.java
@@ -52,6 +52,9 @@ public class ProtobufClassMeta extends ExtendedClassMeta {
* @param cm The class that this metadata is defined on.
* @param mp Protobuf metadata provider (for finding information about other artifacts).
*/
+ @SuppressWarnings({
+ "java:S3776" // Cognitive complexity acceptable for the two-pass field-number assignment.
+ })
public ProtobufClassMeta(ClassMeta<?> cm, ProtobufMetaProvider mp) {
super(cm);
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufFieldEntry.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufFieldEntry.java
index c87a4bf3c4..b538b4906c 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufFieldEntry.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufFieldEntry.java
@@ -108,6 +108,9 @@ public class ProtobufFieldEntry {
*
* @return The class metadata of the property's type.
*/
+ @SuppressWarnings({
+ "java:S1452" // Property type is dynamic; the wildcard ClassMeta<?> is the correct, type-safe return type.
+ })
public ClassMeta<?> propertyType() {
return propertyType;
}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufParserSession.java
index 0aa064c8f7..b78b388378 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufParserSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufParserSession.java
@@ -44,7 +44,8 @@ import org.apache.juneau.marshall.swap.*;
"rawtypes", // Raw types necessary for generic type handling
"unchecked", // Type erasure requires unchecked casts
"java:S110", // Inheritance depth acceptable for parser session hierarchy
- "resource" // Closeable resources are owned by the caller's parser session; Eclipse JDT @Owning warning is by design.
+ "resource", // Closeable resources are owned by the caller's parser session; Eclipse JDT @Owning warning is by design.
+ "java:S115" // Constants use UPPER_camelCase convention (e.g., ARG_ctx)
})
public class ProtobufParserSession extends InputStreamParserSession {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializer.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializer.java
index b51d8353b8..2b632f8e07 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializer.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializer.java
@@ -88,7 +88,8 @@ import org.apache.juneau.marshall.serializer.*;
* </ul>
*/
@SuppressWarnings({
- "java:S110" // Inheritance depth acceptable for this class hierarchy
+ "java:S110", // Inheritance depth acceptable for this class hierarchy
+ "java:S115" // Constants use UPPER_camelCase convention (e.g., ARG_copyFrom, PROP_nativeTypes)
})
public class ProtobufSerializer extends OutputStreamSerializer implements ProtobufMetaProvider {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializerSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializerSession.java
index d2b2ba8f43..ee7e5858ab 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializerSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/protobuf/ProtobufSerializerSession.java
@@ -46,7 +46,8 @@ import org.apache.juneau.marshall.swap.*;
"resource", // Output streams managed by calling code
"java:S110", // Inheritance depth acceptable for serializer session hierarchy
"rawtypes", // Raw types necessary for generic Map/Collection handling
- "unchecked" // Raw Map passed to forEachEntry requires an unchecked conversion to Map<K,V>
+ "unchecked", // Raw Map passed to forEachEntry requires an unchecked conversion to Map<K,V>
+ "java:S115" // Constants use UPPER_camelCase convention (e.g., ARG_ctx)
})
public class ProtobufSerializerSession extends OutputStreamSerializerSession {
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/serializer/SerializerSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/serializer/SerializerSession.java
index 592158229a..0986740bce 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/serializer/SerializerSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/serializer/SerializerSession.java
@@ -679,7 +679,8 @@ public class SerializerSession extends MarshallingTraverseSession {
* @return <jk>true</jk> if the values are equal under the {@code nonDefault} contract.
*/
@SuppressWarnings({
- "java:S1244" // Float equality is intentional: caller has already narrowed to numeric short-circuit; BigDecimal compareTo handles the value-equality semantics.
+ "java:S1244", // Float equality is intentional: caller has already narrowed to numeric short-circuit; BigDecimal compareTo handles the value-equality semantics.
+ "java:S3776" // Cognitive complexity acceptable for the numeric/NaN value-equality logic.
})
private static boolean defaultEquals(Object a, Object b) {
if (a == b)
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/uon/UonParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/uon/UonParserSession.java
index 7d25f2b474..d2c35d4b83 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/uon/UonParserSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/uon/UonParserSession.java
@@ -651,6 +651,7 @@ public class UonParserSession extends ReaderParserSession implements HttpPartPar
@SuppressWarnings({
"java:S1168", // Intentionally returns null for EOF/AMP in this parser state machine.
+ "java:S2583", // Defensive c==-1/AMP sub-checks inside the while(c!=-1 && c!=AMP) loop; kept for state-machine completeness.
"java:S6541", // Brain method acceptable for parser state machine
"java:S3776" // Cognitive complexity acceptable for parser state machine
})
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/utils/Iso8601Utils.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/utils/Iso8601Utils.java
index e695468ce1..95623d631d 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/utils/Iso8601Utils.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/utils/Iso8601Utils.java
@@ -25,7 +25,6 @@ import java.time.Duration;
import java.time.format.*;
import java.time.temporal.*;
import java.util.*;
-import java.util.regex.*;
import javax.xml.datatype.*;
@@ -321,11 +320,11 @@ public final class Iso8601Utils {
if (s.startsWith("PT-"))
s = "-PT" + s.substring(3);
// Number sniffing and explicit format hints.
- if (s.matches("^[+-]?\\d+$"))
+ if (isIntegerLiteral(s))
return (formatHint == null ? DurationFormat.MILLIS : formatHint).parse(s);
- if (s.matches("^[+-]?\\d+\\.\\d+$"))
+ if (isDecimalLiteral(s))
return DurationFormat.SECONDS.parse(s);
- if (s.matches("^[+-]?\\d+(?:\\.\\d+)?(?:ns|us|ms|s|m|h|d)$"))
+ if (isHoconLiteral(s))
return DurationFormat.HOCON.parse(s);
// Use manual parser for full control (handles PTnH, PTnM, PTn.nS, -PTnH, PT-6H, etc.)
Duration d = parseDurationManual(s);
@@ -355,7 +354,7 @@ public final class Iso8601Utils {
if (value == null || value.isEmpty())
return null;
String s = value.trim();
- if (s.matches("^[+-]?\\d+$"))
+ if (isIntegerLiteral(s))
return (formatHint == null ? PeriodFormat.DAYS : formatHint).parse(s);
return Period.parse(s);
}
@@ -464,6 +463,23 @@ public final class Iso8601Utils {
return (T) parseTemporalDefault(iso8601, ttc, zoneId);
}
+ /**
+ * Hand-written state machine that parses the {@code PT}-prefixed body as a strict, gapless sequence of
+ * {@code number[whitespace]unit} components ({@code H}/{@code M}/{@code S}, case-insensitive).
+ *
+ * <p>
+ * Whitespace is permitted between a number and its unit and between/around components, but every
+ * non-whitespace character must belong to a valid component. The parser rejects (by returning <jk>null</jk>,
+ * the same signal used for any input it cannot handle) when it encounters stray characters, a malformed
+ * number (e.g. more than one decimal point, or a trailing dot with no fraction), or a number without a
+ * trailing unit. On rejection {@link #parseDuration} falls through to {@link Duration#parse(CharSequence)},
+ * which throws for genuinely invalid values. Numeric conversion uses the floating-point expression
+ * {@code (long)(value * 1_000_000_000)} to preserve historical rounding for well-formed inputs.
+ *
+ * @param s The candidate duration string (already trimmed/dequoted/PT-normalized by {@link #parseDuration}).
+ * @return The parsed {@link Duration}, or <jk>null</jk> if the string is too short, lacks a {@code PT}/{@code pt}
+ * prefix, contains no component, or contains any stray/malformed content.
+ */
private static Duration parseDurationManual(String s) {
if (s == null || s.length() < 3)
return null;
@@ -474,19 +490,45 @@ public final class Iso8601Utils {
s2 = s2.substring(2);
long totalNanos = 0;
boolean found = false;
- var p = Pattern.compile("(\\d++(?:\\.\\d++)?+)\\s*([HhMmSs])");
- var m = p.matcher(s2);
- while (m.find()) {
+ int len = s2.length();
+ int i = 0;
+ while (i < len) {
+ // Whitespace between/around components is skipped; any other non-component character is rejected.
+ if (isRegexWhitespace(s2.charAt(i))) {
+ i++;
+ continue;
+ }
+ // A component must begin with a digit; any other character is stray junk → reject.
+ if (!isAsciiDigit(s2.charAt(i)))
+ return null;
+ int start = i;
+ while (i < len && isAsciiDigit(s2.charAt(i))) // Integer part.
+ i++;
+ // Optional fraction: a single '.' that MUST be followed by at least one digit.
+ if (i < len && s2.charAt(i) == '.') {
+ i++;
+ if (i >= len || !isAsciiDigit(s2.charAt(i)))
+ return null; // Trailing dot with no fraction → malformed.
+ while (i < len && isAsciiDigit(s2.charAt(i)))
+ i++;
+ }
+ int numEnd = i;
+ while (i < len && isRegexWhitespace(s2.charAt(i))) // Optional whitespace between number and unit.
+ i++;
+ // A unit designator is required; a number without one (or followed by stray chars) is malformed.
+ if (i >= len || !isDurationUnit(s2.charAt(i)))
+ return null;
found = true;
- double v = Double.parseDouble(m.group(1));
+ double v = Double.parseDouble(s2.substring(start, numEnd));
long nanos = (long)(v * 1_000_000_000);
- char unit = Character.toUpperCase(m.group(2).charAt(0));
+ char unit = Character.toUpperCase(s2.charAt(i));
switch (unit) {
case 'H': totalNanos += nanos * 3600; break;
case 'M': totalNanos += nanos * 60; break;
case 'S': totalNanos += nanos; break;
- default: break;
+ default: break; // HTT: isDurationUnit guarantees H/M/S
}
+ i++; // Consume the unit.
}
if (!found)
return null;
@@ -494,6 +536,96 @@ public final class Iso8601Utils {
return neg ? d.negated() : d;
}
+ private static boolean isAsciiDigit(char c) {
+ return c >= '0' && c <= '9';
+ }
+
+ /**
+ * Matches the regex {@code \s} character class (without the {@code UNICODE_CHARACTER_CLASS} flag).
+ */
+ private static boolean isRegexWhitespace(char c) {
+ return c == ' ' || c == '\t' || c == '\n' || c == '\u000B' || c == '\f' || c == '\r';
+ }
+
+ private static boolean isDurationUnit(char c) {
+ return c == 'H' || c == 'h' || c == 'M' || c == 'm' || c == 'S' || c == 's';
+ }
+
+ /**
+ * State-machine equivalent of {@code ^[+-]?\d++$} — an optional sign followed by one or more ASCII digits.
+ *
+ * @param s The string to test.
+ * @return <jk>true</jk> if the entire string is an optionally-signed integer literal.
+ */
+ private static boolean isIntegerLiteral(String s) {
+ int len = s.length();
+ int i = 0;
+ if (i < len && (s.charAt(i) == '+' || s.charAt(i) == '-'))
+ i++;
+ if (i == len)
+ return false;
+ for (int k = i; k < len; k++)
+ if (!isAsciiDigit(s.charAt(k)))
+ return false;
+ return true;
+ }
+
+ /**
+ * State-machine equivalent of {@code ^[+-]?\d++\.\d++$} — an optionally-signed decimal with digits on both
+ * sides of a single dot.
+ *
+ * @param s The string to test.
+ * @return <jk>true</jk> if the entire string is an optionally-signed decimal literal.
+ */
+ private static boolean isDecimalLiteral(String s) {
+ int len = s.length();
+ int i = 0;
+ if (i < len && (s.charAt(i) == '+' || s.charAt(i) == '-'))
+ i++;
+ int intStart = i;
+ while (i < len && isAsciiDigit(s.charAt(i)))
+ i++;
+ if (i == intStart)
+ return false;
+ if (i >= len || s.charAt(i) != '.')
+ return false;
+ i++;
+ int fracStart = i;
+ while (i < len && isAsciiDigit(s.charAt(i)))
+ i++;
+ if (i == fracStart)
+ return false;
+ return i == len;
+ }
+
+ /**
+ * State-machine equivalent of {@code ^[+-]?\d++(?:\.\d++)?(?:ns|us|ms|s|m|h|d)$} — an optionally-signed number
+ * (with optional fraction) followed by a HOCON time unit.
+ *
+ * @param s The string to test.
+ * @return <jk>true</jk> if the entire string is an optionally-signed HOCON duration literal.
+ */
+ private static boolean isHoconLiteral(String s) {
+ int len = s.length();
+ int i = 0;
+ if (i < len && (s.charAt(i) == '+' || s.charAt(i) == '-'))
+ i++;
+ int intStart = i;
+ while (i < len && isAsciiDigit(s.charAt(i)))
+ i++;
+ if (i == intStart)
+ return false;
+ // Optional fraction consumed only when '.' is followed by at least one digit; otherwise left for the unit.
+ if (i < len && s.charAt(i) == '.' && i + 1 < len && isAsciiDigit(s.charAt(i + 1))) {
+ i++;
+ while (i < len && isAsciiDigit(s.charAt(i)))
+ i++;
+ }
+ String unit = s.substring(i);
+ return unit.equals("ns") || unit.equals("us") || unit.equals("ms")
+ || unit.equals("s") || unit.equals("m") || unit.equals("h") || unit.equals("d");
+ }
+
private static Calendar parseCalendarDefault(String iso8601, ZoneId zoneId) {
var formatter = selectParserFormatter(iso8601);
var ta = new DefaultingTemporalAccessor(formatter.parse(iso8601), zoneId);
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/xml/XmlParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/xml/XmlParserSession.java
index e0e1ab9bdb..06f8907671 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/xml/XmlParserSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshall/xml/XmlParserSession.java
@@ -674,7 +674,7 @@ public class XmlParserSession extends ReaderParserSession implements RecordReada
* <p>
* A <jk>null</jk> {@code rootElementName} is equivalent to {@link #parseArrayRecords(Object)}.
* The cursor is buffered ({@link RecordReader#isStreaming()} == <jk>false</jk>); see
- * {@code TODO-175ab} Item 3 for why true element-at-a-time XML streaming is left for a
+ * {@code 175ab} Item 3 for why true element-at-a-time XML streaming is left for a
* demand-driven StAX cursor.
*
* @param input The input.
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/TestUtils.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/TestUtils.java
index 94256bbbab..5f4f516f58 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,19 +17,14 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
import java.io.*;
-import java.lang.reflect.*;
import java.net.*;
import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
import org.apache.juneau.marshall.serializer.*;
import org.apache.juneau.marshall.xml.*;
@@ -41,11 +36,6 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172", // Parameters kept for consistent method signatures across test utilities
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
-})
public class TestUtils extends Utils {
private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
@@ -58,6 +48,11 @@ public class TestUtils extends Utils {
}
}
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
+ }
+
public static void assertNotEqualsAny(Object actual, Object...values) {
assertNotNull(actual, "Value was null.");
for (var i = 0; i < values.length; i++) {
@@ -69,12 +64,6 @@ public class TestUtils extends Utils {
assertEquals(expected, s.toString(actual));
}
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
var exception = Assertions.assertThrows(expectedType, executable);
var messages = getMessages(exception);
@@ -89,120 +78,6 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^\\s/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^\\s>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*?</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
@@ -283,64 +158,6 @@ public class TestUtils extends Utils {
public static final void validateXml(Object o, XmlSerializer s) throws Exception {
s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
+ XmlTestUtils.checkXmlWhitespace(xml);
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
index 0f9642e3b9..263f5f9945 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
@@ -18,6 +18,7 @@ package org.apache.juneau.a.rttests;
import static java.util.Collections.*;
import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.XmlTestUtils.*;
import static org.apache.juneau.commons.utils.CollectionUtils.*;
import static org.apache.juneau.commons.utils.StringUtils.*;
import java.lang.reflect.*;
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/cp/FileFinder_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/cp/FileFinder_Test.java
index 84b7d229a6..ef2352c53a 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/cp/FileFinder_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/cp/FileFinder_Test.java
@@ -120,13 +120,13 @@ public class FileFinder_Test extends TestBase {
.build();
var patterns = a("_a.txt","_b",".c",".d.txt","e.txt","f","g_foo.txt","h.foo.txt","i_foo");
- var patterns_ja = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
- var patterns_ja_JP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
+ var patternsJa = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
+ var patternsJaJP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
for (var i = 0; i < patterns.length; i++) {
var p = patterns[i];
- var p_ja = patterns_ja[i];
- var p_ja_JP = patterns_ja_JP[i];
+ var pJa = patternsJa[i];
+ var pJaJP = patternsJaJP[i];
assertContains("[home:/files/test1/"+p+"]", read(x,"test1/"+p,null));
assertContains("[home:/files/test1/dir/"+p+"]", read(x,"test1/dir/"+p,null));
@@ -135,19 +135,19 @@ public class FileFinder_Test extends TestBase {
assertContains("[home:/files/test1/dir/"+p+"]", read(x,"/test1/dir/"+p+"/",null));
assertContains("[home:/files/test1/dir/dir/"+p+"]", read(x,"/test1/dir/dir/"+p+"/",null));
- assertContains("[home:/files/test1/"+p_ja+"]", read(x,"test1/"+p,JAPANESE));
- assertContains("[home:/files/test1/dir/"+p_ja+"]", read(x,"test1/dir/"+p,JAPANESE));
- assertContains("[home:/files/test1/dir/dir/"+p_ja+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
- assertContains("[home:/files/test1/"+p_ja+"]", read(x,"/test1/"+p+"/",JAPANESE));
- assertContains("[home:/files/test1/dir/"+p_ja+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
- assertContains("[home:/files/test1/dir/dir/"+p_ja+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
-
- assertContains("[home:/files/test1/"+p_ja_JP+"]", read(x,"test1/"+p,JAPAN));
- assertContains("[home:/files/test1/dir/"+p_ja_JP+"]", read(x,"test1/dir/"+p,JAPAN));
- assertContains("[home:/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
- assertContains("[home:/files/test1/"+p_ja_JP+"]", read(x,"/test1/"+p+"/",JAPAN));
- assertContains("[home:/files/test1/dir/"+p_ja_JP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
- assertContains("[home:/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
+ assertContains("[home:/files/test1/"+pJa+"]", read(x,"test1/"+p,JAPANESE));
+ assertContains("[home:/files/test1/dir/"+pJa+"]", read(x,"test1/dir/"+p,JAPANESE));
+ assertContains("[home:/files/test1/dir/dir/"+pJa+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
+ assertContains("[home:/files/test1/"+pJa+"]", read(x,"/test1/"+p+"/",JAPANESE));
+ assertContains("[home:/files/test1/dir/"+pJa+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
+ assertContains("[home:/files/test1/dir/dir/"+pJa+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
+
+ assertContains("[home:/files/test1/"+pJaJP+"]", read(x,"test1/"+p,JAPAN));
+ assertContains("[home:/files/test1/dir/"+pJaJP+"]", read(x,"test1/dir/"+p,JAPAN));
+ assertContains("[home:/files/test1/dir/dir/"+pJaJP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
+ assertContains("[home:/files/test1/"+pJaJP+"]", read(x,"/test1/"+p+"/",JAPAN));
+ assertContains("[home:/files/test1/dir/"+pJaJP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
+ assertContains("[home:/files/test1/dir/dir/"+pJaJP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
}
var badPatterns = a("test1/bad.txt","test1/../test1/_a.txt","bad.txt",null,"",".","..","j.class","k.properties");
@@ -246,13 +246,13 @@ public class FileFinder_Test extends TestBase {
.build();
var patterns = a("_a.txt","_b",".c",".d.txt","e.txt","f","g_foo.txt","h.foo.txt","i_foo");
- var patterns_ja = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
- var patterns_ja_JP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
+ var patternsJa = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
+ var patternsJaJP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
for (var i = 0; i < patterns.length; i++) {
var p = patterns[i];
- var p_ja = patterns_ja[i];
- var p_ja_JP = patterns_ja_JP[i];
+ var pJa = patternsJa[i];
+ var pJaJP = patternsJaJP[i];
assertContains("[cp:/files/test1/"+p+"]", read(x,"test1/"+p,null));
assertContains("[cp:/files/test1/dir/"+p+"]", read(x,"test1/dir/"+p,null));
@@ -261,19 +261,19 @@ public class FileFinder_Test extends TestBase {
assertContains("[cp:/files/test1/dir/"+p+"]", read(x,"/test1/dir/"+p+"/",null));
assertContains("[cp:/files/test1/dir/dir/"+p+"]", read(x,"/test1/dir/dir/"+p+"/",null));
- assertContains("[cp:/files/test1/"+p_ja+"]", read(x,"test1/"+p,JAPANESE));
- assertContains("[cp:/files/test1/dir/"+p_ja+"]", read(x,"test1/dir/"+p,JAPANESE));
- assertContains("[cp:/files/test1/dir/dir/"+p_ja+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
- assertContains("[cp:/files/test1/"+p_ja+"]", read(x,"/test1/"+p+"/",JAPANESE));
- assertContains("[cp:/files/test1/dir/"+p_ja+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
- assertContains("[cp:/files/test1/dir/dir/"+p_ja+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
-
- assertContains("[cp:/files/test1/"+p_ja_JP+"]", read(x,"test1/"+p,JAPAN));
- assertContains("[cp:/files/test1/dir/"+p_ja_JP+"]", read(x,"test1/dir/"+p,JAPAN));
- assertContains("[cp:/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
- assertContains("[cp:/files/test1/"+p_ja_JP+"]", read(x,"/test1/"+p+"/",JAPAN));
- assertContains("[cp:/files/test1/dir/"+p_ja_JP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
- assertContains("[cp:/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
+ assertContains("[cp:/files/test1/"+pJa+"]", read(x,"test1/"+p,JAPANESE));
+ assertContains("[cp:/files/test1/dir/"+pJa+"]", read(x,"test1/dir/"+p,JAPANESE));
+ assertContains("[cp:/files/test1/dir/dir/"+pJa+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
+ assertContains("[cp:/files/test1/"+pJa+"]", read(x,"/test1/"+p+"/",JAPANESE));
+ assertContains("[cp:/files/test1/dir/"+pJa+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
+ assertContains("[cp:/files/test1/dir/dir/"+pJa+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
+
+ assertContains("[cp:/files/test1/"+pJaJP+"]", read(x,"test1/"+p,JAPAN));
+ assertContains("[cp:/files/test1/dir/"+pJaJP+"]", read(x,"test1/dir/"+p,JAPAN));
+ assertContains("[cp:/files/test1/dir/dir/"+pJaJP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
+ assertContains("[cp:/files/test1/"+pJaJP+"]", read(x,"/test1/"+p+"/",JAPAN));
+ assertContains("[cp:/files/test1/dir/"+pJaJP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
+ assertContains("[cp:/files/test1/dir/dir/"+pJaJP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
}
var badPatterns = a("test1/bad.txt","test1/../test1/_a.txt","bad.txt",null,"",".","..");
@@ -410,13 +410,13 @@ public class FileFinder_Test extends TestBase {
.build();
var patterns = a("_a.txt","_b",".c",".d.txt","e.txt","f","g_foo.txt","h.foo.txt","i_foo");
- var patterns_ja = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
- var patterns_ja_JP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
+ var patternsJa = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
+ var patternsJaJP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
for (var i = 0; i < patterns.length; i++) {
var p = patterns[i];
- var p_ja = patterns_ja[i];
- var p_ja_JP = patterns_ja_JP[i];
+ var pJa = patternsJa[i];
+ var pJaJP = patternsJaJP[i];
assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p+"]", read(x,"test1/"+p,null));
assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p+"]", read(x,"test1/dir/"+p,null));
@@ -425,19 +425,19 @@ public class FileFinder_Test extends TestBase {
assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p+"]", read(x,"/test1/dir/"+p+"/",null));
assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p+"]", read(x,"/test1/dir/dir/"+p+"/",null));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja+"]", read(x,"test1/"+p,JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja+"]", read(x,"test1/dir/"+p,JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja+"]", read(x,"/test1/"+p+"/",JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
-
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja_JP+"]", read(x,"test1/"+p,JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja_JP+"]", read(x,"test1/dir/"+p,JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja_JP+"]", read(x,"/test1/"+p+"/",JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja_JP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJa+"]", read(x,"test1/"+p,JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJa+"]", read(x,"test1/dir/"+p,JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJa+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJa+"]", read(x,"/test1/"+p+"/",JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJa+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJa+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
+
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJaJP+"]", read(x,"test1/"+p,JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJaJP+"]", read(x,"test1/dir/"+p,JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJaJP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJaJP+"]", read(x,"/test1/"+p+"/",JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJaJP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJaJP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
}
var badPatterns = a("test1/bad.txt","test1/../test1/_a.txt","bad.txt",null,"",".","..");
@@ -456,13 +456,13 @@ public class FileFinder_Test extends TestBase {
.build();
var patterns = a("_a.txt","_b",".c",".d.txt","e.txt","f","g_foo.txt","h.foo.txt","i_foo");
- var patterns_ja = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
- var patterns_ja_JP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
+ var patternsJa = a("_a_ja.txt","_b_ja",".c",".d_ja.txt","e_ja.txt","f_ja","g_foo_ja.txt","h.foo_ja.txt","i_foo_ja");
+ var patternsJaJP = a("_a_ja_JP.txt","_b_ja_JP",".c",".d_ja_JP.txt","e_ja_JP.txt","f_ja_JP","g_foo_ja_JP.txt","h.foo_ja_JP.txt","i_foo_ja_JP");
for (var i = 0; i < patterns.length; i++) {
var p = patterns[i];
- var p_ja = patterns_ja[i];
- var p_ja_JP = patterns_ja_JP[i];
+ var pJa = patternsJa[i];
+ var pJaJP = patternsJaJP[i];
assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p+"]", read(x,"test1/"+p,null));
assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p+"]", read(x,"test1/dir/"+p,null));
@@ -471,19 +471,19 @@ public class FileFinder_Test extends TestBase {
assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p+"]", read(x,"/test1/dir/"+p+"/",null));
assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p+"]", read(x,"/test1/dir/dir/"+p+"/",null));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja+"]", read(x,"test1/"+p,JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja+"]", read(x,"test1/dir/"+p,JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja+"]", read(x,"/test1/"+p+"/",JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
-
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja_JP+"]", read(x,"test1/"+p,JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja_JP+"]", read(x,"test1/dir/"+p,JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/"+p_ja_JP+"]", read(x,"/test1/"+p+"/",JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+p_ja_JP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
- assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+p_ja_JP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJa+"]", read(x,"test1/"+p,JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJa+"]", read(x,"test1/dir/"+p,JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJa+"]", read(x,"test1/dir/dir/"+p,JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJa+"]", read(x,"/test1/"+p+"/",JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJa+"]", read(x,"/test1/dir/"+p+"/",JAPANESE));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJa+"]", read(x,"/test1/dir/dir/"+p+"/",JAPANESE));
+
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJaJP+"]", read(x,"test1/"+p,JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJaJP+"]", read(x,"test1/dir/"+p,JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJaJP+"]", read(x,"test1/dir/dir/"+p,JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/"+pJaJP+"]", read(x,"/test1/"+p+"/",JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/"+pJaJP+"]", read(x,"/test1/dir/"+p+"/",JAPAN));
+ assertContains("[cp:/org/apache/juneau/cp/files/test1/dir/dir/"+pJaJP+"]", read(x,"/test1/dir/dir/"+p+"/",JAPAN));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/markdown/MarkdownParserSession_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/markdown/MarkdownParserSession_Test.java
index 8125681ee2..46d478a9e8 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/markdown/MarkdownParserSession_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/markdown/MarkdownParserSession_Test.java
@@ -250,12 +250,12 @@ class MarkdownParserSession_Test extends TestBase {
assertEquals("", r.get(0).name);
}
- @Test void d05_invalidJson5InBackticks() throws Exception {
+ @Test void d05_invalidJson5InBackticks() {
var md = "| Property | Value |\n|---|---|\n| addr | `{this is not json5` |";
assertThrows(ParseException.class, () -> MarkdownParser.DEFAULT.parse(md, MarkdownParser_Test.D.class));
}
- @Test void d06_invalidConvertCellValue() throws Exception {
+ @Test void d06_invalidConvertCellValue() {
// "abc" cannot convert to int → ParseException.
var md = "| Property | Value |\n|---|---|\n| age | abc |";
assertThrows(ParseException.class, () -> MarkdownParser.DEFAULT.parse(md, MarkdownParser_Test.A.class));
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/AnnotationWorkList_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/AnnotationWorkList_Test.java
index 6134cd8d7d..aa85de5db2 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/AnnotationWorkList_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/AnnotationWorkList_Test.java
@@ -38,13 +38,13 @@ class AnnotationWorkList_Test {
// equals: o not an AnnotationWorkList
@Test void a03_equals_non_list() {
var list = AnnotationWorkList.create();
- assertNotEquals(list, "not a list");
+ assertNotEquals("not a list", list);
}
// equals: o is null
@Test void a04_equals_null() {
var list = AnnotationWorkList.create();
- assertNotEquals(list, null);
+ assertNotEquals(null, list);
}
// hashCode smoke test
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanCtorApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanCtorApplyAnnotation_Test.java
index 553a37e28f..4733713c10 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanCtorApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanCtorApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class BeanCtorApplyAnnotation_Test extends TestBase {
var applier = new BeanCtorApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = BeanCtorApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanIgnoreApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanIgnoreApplyAnnotation_Test.java
index d8122a7b2d..c859cb1816 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanIgnoreApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanIgnoreApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class BeanIgnoreApplyAnnotation_Test extends TestBase {
var applier = new BeanIgnoreApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = BeanIgnoreApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanTypeApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanTypeApplyAnnotation_Test.java
index 314760a0ba..18d4c90155 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanTypeApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/BeanTypeApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class BeanTypeApplyAnnotation_Test extends TestBase {
var applier = new BeanTypeApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = BeanTypeApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ExampleApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ExampleApplyAnnotation_Test.java
index 515a2946f3..bc1f64514b 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ExampleApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ExampleApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class ExampleApplyAnnotation_Test extends TestBase {
var applier = new ExampleApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = ExampleApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledApplyAnnotation_Test.java
index 02a4e7961c..ee177b8be3 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class MarshalledApplyAnnotation_Test extends TestBase {
var applier = new MarshalledApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = MarshalledApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledIgnoreApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledIgnoreApplyAnnotation_Test.java
index 3f99b9a6fa..83b74264b7 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledIgnoreApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledIgnoreApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class MarshalledIgnoreApplyAnnotation_Test extends TestBase {
var applier = new MarshalledIgnoreApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = MarshalledIgnoreApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledPropApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledPropApplyAnnotation_Test.java
index 70e77d47c9..27c79b970e 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledPropApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/MarshalledPropApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class MarshalledPropApplyAnnotation_Test extends TestBase {
var applier = new MarshalledPropApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = MarshalledPropApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/SwapApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/SwapApplyAnnotation_Test.java
index f9e29b042c..bf72b0c8aa 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/SwapApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/SwapApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class SwapApplyAnnotation_Test extends TestBase {
var applier = new SwapApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = SwapApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/UriApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/UriApplyAnnotation_Test.java
index ef6cdc2ee7..67e17badef 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/UriApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/UriApplyAnnotation_Test.java
@@ -49,7 +49,6 @@ class UriApplyAnnotation_Test extends TestBase {
var applier = new UriApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = UriApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/bson/BsonApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/bson/BsonApplyAnnotation_Test.java
index 73e55cfdd7..f6676c12ba 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/bson/BsonApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/bson/BsonApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class BsonApplyAnnotation_Test extends TestBase {
var applier = new BsonApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = BsonApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/cbor/CborApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/cbor/CborApplyAnnotation_Test.java
index 5285b03d0c..b5d5fd8162 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/cbor/CborApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/cbor/CborApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class CborApplyAnnotation_Test extends TestBase {
var applier = new CborApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = CborApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/JsonPointer_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/JsonPointer_Test.java
index 56519d80fd..d83cdaa8fc 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/JsonPointer_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/JsonPointer_Test.java
@@ -207,7 +207,8 @@ class JsonPointer_Test extends TestBase {
@Test void e06_setIndexOutOfRangeThrows() {
// Setting at an index beyond the end of an existing list (not the append slot) is an error.
var root = JsonMap.of("a", JsonList.of(1, 2));
- assertThrows(IllegalArgumentException.class, () -> JsonPointer.of("/a/5").set(root, 9));
+ var p = JsonPointer.of("/a/5");
+ assertThrows(IllegalArgumentException.class, () -> p.set(root, 9));
}
@Test void e07_setReplaceAtExistingIndex() {
@@ -234,7 +235,8 @@ class JsonPointer_Test extends TestBase {
@Test void e10_setNonNumericListTokenThrows() {
// A non-numeric, non-'-' token on a list is an invalid array index on write.
var root = JsonMap.of("a", JsonList.of(1, 2));
- assertThrows(IllegalArgumentException.class, () -> JsonPointer.of("/a/foo").set(root, 9));
+ var p = JsonPointer.of("/a/foo");
+ assertThrows(IllegalArgumentException.class, () -> p.set(root, 9));
}
// -----------------------------------------------------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/MarshalledNode_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/MarshalledNode_Test.java
index de37233b01..2edcf10fb5 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/MarshalledNode_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/collections/MarshalledNode_Test.java
@@ -217,15 +217,21 @@ class MarshalledNode_Test extends TestBase {
}
@Test void d02_putRequiresObjectNode() {
- assertThrows(IllegalStateException.class, () -> MarshalledNode.arrayNode().put("a", 1));
- assertThrows(IllegalStateException.class, () -> MarshalledNode.of("scalar").put("a", 1));
- assertThrows(IllegalStateException.class, () -> MarshalledNode.of(null).put("a", 1));
+ var array = MarshalledNode.arrayNode();
+ var scalar = MarshalledNode.of("scalar");
+ var nul = MarshalledNode.of(null);
+ assertThrows(IllegalStateException.class, () -> array.put("a", 1));
+ assertThrows(IllegalStateException.class, () -> scalar.put("a", 1));
+ assertThrows(IllegalStateException.class, () -> nul.put("a", 1));
}
@Test void d03_addRequiresArrayNode() {
- assertThrows(IllegalStateException.class, () -> MarshalledNode.objectNode().add("x"));
- assertThrows(IllegalStateException.class, () -> MarshalledNode.of("scalar").add("x"));
- assertThrows(IllegalStateException.class, () -> MarshalledNode.of(null).add("x"));
+ var object = MarshalledNode.objectNode();
+ var scalar = MarshalledNode.of("scalar");
+ var nul = MarshalledNode.of(null);
+ assertThrows(IllegalStateException.class, () -> object.add("x"));
+ assertThrows(IllegalStateException.class, () -> scalar.add("x"));
+ assertThrows(IllegalStateException.class, () -> nul.add("x"));
}
// -----------------------------------------------------------------------------------------------------------------
@@ -333,7 +339,8 @@ class MarshalledNode_Test extends TestBase {
}
@Test void g08_setRootThrows() {
- assertThrows(IllegalArgumentException.class, () -> MarshalledNode.objectNode().set("", 1));
+ var n = MarshalledNode.objectNode();
+ assertThrows(IllegalArgumentException.class, () -> n.set("", 1));
}
@Test void g09_remove() {
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/csv/CsvApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/csv/CsvApplyAnnotation_Test.java
index 83caeb561d..1e9b3a7e73 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/csv/CsvApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/csv/CsvApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class CsvApplyAnnotation_Test extends TestBase {
var applier = new CsvApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = CsvApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hjson/HjsonApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hjson/HjsonApplyAnnotation_Test.java
index 2561c20e8a..c6267409f5 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hjson/HjsonApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hjson/HjsonApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class HjsonApplyAnnotation_Test extends TestBase {
var applier = new HjsonApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = HjsonApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hocon/HoconApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hocon/HoconApplyAnnotation_Test.java
index 3f1b0ce1cd..e177474412 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hocon/HoconApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/hocon/HoconApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class HoconApplyAnnotation_Test extends TestBase {
var applier = new HoconApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = HoconApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlApplyAnnotation_Test.java
index 5d5e477b19..334a25c749 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class HtmlApplyAnnotation_Test extends TestBase {
var applier = new HtmlApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = HtmlApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlLinkApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlLinkApplyAnnotation_Test.java
index 189a3cc931..d09cb4506d 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlLinkApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlLinkApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class HtmlLinkApplyAnnotation_Test extends TestBase {
var applier = new HtmlLinkApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = HtmlLinkApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlParserSession_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlParserSession_Test.java
index 324d06310e..ba8e7b67ad 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlParserSession_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/html/HtmlParserSession_Test.java
@@ -257,7 +257,7 @@ class HtmlParserSession_Test extends TestBase {
public static class BeanWithKnownProps {
public String known;
- public BeanWithKnownProps() {}
+ public BeanWithKnownProps() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test void j01_unknownBeanPropInTableRow() throws Exception {
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ini/IniApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ini/IniApplyAnnotation_Test.java
index 6b5d47fa77..b85b4cc21c 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ini/IniApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/ini/IniApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class IniApplyAnnotation_Test extends TestBase {
var applier = new IniApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = IniApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/internal/DelegateList_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/internal/DelegateList_Test.java
index cdffffc371..587e240df6 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/internal/DelegateList_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/internal/DelegateList_Test.java
@@ -51,18 +51,18 @@ class DelegateList_Test extends TestBase {
@Test void a04_equals_null() {
var cm = BC.<List<String>>getClassMeta(List.class, String.class);
var dl = new DelegateList<>(cm);
- assertNotEquals(dl, null);
+ assertNotEquals(null, dl);
}
@Test void a05_equals_nonList() {
var cm = BC.<List<String>>getClassMeta(List.class, String.class);
var dl = new DelegateList<>(cm);
- assertNotEquals(dl, "not a list");
+ assertNotEquals("not a list", dl);
}
@Test void a06_equals_emptyList() {
var cm = BC.<List<String>>getClassMeta(List.class, String.class);
- var dl = new DelegateList<>(cm);
+ List<Object> dl = new DelegateList<>(cm);
assertEquals(new ArrayList<>(), dl);
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonApplyAnnotation_Test.java
index c0fa4eb64d..a20abca231 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class JsonApplyAnnotation_Test extends TestBase {
var applier = new JsonApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = JsonApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderCoverage_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderCoverage_Test.java
index a70196d110..d0b24f3bfc 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderCoverage_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderCoverage_Test.java
@@ -437,18 +437,14 @@ class JsonTokenReaderCoverage_Test extends TestBase {
}
}
- @Test void g02_deeplyNestedObjectsBeyond64Levels() throws Exception {
+ @Test void g02_deeplyNestedObjectsBeyond64Levels() {
var depth = 70;
var sb = new StringBuilder();
for (var i = 0; i < depth; i++)
sb.append("{\"a\":");
sb.append("1");
sb.append("}".repeat(depth));
- try (var r = JsonParser.DEFAULT.parseTokens(sb.toString())) {
- while (r.next() != TokenType.END_OF_STREAM) {
- // drain; overflow object container handling is exercised
- }
- }
+ assertDoesNotThrow(() -> drain(sb.toString()));
}
@Test void g03_nestedMixedDocument() throws Exception {
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderSupplemental_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderSupplemental_Test.java
index 86fb76b187..fda430db71 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderSupplemental_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/json/JsonTokenReaderSupplemental_Test.java
@@ -72,11 +72,11 @@ class JsonTokenReaderSupplemental_Test extends TestBase {
assertThrowsWithMessage(ParseException.class, "Invalid JSON number", () -> drain("-01"));
}
- @Test void b03_zeroWithFractionOrExponentAccepted() throws Exception {
+ @Test void b03_zeroWithFractionOrExponentAccepted() {
// '0' followed by '.' / 'e' / 'E' is the valid branch of the leading-zero guard.
- drain("0.5");
- drain("0e1");
- drain("0E1");
+ assertDoesNotThrow(() -> drain("0.5"));
+ assertDoesNotThrow(() -> drain("0e1"));
+ assertDoesNotThrow(() -> drain("0E1"));
}
@Test void b04_danglingDecimalPointRejected() {
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/jsonschema/SchemaApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/jsonschema/SchemaApplyAnnotation_Test.java
index ee98b1b953..6cdc1aeb0c 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/jsonschema/SchemaApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/jsonschema/SchemaApplyAnnotation_Test.java
@@ -137,7 +137,6 @@ class SchemaApplyAnnotation_Test extends TestBase {
var applier = new SchemaApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = SchemaApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownApplyAnnotation_Test.java
index bdc8588259..6b3941e5fa 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class MarkdownApplyAnnotation_Test extends TestBase {
var applier = new MarkdownApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = MarkdownApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownParserSession_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownParserSession_Test.java
index bb333504d8..84b716a5b6 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownParserSession_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownParserSession_Test.java
@@ -106,9 +106,19 @@ class MarkdownParserSession_Test extends TestBase {
// b - Empty / blank input handling
//====================================================================================================
- @Test void b01_blankLinesOnly() {
- var r = MarkdownParser.DEFAULT.parse("\n \n\t\n", Map.class);
- assertNull(r);
+ @ParameterizedTest
+ @MethodSource("b01_parsesToNullProvider")
+ void b01_parsesToNull(String input, Class<?> type) {
+ assertNull(MarkdownParser.DEFAULT.parse(input, type));
+ }
+
+ static Stream<Arguments> b01_parsesToNullProvider() {
+ return Stream.of(
+ Arguments.of("\n \n\t\n", Map.class), // b01: blank lines only
+ Arguments.of("*null*", MarkdownParser_Test.A.class), // b06: "*null*" plain value to non-string type
+ Arguments.of("", MarkdownParser_Test.A.class), // o01: empty input for non-string type (parseAnything null branch)
+ Arguments.of(" \n \n ", MarkdownParser_Test.A.class) // o03: blank lines only for non-string type
+ );
}
@ParameterizedTest
@@ -130,12 +140,6 @@ class MarkdownParserSession_Test extends TestBase {
assertEquals(42, r);
}
- @Test void b06_plainNullToBean() {
- // "*null*" line treated as plain value parsed to type — non-string type returns null.
- var r = MarkdownParser.DEFAULT.parse("*null*", MarkdownParser_Test.A.class);
- assertNull(r);
- }
-
//====================================================================================================
// c - Table edge cases (empty data rows, separator filtering)
//====================================================================================================
@@ -249,15 +253,23 @@ class MarkdownParserSession_Test extends TestBase {
assertEquals("", r.get(0).name);
}
- @Test void d05_invalidJson5InBackticks() {
- var md = "| Property | Value |\n|---|---|\n| addr | `{this is not json5` |";
- assertThrows(ParseException.class, () -> MarkdownParser.DEFAULT.parse(md, MarkdownParser_Test.D.class));
+ @ParameterizedTest
+ @MethodSource("d05_parseThrowsProvider")
+ void d05_parseThrows(String md, Class<? extends Throwable> expected, Class<?> type) {
+ assertThrows(expected, () -> MarkdownParser.DEFAULT.parse(md, type));
}
- @Test void d06_invalidConvertCellValue() {
- // "abc" cannot convert to int → ParseException.
- var md = "| Property | Value |\n|---|---|\n| age | abc |";
- assertThrows(ParseException.class, () -> MarkdownParser.DEFAULT.parse(md, MarkdownParser_Test.A.class));
+ static Stream<Arguments> d05_parseThrowsProvider() {
+ return Stream.of(
+ // d05: invalid JSON5 inside backticks → ParseException
+ Arguments.of("| Property | Value |\n|---|---|\n| addr | `{this is not json5` |", ParseException.class, MarkdownParser_Test.D.class),
+ // d06: "abc" cannot convert to int → ParseException
+ Arguments.of("| Property | Value |\n|---|---|\n| age | abc |", ParseException.class, MarkdownParser_Test.A.class),
+ // v01: non-bean type can't be deserialized from a JSON5 object (needsJson5Path → keyValueTableToJson5)
+ Arguments.of("| Property | Value |\n|---|---|\n| value | hello |", Exception.class, NonBeanType.class),
+ // v03: multiple rows → keyValueTableToJson5 appends comma between entries (line 718-719)
+ Arguments.of("| Property | Value |\n|---|---|\n| a | 1 |\n| b | 2 |", Exception.class, NonBeanType.class)
+ );
}
//====================================================================================================
@@ -661,24 +673,12 @@ class MarkdownParserSession_Test extends TestBase {
// o - Empty input parsing
//====================================================================================================
- @Test void o01_emptyInputForBean() {
- // Empty input string for a non-String type → parseAnything null branch at line 174
- var r = MarkdownParser.DEFAULT.parse("", MarkdownParser_Test.A.class);
- assertNull(r);
- }
-
@Test void o02_emptyInputForString() {
// Empty input string for String type → parseAnything returns "" at line 175
var r = MarkdownParser.DEFAULT.parse("", String.class);
assertEquals("", r);
}
- @Test void o03_blankLinesOnlyForBean() {
- // Only blank lines → nonBlank is empty → returns null for non-String
- var r = MarkdownParser.DEFAULT.parse(" \n \n ", MarkdownParser_Test.A.class);
- assertNull(r);
- }
-
//====================================================================================================
// p - Polymorphic bean parsing with _type row
//====================================================================================================
@@ -824,27 +824,16 @@ class MarkdownParserSession_Test extends TestBase {
@Override public String toString() { return value; }
}
- @Test void v01_keyValueTableToJson5_nonBeanType() {
- // Non-bean type (no public properties) → needsJson5Path returns true → keyValueTableToJson5 is invoked
- // The JSON5 path is taken; parsing may throw since non-bean can't be deserialized from JSON5 object
- var md = "| Property | Value |\n|---|---|\n| value | hello |";
- assertThrows(Exception.class, () -> MarkdownParser.DEFAULT.parse(md, NonBeanType.class));
- }
-
@Test void v02_keyValueTableToJson5_typeKeyRow() {
// Non-bean type with _type row → keyValueTableToJson5 handles _type as quoted string (line 721-722)
// May succeed or fail depending on how Json5Parser handles the output; either way, line 721-722 is exercised.
var md = "| Property | Value |\n|---|---|\n| _type | mytype |\n| value | hello |";
- try {
- MarkdownParser.DEFAULT.parse(md, NonBeanType.class);
- } catch (Exception e) {
- // Expected: non-bean type can't be deserialized from JSON5 object
- }
- }
-
- @Test void v03_keyValueTableToJson5_multipleRows() {
- // Multiple rows → keyValueTableToJson5 appends comma between entries (line 718-719)
- var md = "| Property | Value |\n|---|---|\n| a | 1 |\n| b | 2 |";
- assertThrows(Exception.class, () -> MarkdownParser.DEFAULT.parse(md, NonBeanType.class));
+ assertDoesNotThrow(() -> {
+ try {
+ MarkdownParser.DEFAULT.parse(md, NonBeanType.class);
+ } catch (Exception e) {
+ // Expected: non-bean type can't be deserialized from JSON5 object
+ }
+ });
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownSerializer_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownSerializer_Test.java
index a85471a33f..1ce658fc8d 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownSerializer_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/markdown/MarkdownSerializer_Test.java
@@ -519,14 +519,6 @@ class MarkdownSerializer_Test {
assertTrue(md.contains("42"), "Expected numeric key in output: " + md);
}
- @Test void r02_nullValueStringAsMapKey() {
- // Key matching nullValue → isAmbiguousString(key, nullValue) returns true at line 370
- var m = new java.util.LinkedHashMap<String, String>();
- m.put("*null*", "surprise");
- var md = MarkdownSerializer.DEFAULT.serialize(m);
- assertNotNull(md);
- }
-
//====================================================================================================
// s - Collection with null item in table mode (line 310)
//====================================================================================================
@@ -569,19 +561,21 @@ class MarkdownSerializer_Test {
assertTrue(md.contains("key"), "Expected key in output: " + md);
}
- @Test void u02_nullValueStringAsMapValue() {
- // String equal to nullValue → isAmbiguousString returns true at line 370 (s.equals(nullValue))
+ @ParameterizedTest
+ @MethodSource("u02_ambiguousMapEntryProducesOutputProvider")
+ void u02_ambiguousMapEntryProducesOutput(String key, String value) {
+ // Ambiguous map keys/values still produce non-null serialized output.
var m = new java.util.LinkedHashMap<String, String>();
- m.put("key", "*null*");
+ m.put(key, value);
var md = MarkdownSerializer.DEFAULT.serialize(m);
assertNotNull(md);
}
- @Test void u03_controlCharStringAsMapValue() {
- // String with char < 32 → isAmbiguousString returns true at line 373
- var m = new java.util.LinkedHashMap<String, String>();
- m.put("key", "a\u007fb"); // char 127 (DEL) triggers the c == 127 branch
- var md = MarkdownSerializer.DEFAULT.serialize(m);
- assertNotNull(md);
+ static Stream<Arguments> u02_ambiguousMapEntryProducesOutputProvider() {
+ return Stream.of(
+ Arguments.of("key", "*null*"), // value equal to nullValue → isAmbiguousString line 370
+ Arguments.of("key", "a\u007fb"), // char 127 (DEL) → isAmbiguousString line 373
+ Arguments.of("*null*", "surprise") // key equal to nullValue → isAmbiguousString line 370
+ );
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/marshaller/MarshallerStreamShortcuts_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/marshaller/MarshallerStreamShortcuts_Test.java
index 324d94d2ce..ed64a7da98 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/marshaller/MarshallerStreamShortcuts_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/marshaller/MarshallerStreamShortcuts_Test.java
@@ -111,6 +111,7 @@ class MarshallerStreamShortcuts_Test extends TestBase {
}
@Test void a09_writeTokensClassCastForNonTokenFormat() {
- assertThrows(ClassCastException.class, () -> Csv.DEFAULT.toTokens(new StringBuilder()));
+ var sb = new StringBuilder();
+ assertThrows(ClassCastException.class, () -> Csv.DEFAULT.toTokens(sb));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackApplyAnnotation_Test.java
index 10dab2b54b..275aa5ba17 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class MsgPackApplyAnnotation_Test extends TestBase {
var applier = new MsgPackApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = MsgPackApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackConformance_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackConformance_Test.java
index 011230cb0d..6bbeabe48f 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackConformance_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/msgpack/MsgPackConformance_Test.java
@@ -30,7 +30,7 @@ import org.apache.juneau.marshall.serializer.*;
import org.junit.jupiter.api.*;
/**
- * Conformance regression tests guarding the Phase-2 MessagePack codec fixes (TODO-175fd audit).
+ * Conformance regression tests guarding the Phase-2 MessagePack codec fixes (175fd audit).
*
* <p>
* Each test pins a specific spec-corner / lossless-round-trip gap so that a future regression is caught:
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/oapi/OpenApiApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/oapi/OpenApiApplyAnnotation_Test.java
index c0220d601b..33224fabfc 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/oapi/OpenApiApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/oapi/OpenApiApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class OpenApiApplyAnnotation_Test extends TestBase {
var applier = new OpenApiApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = OpenApiApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/parquet/ParquetColumnReader_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/parquet/ParquetColumnReader_Test.java
index 928b8fa576..80c7d96a95 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/parquet/ParquetColumnReader_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/parquet/ParquetColumnReader_Test.java
@@ -127,12 +127,13 @@ class ParquetColumnReader_Test extends TestBase {
}
@Test
- void a10_byteArrayLengthGuard() {
+ void a10_byteArrayLengthGuard() throws Exception {
// A BYTE_ARRAY whose declared length exceeds the cap throws. REQUIRED column (no def levels):
// 4-byte LE length = 0x7FFFFFFF, then no payload.
var page = new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x7F};
var r = new ParquetColumnReader(page, 1, 0);
- assertThrows(IOException.class, () -> { r.advance(); r.readByteArray(); });
+ r.advance();
+ assertThrows(IOException.class, r::readByteArray);
}
@Test
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/plaintext/PlainTextApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/plaintext/PlainTextApplyAnnotation_Test.java
index 8cb55869e6..5158271aa3 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/plaintext/PlainTextApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/plaintext/PlainTextApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class PlainTextApplyAnnotation_Test extends TestBase {
var applier = new PlainTextApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = PlainTextApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufApplyAnnotation_Test.java
index 3a7ba46b26..fa93a64b78 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class ProtobufApplyAnnotation_Test extends TestBase {
var applier = new ProtobufApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = ProtobufApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufCoverage_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufCoverage_Test.java
index 61bcc2c96e..6645ffbbb7 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufCoverage_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufCoverage_Test.java
@@ -191,7 +191,7 @@ class ProtobufCoverage_Test extends TestBase {
@Protobuf(type=ProtobufScalarType.SFIXED64) public long sf64;
@Protobuf(type=ProtobufScalarType.UINT32) public int u32;
@Protobuf(type=ProtobufScalarType.INT64) public long i64;
- public ScalarTypes() {}
+ public ScalarTypes() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
@@ -233,8 +233,8 @@ class ProtobufCoverage_Test extends TestBase {
assertNotNull(s);
}
- public static class A04_C1 { public int f1; public void m1() {} }
- public static class A04_C2 { public int f2; public void m2() {} }
+ public static class A04_C1 { public int f1; public void m1() { /* No-op method used only as a reflection target in a04_applyTargetingMethods. */ } }
+ public static class A04_C2 { public int f2; public void m2() { /* No-op method used only as a reflection target in a04_applyTargetingMethods. */ } }
@Test
void a04_applyTargetingMethods() throws Exception {
@@ -268,7 +268,7 @@ class ProtobufCoverage_Test extends TestBase {
public java.time.Duration dur;
public java.time.LocalDate ld;
public java.time.Period per;
- public Temporals() {}
+ public Temporals() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
@@ -292,7 +292,7 @@ class ProtobufCoverage_Test extends TestBase {
public static class Holder {
public java.util.Map<String,ProtobufContainers_Test.Inner> m;
- public Holder() {}
+ public Holder() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
@@ -313,7 +313,7 @@ class ProtobufCoverage_Test extends TestBase {
public java.util.Map<String,java.time.LocalDate> lds;
public java.util.Map<String,java.time.Duration> durs;
public java.util.Map<String,java.time.Period> pers;
- public C03_TemporalMaps() {}
+ public C03_TemporalMaps() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
@@ -349,7 +349,7 @@ class ProtobufCoverage_Test extends TestBase {
public static class Cycle {
public String name;
public Cycle self;
- public Cycle() {}
+ public Cycle() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufEdgeCases_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufEdgeCases_Test.java
index 6d3de34be0..598fefaa4a 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufEdgeCases_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufEdgeCases_Test.java
@@ -135,7 +135,7 @@ class ProtobufEdgeCases_Test extends TestBase {
public static class Lists {
public List<Integer> nums;
public List<String> strs;
- public Lists() {}
+ public Lists() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
@@ -148,7 +148,7 @@ class ProtobufEdgeCases_Test extends TestBase {
public static class Maps {
public Map<String,Integer> m;
- public Maps() {}
+ public Maps() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufRoundTrip_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufRoundTrip_Test.java
index cbeecfaa28..07a76622b5 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufRoundTrip_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufRoundTrip_Test.java
@@ -42,7 +42,7 @@ class ProtobufRoundTrip_Test extends TestBase {
public String s;
public java.math.BigInteger bi;
public java.math.BigDecimal bd;
- public AllScalars() {}
+ public AllScalars() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
@Test
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufSwap_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufSwap_Test.java
index da68027b61..28b1b84dbf 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufSwap_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/protobuf/ProtobufSwap_Test.java
@@ -64,7 +64,7 @@ class ProtobufSwap_Test extends TestBase {
public static class PointSurrogate {
public int px;
public int py;
- public PointSurrogate() {}
+ public PointSurrogate() { /* Public no-arg constructor required for Juneau bean recognition. */ }
}
/** POJO -> surrogate-bean (message) swap. */
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextApplyAnnotation_Test.java
index 0e2329f449..93b52ee412 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class PrototextApplyAnnotation_Test extends TestBase {
var applier = new PrototextApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = PrototextApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextTokenizer_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextTokenizer_Test.java
index 150af82fa5..71f6e8cd39 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextTokenizer_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/prototext/PrototextTokenizer_Test.java
@@ -495,13 +495,16 @@ class PrototextTokenizer_Test {
@Test void b41_directReadBoolean_invalid() {
// Hits the error path in readBoolean (line 535) — non-boolean integer and non-bool ident.
- assertThrows(ParseException.class, () -> tok("42").readBoolean());
- assertThrows(ParseException.class, () -> tok("\"true\"").readBoolean());
+ var t1 = tok("42");
+ assertThrows(ParseException.class, t1::readBoolean);
+ var t2 = tok("\"true\"");
+ assertThrows(ParseException.class, t2::readBoolean);
}
@Test void b42_directReadBoolean_unknownIdent() {
// Unknown identifier (not in the true/false/t/f/1/0 set) — falls through to the error path.
- assertThrows(ParseException.class, () -> tok("yes").readBoolean());
+ var t = tok("yes");
+ assertThrows(ParseException.class, t::readBoolean);
}
@Test void b43_invalidEscape_endOfStream() {
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/soap/SoapXmlApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/soap/SoapXmlApplyAnnotation_Test.java
index 5bf4abde91..fd4d8b2b95 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/soap/SoapXmlApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/soap/SoapXmlApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class SoapXmlApplyAnnotation_Test extends TestBase {
var applier = new SoapXmlApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = SoapXmlApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/ArrayRecordStream_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/ArrayRecordStream_Test.java
index 81a116ec2d..de72d545cd 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/ArrayRecordStream_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/ArrayRecordStream_Test.java
@@ -92,7 +92,7 @@ class ArrayRecordStream_Test extends TestBase {
public Bean(String name, int age) { this.name = name; this.age = age; }
}
- /** Self-similar bean for the deep-nesting / self-reference array-element rows (TODO-175ab Item 2). */
+ /** Self-similar bean for the deep-nesting / self-reference array-element rows (175ab Item 2). */
public static class Node {
public String id;
public Node child;
@@ -343,7 +343,8 @@ class ArrayRecordStream_Test extends TestBase {
var baos = new ByteArrayOutputStream();
try (var w = MsgPackSerializer.DEFAULT.serializeArrayRecords(baos, 1)) {
w.write(new Bean("a", 1));
- assertThrows(IllegalStateException.class, () -> w.write(new Bean("b", 2)));
+ var overflow = new Bean("b", 2);
+ assertThrows(IllegalStateException.class, () -> w.write(overflow));
}
}
@@ -366,13 +367,13 @@ class ArrayRecordStream_Test extends TestBase {
}
// =====================================================================================
- // Self-reference / cycle as an array element — TODO-175ab Item 2. A cycle must surface as a
+ // Self-reference / cycle as an array element — 175ab Item 2. A cycle must surface as a
// controlled failure, never a raw StackOverflowError, on the streaming write path.
// =====================================================================================
@ParameterizedTest
@EnumSource(value = Format.class, names = {"JSON", "JSON5", "CBOR", "MSGPACK"})
- void h02_selfReferenceArrayElementIsHandled(Format fmt) throws Exception {
+ void h02_selfReferenceArrayElementIsHandled(Format fmt) {
var a = new Node("a", null);
a.child = a; // self-reference
assertDoesNotThrow(() -> {
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/BinaryNativeKind_GenericConsumer_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/BinaryNativeKind_GenericConsumer_Test.java
index 0869005595..d62df6b332 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/BinaryNativeKind_GenericConsumer_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/BinaryNativeKind_GenericConsumer_Test.java
@@ -49,11 +49,7 @@ class BinaryNativeKind_GenericConsumer_Test extends TestBase {
if (t == TokenType.END_OF_STREAM)
break;
switch (t) {
- case VALUE_NUMBER:
- case VALUE_STRING:
- case VALUE_BINARY:
- case VALUE_NULL:
- case VALUE_BOOLEAN:
+ case VALUE_NUMBER, VALUE_STRING, VALUE_BINARY, VALUE_NULL, VALUE_BOOLEAN:
sb.append(t).append('(');
switch (r.getNativeKind()) {
case CBOR_TAG:
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/FormatStreamingCapability_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/FormatStreamingCapability_Test.java
index 0578a09523..2aaf4ec64a 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/FormatStreamingCapability_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/FormatStreamingCapability_Test.java
@@ -53,7 +53,7 @@ import org.junit.jupiter.api.*;
* ({@link RecordReadable#isRecordStreaming()}, {@link ArrayRecordReadable#isArrayRecordStreaming()}
* and the writable equivalents) on every format's convenience parser/serializer class and on its
* per-invocation session. Asserts the convenience-class flag agrees with the session flag (the
- * TODO-175aa reader/writer-mirror invariant) so a drift between the two surfaces is caught.
+ * 175aa reader/writer-mirror invariant) so a drift between the two surfaces is caught.
*/
class FormatStreamingCapability_Test extends TestBase {
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/RecordStream_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/RecordStream_Test.java
index 97b791fbc7..85b3c81ca0 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/RecordStream_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/RecordStream_Test.java
@@ -202,7 +202,7 @@ class RecordStream_Test extends TestBase {
public Deep2D(List<List<Flat>> g, Flat[][] m) { this.grid = g; this.matrix = m; }
}
- /** Self-similar bean used for the deep-nesting and self-reference/cycle matrix rows (TODO-175ab Item 2). */
+ /** Self-similar bean used for the deep-nesting and self-reference/cycle matrix rows (175ab Item 2). */
public static class Node {
public String id;
public Node child;
@@ -391,7 +391,7 @@ class RecordStream_Test extends TestBase {
}
// =====================================================================================
- // Very-deeply-nested structure (5+ levels) — TODO-175ab Item 2 (recursion-limit row)
+ // Very-deeply-nested structure (5+ levels) — 175ab Item 2 (recursion-limit row)
// =====================================================================================
@ParameterizedTest
@@ -418,7 +418,7 @@ class RecordStream_Test extends TestBase {
}
// =====================================================================================
- // Self-reference / cycle — TODO-175ab Item 2 (depends on the 175aa PojoWalker cycle guard).
+ // Self-reference / cycle — 175ab Item 2 (depends on the 175aa PojoWalker cycle guard).
// Per-format cycle handling legitimately differs: most formats (json, json5, cbor, msgpack,
// hjson, uon, oapi) surface a self-reference as a *controlled* failure — a SerializeException
// (the base session converts a StackOverflowError into a recursion message) or the PojoWalker
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/StreamInternals_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/StreamInternals_Test.java
index ea26299b5e..22300a65d5 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/StreamInternals_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/stream/StreamInternals_Test.java
@@ -205,13 +205,13 @@ class StreamInternals_Test extends TestBase {
assertEquals("\"" + uuid + "\"", emit(uuid));
}
- @Test void a23_recursionGuardOnCollection() throws Exception {
+ @Test void a23_recursionGuardOnCollection() {
var l = new ArrayList<Object>();
l.add(l);
assertThrowsWithMessage(IllegalStateException.class, "Recursion detected", () -> emit(l));
}
- @Test void a24_recursionGuardOnMap() throws Exception {
+ @Test void a24_recursionGuardOnMap() {
var m = new LinkedHashMap<String, Object>();
m.put("self", m);
assertThrowsWithMessage(IllegalStateException.class, "Recursion detected", () -> emit(m));
@@ -524,7 +524,9 @@ class StreamInternals_Test extends TestBase {
throw new ParseException("boom-read");
}
@Override public boolean isStreaming() { return true; }
- @Override public void close() {}
+ @Override public void close() {
+ // No-op: this stub holds no underlying resource to release.
+ }
}
@Test void e01_streamHappyPath() throws Exception {
@@ -573,8 +575,12 @@ class StreamInternals_Test extends TestBase {
@Override public String getNumberLexeme() { return null; }
@Override public boolean getBool() { return false; }
@Override public byte[] getBinary() { return null; }
- @Override public void skipChildren() {}
- @Override public void close() {}
+ @Override public void skipChildren() {
+ // No-op: the stub never sits on a structural token, so there are no children to skip.
+ }
+ @Override public void close() {
+ // No-op: this stub holds no underlying resource to release.
+ }
}
/** Minimal TokenWriter stub that overrides only the abstract methods, leaving object()/write() defaults. */
@@ -593,8 +599,12 @@ class StreamInternals_Test extends TestBase {
@Override public TokenWriter bool(boolean value) { return this; }
@Override public TokenWriter nil() { return this; }
@Override public TokenWriter binary(byte[] value) { return this; }
- @Override public void flush() {}
- @Override public void close() {}
+ @Override public void flush() {
+ // No-op: this stub buffers nothing, so there is nothing to flush.
+ }
+ @Override public void close() {
+ // No-op: this stub holds no underlying resource to release.
+ }
}
@Test void f01_tokenReaderCanReadDefaultIsFalse() throws Exception {
@@ -604,7 +614,7 @@ class StreamInternals_Test extends TestBase {
}
}
- @Test void f02_tokenReaderReadDefaultsThrow() throws Exception {
+ @Test void f02_tokenReaderReadDefaultsThrow() {
var cm = MarshallingContext.DEFAULT.getClassMeta(Integer.class);
try (var r = new StubTokenReader()) {
assertThrows(UnsupportedOperationException.class, () -> r.read(Integer.class));
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/toml/TomlTokenizer_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/toml/TomlTokenizer_Test.java
index 4f2e7c1e4d..43a9f821a9 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/toml/TomlTokenizer_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/toml/TomlTokenizer_Test.java
@@ -540,47 +540,56 @@ class TomlTokenizer_Test extends TestBase {
@Test
void j19_readIntegerEmptyHexThrows() {
- assertThrows(ParseException.class, () -> t("0x").readInteger());
+ var tok = t("0x");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j20_readIntegerEmptyOctalThrows() {
- assertThrows(ParseException.class, () -> t("0o").readInteger());
+ var tok = t("0o");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j21_readIntegerEmptyBinaryThrows() {
- assertThrows(ParseException.class, () -> t("0b").readInteger());
+ var tok = t("0b");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j22_readIntegerEmptyThrows() {
- assertThrows(ParseException.class, () -> t("").readInteger());
+ var tok = t("");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j23_readIntegerLeadingZerosThrows() {
- assertThrows(ParseException.class, () -> t("01").readInteger());
+ var tok = t("01");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j24_readIntegerOverflowDecimal() {
- assertThrows(ParseException.class, () -> t("99999999999999999999").readInteger());
+ var tok = t("99999999999999999999");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j25_readIntegerOverflowHex() {
- assertThrows(ParseException.class, () -> t("0xFFFFFFFFFFFFFFFFF").readInteger());
+ var tok = t("0xFFFFFFFFFFFFFFFFF");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j26_readIntegerOverflowOctal() {
- assertThrows(ParseException.class, () -> t("0o7777777777777777777777").readInteger());
+ var tok = t("0o7777777777777777777777");
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
void j27_readIntegerOverflowBinary() {
- assertThrows(ParseException.class, () -> t("0b" + "1".repeat(80)).readInteger());
+ var tok = t("0b" + "1".repeat(80));
+ assertThrows(ParseException.class, tok::readInteger);
}
@Test
@@ -650,12 +659,14 @@ class TomlTokenizer_Test extends TestBase {
@Test
void k11_readFloatEmptyThrows() {
- assertThrows(ParseException.class, () -> t("").readFloat());
+ var tok = t("");
+ assertThrows(ParseException.class, tok::readFloat);
}
@Test
void k12_readFloatBareSignThrows() {
- assertThrows(ParseException.class, () -> t("-q").readFloat());
+ var tok = t("-q");
+ assertThrows(ParseException.class, tok::readFloat);
}
//-----------------------------------------------------------------------------------------------------------------
@@ -671,7 +682,8 @@ class TomlTokenizer_Test extends TestBase {
void l02_specialPosInfNotSupported() {
// readSpecialFloat does not accept +inf (only "inf" without sign or "-inf"); // NOSONAR
// note: the parser session has its own parseSpecialFloat that does accept "+inf".
- assertThrows(ParseException.class, () -> t("+inf").readSpecialFloat());
+ var tok = t("+inf");
+ assertThrows(ParseException.class, tok::readSpecialFloat);
}
@Test
@@ -696,7 +708,8 @@ class TomlTokenizer_Test extends TestBase {
@Test
void l07_specialInvalid() {
- assertThrows(ParseException.class, () -> t("bogus").readSpecialFloat());
+ var tok = t("bogus");
+ assertThrows(ParseException.class, tok::readSpecialFloat);
}
@Test
@@ -720,18 +733,21 @@ class TomlTokenizer_Test extends TestBase {
@Test
void m03_booleanInvalid() {
- assertThrows(ParseException.class, () -> t("xyz").readBoolean());
+ var tok = t("xyz");
+ assertThrows(ParseException.class, tok::readBoolean);
}
@Test
void m04_booleanWrongPrefix() {
// starts with 't' but not "true"
- assertThrows(ParseException.class, () -> t("trxx").readBoolean());
+ var tok = t("trxx");
+ assertThrows(ParseException.class, tok::readBoolean);
}
@Test
void m05_booleanWrongFalsePrefix() {
- assertThrows(ParseException.class, () -> t("flxxx").readBoolean());
+ var tok = t("flxxx");
+ assertThrows(ParseException.class, tok::readBoolean);
}
@Test
@@ -745,7 +761,8 @@ class TomlTokenizer_Test extends TestBase {
@Test
void n01_expectEofMidWordThrows() {
- assertThrows(ParseException.class, () -> t("tru").readBoolean());
+ var tok = t("tru");
+ assertThrows(ParseException.class, tok::readBoolean);
}
//-----------------------------------------------------------------------------------------------------------------
@@ -799,7 +816,8 @@ class TomlTokenizer_Test extends TestBase {
@Test
void o08_readDateTimeEmptyThrows() {
- assertThrows(ParseException.class, () -> t("").readDateTime());
+ var tok = t("");
+ assertThrows(ParseException.class, tok::readDateTime);
}
@ParameterizedTest
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/uon/UonApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/uon/UonApplyAnnotation_Test.java
index 5fb9b59b79..9488935ab2 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/uon/UonApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/uon/UonApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class UonApplyAnnotation_Test extends TestBase {
var applier = new UonApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = UonApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/urlencoding/UrlEncodingApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/urlencoding/UrlEncodingApplyAnnotation_Test.java
index 225bd85409..a9db62d80a 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/urlencoding/UrlEncodingApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/urlencoding/UrlEncodingApplyAnnotation_Test.java
@@ -50,7 +50,6 @@ class UrlEncodingApplyAnnotation_Test extends TestBase {
var applier = new UrlEncodingApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = UrlEncodingApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/utils/Iso8601Utils_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/utils/Iso8601Utils_Test.java
index c1980fa8b7..033a19d081 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/utils/Iso8601Utils_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/utils/Iso8601Utils_Test.java
@@ -634,4 +634,132 @@ class Iso8601Utils_Test extends TestBase {
var r = Iso8601Utils.fromEpochMillis(0L, BC.getClassMeta(String.class), UTC);
assertNull(r);
}
+
+ //------------------------------------------------------------------------------------------------------------------
+ // parseDuration — state-machine sniff/manual edge cases (replaces former regex implementation).
+ // These lock in the exact accept/reject and value behavior across signs, fractions, HOCON units,
+ // whitespace, and the lenient junk-skipping of the manual parser.
+ //------------------------------------------------------------------------------------------------------------------
+
+ @Test void v01_parseDuration_integer_signed_positive() {
+ assertEquals(Duration.ofMillis(500), Iso8601Utils.parseDuration("+500", null));
+ }
+
+ @Test void v02_parseDuration_integer_signed_negative() {
+ assertEquals(Duration.ofMillis(-500), Iso8601Utils.parseDuration("-500", null));
+ }
+
+ @Test void v03_parseDuration_decimal_signedNegative_seconds() {
+ assertEquals(Duration.ofSeconds(-2, -250_000_000), Iso8601Utils.parseDuration("-2.25", null));
+ }
+
+ @Test void v04_parseDuration_hocon_ns() {
+ assertEquals(Duration.ofNanos(5), Iso8601Utils.parseDuration("5ns", null));
+ }
+
+ @Test void v05_parseDuration_hocon_us() {
+ assertEquals(Duration.ofNanos(5_000), Iso8601Utils.parseDuration("5us", null));
+ }
+
+ @Test void v06_parseDuration_hocon_minutes() {
+ assertEquals(Duration.ofMinutes(5), Iso8601Utils.parseDuration("5m", null));
+ }
+
+ @Test void v07_parseDuration_hocon_hours() {
+ assertEquals(Duration.ofHours(5), Iso8601Utils.parseDuration("5h", null));
+ }
+
+ @Test void v08_parseDuration_hocon_days() {
+ assertEquals(Duration.ofDays(5), Iso8601Utils.parseDuration("5d", null));
+ }
+
+ @Test void v09_parseDuration_hocon_fractional() {
+ assertEquals(Duration.ofMillis(1500), Iso8601Utils.parseDuration("1.5s", null));
+ }
+
+ @Test void v10_parseDuration_uppercaseUnit_notHocon_throws() {
+ // Uppercase units are NOT accepted by the HOCON sniff (lowercase-only) and have no PT prefix,
+ // so the manual parser returns null and Duration.parse rejects the value.
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("500MS", null));
+ }
+
+ @Test void v11_parseDuration_manual_whitespaceBetweenNumberAndUnit() {
+ assertEquals(Duration.ofHours(1), Iso8601Utils.parseDuration("PT1 H", null));
+ }
+
+ @Test void v12_parseDuration_manual_strayJunkBetweenComponents_rejected() {
+ // Strict parser: stray embedded characters are no longer silently skipped — the value is rejected
+ // (manual returns null → Duration.parse rejects "PT1Hfoo2M").
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1Hfoo2M", null));
+ }
+
+ @Test void v13_parseDuration_manual_doubledDot_rejected() {
+ // Strict parser: a malformed multi-dot number is rejected rather than partially parsed.
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1.2.3H", null));
+ }
+
+ @Test void v16_parseDuration_manual_trailingJunk_rejected() {
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1H30M45Sjunk", null));
+ }
+
+ @Test void v17_parseDuration_manual_leadingJunkAfterT_rejected() {
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PTfoo1H", null));
+ }
+
+ @Test void v18_parseDuration_manual_embeddedLetters_rejected() {
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1H2Mxyz", null));
+ }
+
+ @Test void v19_parseDuration_manual_strayPunctuation_rejected() {
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1H!2M", null));
+ }
+
+ @Test void v20_parseDuration_manual_leadingDotNoInteger_rejected() {
+ // "PT.5H": the leading bare dot is stray punctuation, not a valid component start.
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT.5H", null));
+ }
+
+ @Test void v21_parseDuration_manual_consecutiveDots_rejected() {
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1..2H", null));
+ }
+
+ @Test void v22_parseDuration_manual_whitespaceInsideNumber_rejected() {
+ // A space splitting two digit runs is no longer skipped; "1 0H" is malformed.
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1 0H", null));
+ }
+
+ @Test void v14_parseDuration_manual_dotWithoutFraction_throws() {
+ // "PT1.H": the dot is not followed by a digit, so no number/unit pair matches; manual returns
+ // null and Duration.parse rejects "PT1.H".
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parseDuration("PT1.H", null));
+ }
+
+ @Test void v15_parseDuration_manual_multipleComponents() {
+ assertEquals(Duration.ofHours(1).plusMinutes(30).plusSeconds(45), Iso8601Utils.parseDuration("PT1H30M45S", null));
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // parsePeriod — state-machine sniff edge cases (replaces former regex implementation).
+ //------------------------------------------------------------------------------------------------------------------
+
+ @Test void w01_parsePeriod_integer_signedPositive_days() {
+ assertEquals(Period.ofDays(10), Iso8601Utils.parsePeriod("+10", null));
+ }
+
+ @Test void w02_parsePeriod_integer_signedNegative_days() {
+ assertEquals(Period.ofDays(-10), Iso8601Utils.parsePeriod("-10", null));
+ }
+
+ @Test void w03_parsePeriod_iso8601_weeks() {
+ assertEquals(Period.ofWeeks(2), Iso8601Utils.parsePeriod("P2W", PeriodFormat.ISO_8601));
+ }
+
+ @Test void w04_parsePeriod_invalidTimeDesignator_throws() {
+ // "P1H" is not a bare integer and not a valid Period (H is a time component) → Period.parse rejects.
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parsePeriod("P1H", PeriodFormat.ISO_8601));
+ }
+
+ @Test void w05_parsePeriod_nonNumericGarbage_throws() {
+ assertThrows(RuntimeException.class, () -> Iso8601Utils.parsePeriod("abc", PeriodFormat.ISO_8601));
+ }
}
diff --git a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/xml/XmlApplyAnnotation_Test.java b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/xml/XmlApplyAnnotation_Test.java
index 8a0cafa420..9c01b7eb9b 100644
--- a/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/xml/XmlApplyAnnotation_Test.java
+++ b/juneau-core/juneau-marshall/src/test/java/org/apache/juneau/marshall/xml/XmlApplyAnnotation_Test.java
@@ -75,7 +75,6 @@ class XmlApplyAnnotation_Test extends TestBase {
var applier = new XmlApplyAnnotation.Applier(vr);
var b = MarshallingContext.DEFAULT.copy();
var a = XmlApplyAnnotation.DEFAULT;
- applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b);
- // No exception = early-return branch was taken
+ assertDoesNotThrow(() -> applier.apply(AnnotationInfo.of(ClassInfo.of(Object.class), a), b));
}
}
diff --git a/juneau-core/juneau-test-utils/src/main/java/org/apache/juneau/XmlTestUtils.java b/juneau-core/juneau-test-utils/src/main/java/org/apache/juneau/XmlTestUtils.java
new file mode 100644
index 0000000000..172f299927
--- /dev/null
+++ b/juneau-core/juneau-test-utils/src/main/java/org/apache/juneau/XmlTestUtils.java
@@ -0,0 +1,141 @@
+/*
+ * 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 org.apache.juneau;
+
+import static org.apache.juneau.commons.utils.Utils.*;
+
+import java.util.regex.*;
+
+/**
+ * Shared test-support utilities for validating XML output.
+ */
+public final class XmlTestUtils {
+
+ private XmlTestUtils() {}
+
+ /**
+ * Validates that the whitespace is correct in the specified XML.
+ *
+ * @param out The XML to validate.
+ * @throws Exception If the whitespace/indentation in the XML is incorrect.
+ */
+ @SuppressWarnings({
+ "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
+ })
+ public static void checkXmlWhitespace(String out) throws Exception {
+ if (out.indexOf('\u0000') != -1) {
+ for (var s : out.split("\u0000"))
+ checkXmlWhitespace(s);
+ return;
+ }
+
+ var indent = -1;
+ // Whitespace-validation patterns. The lookbehind on the trailing '>' distinguishes start tags ('(?<!/)')
+ // from self-closing tags ('(?<=/)') in a single linear pass, avoiding the super-linear backtracking of the
+ // previous '.*'/nested-quantifier forms (java:S8786).
+ var startTag = Pattern.compile("^(\\s*)<[^/>][^>]*(?<!/)>$");
+ var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
+ var combinedTag = Pattern.compile("^(\\s*)<[^/>][^>]*(?<=/)>$");
+ var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
+ var lines = out.split("\n");
+ try {
+ for (var i = 0; i < lines.length; i++) {
+ var line = lines[i];
+ var m = startTag.matcher(line);
+ if (m.matches()) {
+ indent++;
+ if (m.group(1).length() != indent)
+ throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
+ continue;
+ }
+ m = endTag.matcher(line);
+ if (m.matches()) {
+ if (m.group(1).length() != indent)
+ throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
+ indent--;
+ continue;
+ }
+ m = combinedTag.matcher(line);
+ if (m.matches()) {
+ indent++;
+ if (m.group(1).length() != indent)
+ throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
+ indent--;
+ continue;
+ }
+ m = contentOnly.matcher(line);
+ if (m.matches()) {
+ indent++;
+ if (m.group(1).length() != indent)
+ throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
+ indent--;
+ continue;
+ }
+ var twc = tagWithContentIndent(line);
+ if (twc != -1) {
+ indent++;
+ if (twc != indent)
+ throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
+ indent--;
+ continue;
+ }
+ throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
+ }
+ if (indent != -1)
+ throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
+ } catch (Exception e) {
+ printLines(lines);
+ throw e;
+ }
+ }
+
+ /**
+ * Returns the leading-whitespace indent width of a line that is a single tag-with-content line.
+ *
+ * <p>
+ * A tag-with-content line is one that — after any optional leading whitespace — starts with an opening tag and
+ * ends with a closing tag, such as <c><foo>bar</foo></c>. This is a linear-time replacement for the
+ * <c>^(\s*)<[^>]+>.*</[^>]+>$</c> regular expression that avoids its super-linear backtracking.
+ *
+ * @param line The line to test.
+ * @return
+ * The number of leading whitespace characters on the line, or <c>-1</c> if the line is not a single
+ * tag-with-content line.
+ */
+ private static int tagWithContentIndent(String line) {
+ var n = line.length();
+ var w = 0;
+ while (w < n) {
+ var c = line.charAt(w);
+ if (c != ' ' && c != '\t' && c != '\n' && c != '\u000B' && c != '\f' && c != '\r')
+ break;
+ w++;
+ }
+ if (n - w < 2 || line.charAt(w) != '<' || line.charAt(n - 1) != '>')
+ return -1;
+ var open = line.indexOf('>', w); // End of the opening tag.
+ if (open - w < 2)
+ return -1;
+ var close = line.lastIndexOf("</"); // Start of the final closing tag.
+ if (close <= open || close + 3 > n - 1)
+ return -1;
+ for (var j = close + 2; j < n - 1; j++) // Closing tag name must not contain '>'.
+ if (line.charAt(j) == '>')
+ return -1;
+ return w;
+ }
+}
diff --git a/juneau-integration-tests/src/test/java/org/apache/juneau/TestUtils.java b/juneau-integration-tests/src/test/java/org/apache/juneau/TestUtils.java
index faf154112c..ea9060ea8c 100644
--- a/juneau-integration-tests/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-integration-tests/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,20 +17,14 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
import java.io.*;
-import java.lang.reflect.*;
import java.net.*;
-import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
import org.apache.juneau.bean.swagger.Swagger;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
import org.apache.juneau.junit.bct.*;
import org.apache.juneau.marshall.serializer.*;
@@ -142,17 +136,8 @@ import org.junit.jupiter.api.*;
* @see BeanConverter
* @see BasicBeanConverter
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
-
public static void assertEqualsAll(Object...values) {
for (var i = 1; i < values.length; i++) {
assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
@@ -166,15 +151,6 @@ public class TestUtils extends Utils {
assertEquals(expected, json5(value));
}
- /**
- * Converts the specified object to a string and then replaces any newlines with pipes for easy comparison during testing.
- * @param value
- */
- public static String pipedLines(Object value) {
- return r(value).replaceAll("\\r?\\n", "|");
- }
-
-
public static void assertNotEqualsAny(Object actual, Object...values) {
assertNotNull(actual, "Value was null.");
for (var i = 0; i < values.length; i++) {
@@ -196,13 +172,6 @@ public class TestUtils extends Utils {
return t;
}
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
var exception = Assertions.assertThrows(expectedType, executable);
var messages = getMessages(exception);
@@ -210,117 +179,6 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- public static final void checkXmlWhitespace(String out) throws SerializeException {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^\\s/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^\\s>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>[^<]*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new SerializeException("Wrong indentation detected on start tag line ''{0}''", i+1);
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new SerializeException("Wrong indentation detected on end tag line ''{0}''", i+1);
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new SerializeException("Wrong indentation detected on combined tag line ''{0}''", i+1);
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new SerializeException("Wrong indentation detected on content-only line ''{0}''", i+1);
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new SerializeException("Wrong indentation detected on tag-with-content line ''{0}''", i+1);
- indent--;
- continue;
- }
- throw new SerializeException("Unmatched whitespace line at line number ''{0}''", i+1);
- }
- if (indent != -1)
- throw new SerializeException("Possible unmatched tag. indent=''{0}''", indent);
- } catch (SerializeException e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
@@ -360,10 +218,6 @@ public class TestUtils extends Utils {
return safe(()->json5(o, c));
}
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
/**
* Creates a reader from the specified string.
*
@@ -374,36 +228,6 @@ public class TestUtils extends Utils {
return new StringReader(in);
}
- /**
- * Temporarily sets the default system locale to the specified locale.
- * Use {@link #unsetLocale()} to unset it.
- *
- * @param v The locale to use as the default until {@link #unsetLocale()} is called.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- * Use {@link #unsetTimeZone()} to unset it.
- *
- * @param v The timezone ID passed to {@link TimeZone#getTimeZone(String)}.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
/**
* Constructs a {@link URL} object from a string.
*/
@@ -411,129 +235,12 @@ public class TestUtils extends Utils {
return safe(()->new URI(value).toURL());
}
- /**
- * Test whitespace and generated schema.
- */
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
/**
* Test whitespace and generated schema.
*/
public static final void validateXml(Object o, XmlSerializer s) throws Exception {
s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- *
- * <p>Uses a depth-tracking parser to handle nested elements correctly, even with malformed HTML.</p>
- *
- * <h5 class='section'>Examples:</h5>
- * <pre>
- * // Extract all div elements with class='tag-block'
- * List<String> blocks = extractXml(html, "div", Map.of("class", "tag-block"));
- *
- * // Extract all span elements (no attribute filtering)
- * List<String> spans = extractXml(html, "span", null);
- *
- * // Extract divs with multiple attributes
- * List<String> divs = extractXml(html, "div", Map.of("class", "header", "id", "main"));
- * </pre>
- *
- * @param html The HTML/XML content to parse
- * @param elementName The element name to extract (e.g., "div", "span")
- * @param withAttributes Optional map of attribute name/value pairs that must match.
- * Pass null or empty map to match all elements of the given name.
- * @return List of HTML content strings (inner content of matching elements)
- */
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list(); // NOAI
-
- if (html == null || elementName == null) {
- return results;
- }
-
- // Find all opening tags of the specified element
- var openTag = "<" + elementName;
- int searchPos = 0;
-
- while ((searchPos = html.indexOf(openTag, searchPos)) != -1) {
- // Find the end of the opening tag
- int tagEnd = html.indexOf('>', searchPos);
- if (tagEnd == -1) break;
-
- var fullOpenTag = html.substring(searchPos, tagEnd + 1);
-
- // Check if attributes match
- var matches = true;
- if (withAttributes != null && !withAttributes.isEmpty()) {
- for (var entry : withAttributes.entrySet()) {
- var attrName = entry.getKey();
- var attrValue = entry.getValue();
-
- // Look for attribute in the tag (handle both single and double quotes)
- var pattern1 = attrName + "=\"" + attrValue + "\"";
- var pattern2 = attrName + "='" + attrValue + "'";
-
- if (!fullOpenTag.contains(pattern1) && !fullOpenTag.contains(pattern2)) {
- matches = false;
- break;
- }
- }
- }
-
- if (matches) {
- // Find matching closing tag by tracking depth
- int contentStart = tagEnd + 1;
- int depth = 1;
- int pos = contentStart;
-
- while (pos < html.length() && depth > 0) {
- // Look for next opening or closing tag of same element
- int nextOpen = html.indexOf("<" + elementName, pos);
- int nextClose = html.indexOf("</" + elementName + ">", pos);
-
- // Validate that nextOpen is actually an opening tag
- if (nextOpen != -1 && (nextOpen < nextClose || nextClose == -1)) {
- if (nextOpen + elementName.length() + 1 < html.length()) {
- var nextChar = html.charAt(nextOpen + elementName.length() + 1);
- if (nextChar == ' ' || nextChar == '>' || nextChar == '/') {
- depth++;
- pos = nextOpen + elementName.length() + 1;
- continue;
- }
- }
- // Not a valid opening tag, skip it
- pos = nextOpen + 1;
- continue;
- }
-
- if (nextClose != -1) {
- depth--;
- if (depth == 0) {
- // Found matching close tag
- results.add(html.substring(contentStart, nextClose));
- break;
- }
- pos = nextClose + elementName.length() + 3;
- } else {
- // No more closing tags
- break;
- }
- }
- }
-
- searchPos = tagEnd + 1;
- }
-
- return results;
+ XmlTestUtils.checkXmlWhitespace(xml);
}
}
\ No newline at end of file
diff --git a/juneau-integration-tests/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java b/juneau-integration-tests/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
index 0f9642e3b9..263f5f9945 100644
--- a/juneau-integration-tests/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
+++ b/juneau-integration-tests/src/test/java/org/apache/juneau/a/rttests/RoundTrip_Tester.java
@@ -18,6 +18,7 @@ package org.apache.juneau.a.rttests;
import static java.util.Collections.*;
import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.XmlTestUtils.*;
import static org.apache.juneau.commons.utils.CollectionUtils.*;
import static org.apache.juneau.commons.utils.StringUtils.*;
import java.lang.reflect.*;
diff --git a/juneau-integration-tests/src/test/java/org/apache/juneau/rest/server/RestContext_ValueAgainstConfig_Test.java b/juneau-integration-tests/src/test/java/org/apache/juneau/rest/server/RestContext_ValueAgainstConfig_Test.java
index d985937932..daee08de01 100644
--- a/juneau-integration-tests/src/test/java/org/apache/juneau/rest/server/RestContext_ValueAgainstConfig_Test.java
+++ b/juneau-integration-tests/src/test/java/org/apache/juneau/rest/server/RestContext_ValueAgainstConfig_Test.java
@@ -113,7 +113,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
String nested;
}
- @Test void a01_happyPath_configKeyResolves() throws Exception {
+ @Test void a01_happyPath_configKeyResolves() {
var rc = build(HappyPathResource.class);
var bean = (HappyPathResource) rc.getResource();
assertEquals("secret-A", bean.apiKey);
@@ -136,7 +136,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
String fromSettings;
}
- @Test void a02_fallThrough_defaultBranch_andSettings() throws Exception {
+ @Test void a02_fallThrough_defaultBranch_andSettings() {
Settings.get().setGlobal("valcfg.absent.from.settings", "from-settings");
try {
var rc = build(FallThroughResource.class);
@@ -165,7 +165,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
String foo;
}
- @Test void a03_resourceIsolation_each_sees_own_config() throws Exception {
+ @Test void a03_resourceIsolation_each_sees_own_config() {
var rcA = build(IsolationResourceA.class);
var rcB = build(IsolationResourceB.class);
assertEquals("A", ((IsolationResourceA) rcA.getResource()).foo);
@@ -185,7 +185,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
String fromSettings;
}
- @Test void a04_noConfig_falls_through_to_settings_only() throws Exception {
+ @Test void a04_noConfig_falls_through_to_settings_only() {
Settings.get().setGlobal("valcfg.noconfig.fromSettings", "settings-value");
try {
var rc = build(NoConfigResource.class);
@@ -217,7 +217,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
@Rest(config=CFG_CHILD)
public static class InheritanceChild extends InheritanceParent {}
- @Test void a05_inheritance_child_wins_parent_fills_gaps() throws Exception {
+ @Test void a05_inheritance_child_wins_parent_fills_gaps() {
var rc = build(InheritanceChild.class);
var bean = (InheritanceChild) rc.getResource();
// Child wins on collision: shared resolves to child's value.
@@ -228,7 +228,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
assertEquals("child-value", bean.childOnly);
}
- @Test void a05b_parent_alone_resolves_parent_keys() throws Exception {
+ @Test void a05b_parent_alone_resolves_parent_keys() {
var rc = build(InheritanceParent.class);
var bean = (InheritanceParent) rc.getResource();
assertEquals("parent-shared", bean.shared);
@@ -251,7 +251,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
Supplier<String> value;
}
- @Test void a06_setGlobal_overrides_resource_config() throws Exception {
+ @Test void a06_setGlobal_overrides_resource_config() {
var rc = build(OverrideResource.class);
var bean = (OverrideResource) rc.getResource();
// No override active → resource Config value wins.
@@ -269,7 +269,7 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
assertEquals("from-config", bean.value.get());
}
- @Test void a06b_setLocal_overrides_resource_config() throws Exception {
+ @Test void a06b_setLocal_overrides_resource_config() {
var rc = build(OverrideResource.class);
var bean = (OverrideResource) rc.getResource();
@@ -339,14 +339,14 @@ class RestContext_ValueAgainstConfig_Test extends TestBase {
// Acceptance #8 — Registration is under name "rest.config" in the resource BeanStore.
//------------------------------------------------------------------------------------------------------------------
- @Test void a08_propertySource_registered_under_rest_config_name() throws Exception {
+ @Test void a08_propertySource_registered_under_rest_config_name() {
var rc = build(HappyPathResource.class);
var src = rc.getBeanStore().getBean(PropertySource.class, "rest.config").orElse(null);
assertNotNull(src, "Expected a PropertySource bean registered as \"rest.config\" in the resource BeanStore.");
assertEquals("secret-A", src.get("api.key").value().orElse(null));
}
- @Test void a08b_no_config_no_registration() throws Exception {
+ @Test void a08b_no_config_no_registration() {
// A @Rest resource with no config= attribute and no @Bean Config method should leave the
// "rest.config" slot empty (rawConfig.get() returns an empty Config that the bridge skips).
var rc = build(NoConfigResource.class);
diff --git a/juneau-microservice/juneau-microservice-jetty/src/main/java/org/apache/juneau/microservice/jetty/JettyServerComponent.java b/juneau-microservice/juneau-microservice-jetty/src/main/java/org/apache/juneau/microservice/jetty/JettyServerComponent.java
index 0cb615bb68..4af2d103f5 100644
--- a/juneau-microservice/juneau-microservice-jetty/src/main/java/org/apache/juneau/microservice/jetty/JettyServerComponent.java
+++ b/juneau-microservice/juneau-microservice-jetty/src/main/java/org/apache/juneau/microservice/jetty/JettyServerComponent.java
@@ -83,6 +83,10 @@ import jakarta.servlet.*;
public class JettyServerComponent implements MicroserviceListener {
private static final String KEY_SERVLET_CONTEXT_HANDLER = "ServletContextHandler";
+
+ @SuppressWarnings({
+ "java:S2245" // Used only to pick a benign ephemeral listen port (non security-sensitive); SecureRandom is unnecessary.
+ })
private static final Random RANDOM = new Random();
/** Default bounded graceful-shutdown drain timeout applied to the Jetty server when none is configured. */
diff --git a/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/JettyGracefulShutdown_Test.java b/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/JettyGracefulShutdown_Test.java
index 07379b67e0..dabdbcc304 100644
--- a/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/JettyGracefulShutdown_Test.java
+++ b/juneau-microservice/juneau-microservice-jetty/src/test/java/org/apache/juneau/microservice/jetty/JettyGracefulShutdown_Test.java
@@ -29,7 +29,7 @@ import org.eclipse.jetty.server.*;
import org.junit.jupiter.api.*;
/**
- * Graceful-shutdown / readiness-gating tests for {@link JettyServerComponent} (TODO-174a).
+ * Graceful-shutdown / readiness-gating tests for {@link JettyServerComponent}.
*
* <p>
* Verifies the zero-downtime shutdown contract on the Jetty side:
diff --git a/juneau-microservice/juneau-microservice-test/src/main/java/org/apache/juneau/microservice/test/EphemeralJettyServerConfig.java b/juneau-microservice/juneau-microservice-test/src/main/java/org/apache/juneau/microservice/test/EphemeralJettyServerConfig.java
index 60f12d5c8b..17f33c677b 100644
--- a/juneau-microservice/juneau-microservice-test/src/main/java/org/apache/juneau/microservice/test/EphemeralJettyServerConfig.java
+++ b/juneau-microservice/juneau-microservice-test/src/main/java/org/apache/juneau/microservice/test/EphemeralJettyServerConfig.java
@@ -16,7 +16,10 @@
*/
package org.apache.juneau.microservice.test;
+import java.time.*;
+
import org.apache.juneau.commons.inject.*;
+import org.apache.juneau.microservice.jetty.*;
import org.eclipse.jetty.ee11.servlet.*;
import org.eclipse.jetty.server.*;
@@ -58,4 +61,22 @@ public class EphemeralJettyServerConfig {
server.setHandler(sch);
return server;
}
+
+ /**
+ * Disables the 30s graceful-shutdown drain wait for integration tests.
+ *
+ * <p>
+ * {@code JettyServerComponent} applies a 30s {@code stopTimeout} default to support zero-downtime k8s
+ * rollouts. In ephemeral test servers there are no load balancers or in-flight production traffic, so
+ * the drain wait only adds ~1s per test class to the suite runtime. Setting it to zero restores fast
+ * shutdown.
+ *
+ * @return {@link JettySettings} with {@code stopTimeout} set to zero.
+ */
+ @Bean
+ public JettySettings jettySettings() {
+ return JettySettings.create()
+ .stopTimeout(Duration.ZERO)
+ .build();
+ }
}
diff --git a/juneau-petstore/juneau-petstore-core/src/main/resources/htdocs/petstore-ui.html b/juneau-petstore/juneau-petstore-core/src/main/resources/htdocs/petstore-ui.html
index c48c66ae09..7248eecd5a 100644
--- a/juneau-petstore/juneau-petstore-core/src/main/resources/htdocs/petstore-ui.html
+++ b/juneau-petstore/juneau-petstore-core/src/main/resources/htdocs/petstore-ui.html
@@ -43,9 +43,9 @@
<body>
<div id="root"></div>
- <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
- <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>
- <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
+ <script src="https://unpkg.com/react@18.3.1/umd/react.production.min.js" integrity="sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z" crossorigin="anonymous"></script>
+ <script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js" integrity="sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1" crossorigin="anonymous"></script>
+ <script src="https://unpkg.com/@babel/standalone@8.0.3/babel.min.js" integrity="sha384-fsMuX1qrlL2OwY1g8apML4JcSv2aYFaMXKQIjzX+OOveqSCCdmIMjwNQRoralXGe" crossorigin="anonymous"></script>
<script type="text/babel">
const { useState, useEffect } = React;
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/remote/RemoteClient.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/remote/RemoteClient.java
index 1d77235375..333d84a7a8 100644
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/remote/RemoteClient.java
+++ b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/remote/RemoteClient.java
@@ -760,6 +760,9 @@ public final class RemoteClient {
* and wrapper returns ({@link Optional}/{@link Future}/{@link CompletableFuture}) are never retried.
* </ul>
*/
+ @SuppressWarnings({
+ "java:S3776" // Cognitive complexity acceptable for the gated retry loop (verb/body/status safety gates + backoff).
+ })
private Object processReturn(RequestSupplier reqSupplier, RrpcInterfaceMethodMeta methodMeta, Method method, boolean throwOnError, String acceptFallback) throws Exception {
var returnMode = methodMeta.getReturnType();
var returnType = method.getReturnType();
diff --git a/juneau-rest/juneau-rest-common-classic/src/test/java/org/apache/juneau/TestUtils.java b/juneau-rest/juneau-rest-common-classic/src/test/java/org/apache/juneau/TestUtils.java
index 03e68fabbc..b7dc904e6e 100644
--- a/juneau-rest/juneau-rest-common-classic/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-rest/juneau-rest-common-classic/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,22 +17,13 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
import org.junit.jupiter.api.*;
/**
@@ -41,45 +32,11 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
- public static void assertEqualsAll(Object...values) {
- for (var i = 1; i < values.length; i++) {
- assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
- }
- }
-
- public static void assertNotEqualsAny(Object actual, Object...values) {
- assertNotNull(actual, "Value was null.");
- for (var i = 0; i < values.length; i++) {
- assertNotEquals(values[i], actual, fs("Element at index {0} unexpectedly matched. expected={1}, actual={2}", i, values[i], s(actual)));
- }
- }
-
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
}
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
@@ -89,120 +46,6 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^\\s/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^\\s>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>[^<]*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
@@ -214,140 +57,10 @@ public class TestUtils extends Utils {
return new ByteArrayInputStream(in.getBytes());
}
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
/**
* Creates a reader from the specified string.
*/
public static final StringReader reader(String in) {
return new StringReader(in);
}
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*)?>", Pattern.CASE_INSENSITIVE);
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
- }
-
- public static String pipedLines(Object value) {
- return r(value).replaceAll("\\r?\\n", "|");
- }
}
diff --git a/juneau-rest/juneau-rest-common/src/main/java/org/apache/juneau/http/remote/RrpcInterfaceMeta.java b/juneau-rest/juneau-rest-common/src/main/java/org/apache/juneau/http/remote/RrpcInterfaceMeta.java
index f31b43c405..fa3ed56901 100644
--- a/juneau-rest/juneau-rest-common/src/main/java/org/apache/juneau/http/remote/RrpcInterfaceMeta.java
+++ b/juneau-rest/juneau-rest-common/src/main/java/org/apache/juneau/http/remote/RrpcInterfaceMeta.java
@@ -447,8 +447,9 @@ public final class RrpcInterfaceMeta {
return methodMetas.get(method);
}
- // Complexity inherent to interface metadata parsing; refactoring would reduce readability without benefit.
- @SuppressWarnings("java:S3776")
+ @SuppressWarnings({
+ "java:S3776" // Cognitive complexity inherent to per-verb interface-metadata parsing; refactoring would reduce readability without benefit.
+ })
private static Optional<RrpcInterfaceMethodMeta> buildMethodMeta(Method m) {
if (m.isAnnotationPresent(RemoteGet.class)) {
var a = m.getAnnotation(RemoteGet.class);
diff --git a/juneau-rest/juneau-rest-common/src/test/java/org/apache/juneau/TestUtils.java b/juneau-rest/juneau-rest-common/src/test/java/org/apache/juneau/TestUtils.java
index a27efd3aa2..fb824fcc09 100644
--- a/juneau-rest/juneau-rest-common/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-rest/juneau-rest-common/src/test/java/org/apache/juneau/TestUtils.java
@@ -17,22 +17,12 @@
package org.apache.juneau;
import static java.util.stream.Collectors.*;
-import static org.apache.juneau.commons.utils.CollectionUtils.*;
-import static org.apache.juneau.commons.utils.ThrowableUtils.*;
import static org.apache.juneau.marshall.marshaller.MarshallUtils.*;
import static org.junit.jupiter.api.Assertions.*;
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.util.*;
-import java.util.regex.*;
import java.util.stream.*;
-import org.apache.juneau.commons.bean.*;
import org.apache.juneau.commons.utils.*;
-import org.apache.juneau.marshall.serializer.*;
-import org.apache.juneau.marshall.xml.*;
import org.junit.jupiter.api.*;
/**
@@ -41,22 +31,19 @@ import org.junit.jupiter.api.*;
* <p>Contains a marshall-compatible subset of the methods available in the full {@code TestUtils}
* in {@code juneau-integration-tests}. Methods that depend on {@code juneau-rest-*} modules are excluded.</p>
*/
-@SuppressWarnings({
- "unchecked", // BeanTester cast and generic type handling in test utilities
- "java:S1172" // Parameters kept for consistent method signatures across test utilities
-})
public class TestUtils extends Utils {
- private static final ThreadLocal<TimeZone> SYSTEM_TIME_ZONE = new ThreadLocal<>();
-
- public static final ThreadLocal<Locale> SYSTEM_LOCALE = new ThreadLocal<>();
-
public static void assertEqualsAll(Object...values) {
for (var i = 1; i < values.length; i++) {
assertEquals(values[0], values[i], fs("Elements at index {0} and {1} did not match. {0}={2}, {1}={3}", 0, i, r(values[0]), r(values[i])));
}
}
+ public static String assertJson(String expected, Object value) {
+ assertEquals(expected, json5(value));
+ return expected;
+ }
+
public static void assertNotEqualsAny(Object actual, Object...values) {
assertNotNull(actual, "Value was null.");
for (var i = 0; i < values.length; i++) {
@@ -64,27 +51,6 @@ public class TestUtils extends Utils {
}
}
- public static void assertSerialized(Object actual, WriterSerializer s, String expected) {
- assertEquals(expected, s.toString(actual));
- }
-
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- public static <T extends Throwable> T assertThrowable(Class<? extends Throwable> expectedType, String expectedSubstring, T t) {
- assertTrue(expectedType.isInstance(t), fs("Expected throwable of type: {0}.\nActual: {1}", expectedType.getName(), t == null ? "null" : t.getClass().getName()));
- var messages = getMessages(t);
- assertTrue(messages.contains(expectedSubstring), fs("Expected message to contain: {0}.\nActual:\n{1}", expectedSubstring, messages));
- return t;
- }
-
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = Assertions.assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), fs("Expected message to contain: {0}.\nActual:\n{1}", x, messages)));
- return exception;
- }
-
public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, String expectedSubstring, org.junit.jupiter.api.function.Executable executable) {
var exception = Assertions.assertThrows(expectedType, executable);
var messages = getMessages(exception);
@@ -92,265 +58,7 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Validates that the whitespace is correct in the specified XML.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void checkXmlWhitespace(String out) throws Exception {
- if (out.indexOf('\u0000') != -1) {
- for (var s : out.split("\u0000"))
- checkXmlWhitespace(s);
- return;
- }
-
- var indent = -1;
- var startTag = Pattern.compile("^(\\s*)<[^\\s/>]++(\\s++\\S++=['\"]\\S*+['\"])*+\\s*+>$");
- var endTag = Pattern.compile("^(\\s*)</[^>]+>$");
- var combinedTag = Pattern.compile("^(\\s*)<[^\\s>/]++(\\s++\\S++=['\"]\\S*+['\"])*+\\s*+/>$");
- var contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$");
- var tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$");
- var lines = out.split("\n");
- try {
- for (var i = 0; i < lines.length; i++) {
- var line = lines[i];
- var m = startTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on start tag line ''" + (i+1) + "''");
- continue;
- }
- m = endTag.matcher(line);
- if (m.matches()) {
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on end tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = combinedTag.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on combined tag line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = contentOnly.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on content-only line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- m = tagWithContent.matcher(line);
- if (m.matches()) {
- indent++;
- if (m.group(1).length() != indent)
- throw new Exception("Wrong indentation detected on tag-with-content line ''" + (i+1) + "''");
- indent--;
- continue;
- }
- throw new Exception("Unmatched whitespace line at line number ''" + (i+1) + "''");
- }
- if (indent != -1)
- throw new Exception("Possible unmatched tag. indent=''" + indent + "''");
- } catch (Exception e) {
- printLines(lines);
- throw e;
- }
- }
-
- /**
- * Returns the value of the specified field/property on the specified object.
- * First looks for getter, then looks for field.
- * Methods and fields can be any visibility.
- */
- public static Object getBeanProp(Object o, String name) {
- return safe(() -> {
- var f = (Field)null;
- var c = o.getClass();
- var n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
- var m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("is"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get"+n) && x.getParameterCount() == 0 && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals("get") && x.getParameterCount() == 1 && x.getParameterTypes()[0] == String.class && x.getAnnotation(BeanIgnore.class) == null).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o, name);
- }
- var c2 = c;
- while (f == null && c2 != null) {
- f = Arrays.stream(c2.getDeclaredFields()).filter(x -> x.getName().equals(name)).findFirst().orElse(null);
- c2 = c2.getSuperclass();
- }
- if (f != null) {
- f.setAccessible(true);
- return f.get(o);
- }
- m = Arrays.stream(c.getMethods()).filter(x -> x.getName().equals(name) && x.getParameterCount() == 0).findFirst().orElse(null);
- if (m != null) {
- m.setAccessible(true);
- return m.invoke(o);
- }
- throw rex("Property {0} not found on object of type {1}", name, cn(o));
- });
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Throwable::getCause).takeWhile(e -> e != null).map(Throwable::getMessage).collect(joining("\n"));
}
-
- /**
- * Creates an input stream from the specified string.
- */
- public static final ByteArrayInputStream inputStream(String in) {
- return new ByteArrayInputStream(in.getBytes());
- }
-
- public static String json(Object o) {
- return json5(o);
- }
-
- public static <T> T json(String o, Class<T> c) {
- return safe(()->json5(o, c));
- }
-
- public static <T> T jsonRoundTrip(T o, Class<T> c) {
- return json(json(o), c);
- }
-
- /**
- * Creates a reader from the specified string.
- */
- public static final StringReader reader(String in) {
- return new StringReader(in);
- }
-
- /**
- * Temporarily sets the default system locale to the specified locale.
- */
- public static final void setLocale(Locale v) {
- SYSTEM_LOCALE.set(Locale.getDefault());
- Locale.setDefault(v);
- }
-
- /**
- * Temporarily sets the default system timezone to the specified timezone ID.
- */
- public static final synchronized void setTimeZone(String v) {
- SYSTEM_TIME_ZONE.set(TimeZone.getDefault());
- TimeZone.setDefault(TimeZone.getTimeZone(v));
- }
-
- public static final void unsetLocale() {
- Locale.setDefault(SYSTEM_LOCALE.get());
- }
-
- public static final synchronized void unsetTimeZone() {
- TimeZone.setDefault(SYSTEM_TIME_ZONE.get());
- }
-
- /**
- * Constructs a {@link URL} object from a string.
- */
- public static URL url(String value) {
- return safe(()->new URI(value).toURL());
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o) throws Exception {
- validateXml(o, XmlSerializer.DEFAULT_NS_SQ);
- }
-
- /**
- * Validates XML whitespace and namespace formatting on a serialized object.
- */
- @SuppressWarnings({
- "java:S112" // Generic exception throw required; checked exception wrapping would obscure test intent.
- })
- public static final void validateXml(Object o, XmlSerializer s) throws Exception {
- s = s.copy().ws().ns().addNamespaceUrisToRoot().build();
- var xml = s.serialize(o);
- checkXmlWhitespace(xml);
- }
-
- public static final <T> BeanTester<T> testBean(T bean) {
- return (BeanTester<T>) new BeanTester<>().bean(bean);
- }
-
- /**
- * Extracts HTML/XML elements from a string based on element name and attributes.
- */
- public static List<String> extractXml(String html, String elementName, Map<String,String> withAttributes) {
- List<String> results = list();
- if (html == null || elementName == null)
- return results;
- var pattern = Pattern.compile("<" + Pattern.quote(elementName) + "(\\s[^>]*+)?>", Pattern.CASE_INSENSITIVE);
- @SuppressWarnings({
- "unused" // Unused parameters/variables kept for consistent method signatures across test utilities.
- })
- var matcher = pattern.matcher(html);
- var depth = 0;
- var startPos = -1;
- for (var i = 0; i < html.length(); i++) {
- var remaining = html.substring(i);
- if (remaining.startsWith("<" + elementName) && (remaining.length() == elementName.length() + 1 || !Character.isLetterOrDigit(remaining.charAt(elementName.length() + 1)))) {
- if (depth == 0) {
- var tagEnd = html.indexOf('>', i);
- if (tagEnd == -1) break;
- var tag = html.substring(i, tagEnd + 1);
- var matches = withAttributes == null || withAttributes.isEmpty();
- if (!matches && withAttributes != null) {
- matches = true;
- for (var entry : withAttributes.entrySet()) {
- if (!tag.contains(entry.getKey() + "=\"" + entry.getValue() + "\"") && !tag.contains(entry.getKey() + "='" + entry.getValue() + "'")) {
- matches = false;
- break;
- }
- }
- }
- if (matches) {
- startPos = i;
- depth = 1;
- i = tagEnd;
- }
- } else {
- depth++;
- }
- } else if (remaining.startsWith("</" + elementName + ">")) {
- if (depth == 1 && startPos >= 0) {
- results.add(html.substring(startPos, i + elementName.length() + 3));
- depth = 0;
- startPos = -1;
- } else if (depth > 1) {
- depth--;
- }
- }
- }
- return results;
- }
-
- public static String assertJson(String expected, Object value) {
- assertEquals(expected, json5(value));
- return expected;
- }
-
- public static String pipedLines(Object value) {
- return r(value).replaceAll("\\r?\\n", "|");
- }
}
diff --git a/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java b/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java
index c81477f149..c7cce31675 100644
--- a/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java
+++ b/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java
@@ -26,6 +26,7 @@ import java.util.concurrent.*;
import org.apache.juneau.commons.inject.*;
import org.apache.juneau.marshall.*;
import org.apache.juneau.marshall.json.*;
+import org.apache.juneau.marshall.parser.*;
import org.apache.juneau.rest.client.*;
import org.apache.juneau.rest.client.RestRequest;
import org.apache.juneau.rest.server.*;
@@ -193,6 +194,7 @@ public final class MockRestClient implements Closeable {
private final Object impl;
private String contextPath;
private BeanStore overridingBeanStore;
+ private Parser defaultParser;
private Builder(Object impl) {
this.impl = impl;
@@ -239,6 +241,32 @@ public final class MockRestClient implements Closeable {
return this;
}
+ /**
+ * Sets an explicit default parser used when the response {@code Content-Type} matches no registered parser.
+ *
+ * <p>
+ * Setting this also causes the client to advertise the parser's media types in the {@code Accept} header,
+ * so the server must be able to produce that content type. Omit this (the default) when the target
+ * resource does not have a JSON serializer configured.
+ *
+ * <h5 class='section'>Example:</h5>
+ * <p class='bjava'>
+ * <jk>try</jk> (<jv>client</jv> = MockRestClient.<jsm>builder</jsm>(MyJsonResource.<jk>class</jk>)
+ * .defaultParser(JsonParser.<jsf>DEFAULT</jsf>)
+ * .build()) {
+ * <jk>var</jk> <jv>api</jv> = <jv>client</jv>.getClient().remote(MyApi.<jk>class</jk>);
+ * <jv>api</jv>.someMethod();
+ * }
+ * </p>
+ *
+ * @param value The parser. May be <jk>null</jk>.
+ * @return This object.
+ */
+ public Builder defaultParser(Parser value) {
+ defaultParser = value;
+ return this;
+ }
+
/**
* Builds and returns the {@link MockRestClient}.
*
@@ -268,12 +296,14 @@ public final class MockRestClient implements Closeable {
var servletPath = toValidContextPath(restContext.getFullPath());
var fullContextPath = emptyIfNull(contextPath) + emptyIfNull(servletPath);
- var transport = new JuneauRestTransport(restContext, servletPath);
- var ngClient = RestClient.builder()
- .transport(transport)
- .rootUrl("http://localhost" + fullContextPath)
- .defaultSerializer(JsonSerializer.DEFAULT)
- .build();
+ var transport = new JuneauRestTransport(restContext, servletPath);
+ var clientBuilder = RestClient.builder()
+ .transport(transport)
+ .rootUrl("http://localhost" + fullContextPath)
+ .defaultSerializer(JsonSerializer.DEFAULT);
+ if (defaultParser != null)
+ clientBuilder.defaultParser(defaultParser);
+ var ngClient = clientBuilder.build();
return new MockRestClient(ngClient);
} catch (Exception e) {
diff --git a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/RestSession.java b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/RestSession.java
index 6d898e769b..ee9684e72e 100644
--- a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/RestSession.java
+++ b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/RestSession.java
@@ -546,14 +546,8 @@ public class RestSession extends ContextSession {
var opRestContext = opSession.getContext().getContext();
if (opRestContext.isMixinContext())
opRestContext.startCall(this);
- try {
- // Resource-level authentication fold (RestAuthenticator) — runs before preCall so @RestPreCall
- // hooks, guards (roleGuard), and @Auth arg resolution all see the resolved principal/roles.
- opRestContext.authenticate(opSession);
- } catch (AuthenticationException e) {
- AuthFilter.sendChallenge(res, e);
+ if (! authenticateOrChallenge(opRestContext))
return;
- }
context.preCall(opSession);
opSession.run();
context.postCall(opSession);
@@ -572,6 +566,28 @@ public class RestSession extends ContextSession {
}
}
+ /**
+ * Runs the resource-level authentication fold ({@link RestAuthenticator}) and, on failure, writes the 401 challenge.
+ *
+ * <p>
+ * Runs before preCall so {@link RestPreCall @RestPreCall} hooks, guards (roleGuard), and {@code @Auth} arg resolution
+ * all see the resolved principal/roles.
+ *
+ * @param opRestContext The operation's REST context.
+ * @return <jk>true</jk> if the request should proceed, or <jk>false</jk> if a 401 challenge was sent and processing
+ * should stop.
+ * @throws IOException If writing the challenge response fails.
+ */
+ private boolean authenticateOrChallenge(RestContext opRestContext) throws IOException {
+ try {
+ opRestContext.authenticate(opSession);
+ return true;
+ } catch (AuthenticationException e) {
+ AuthFilter.sendChallenge(res, e);
+ return false;
+ }
+ }
+
/**
* Sets the HTTP status on this call.
*
diff --git a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/arg/TokenWriterArg.java b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/arg/TokenWriterArg.java
index 824b4962df..c16598e2d6 100644
--- a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/arg/TokenWriterArg.java
+++ b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/arg/TokenWriterArg.java
@@ -16,6 +16,8 @@
*/
package org.apache.juneau.rest.server.arg;
+import java.io.*;
+
import org.apache.juneau.commons.reflect.*;
import org.apache.juneau.http.response.*;
import org.apache.juneau.marshall.serializer.*;
@@ -77,7 +79,7 @@ public class TokenWriterArg extends SimpleRestOperationArg {
this.declaredType = declaredType;
}
- private static Object resolve(RestOpSession opSession, Class<?> declaredType) throws Exception {
+ private static Object resolve(RestOpSession opSession, Class<?> declaredType) throws IOException {
var req = opSession.getRequest();
var res = opSession.getResponse();
var match = res.getSerializerMatch();
diff --git a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/auth/AuthFilter.java b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/auth/AuthFilter.java
index c4d392dcea..fe83ccd45d 100644
--- a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/auth/AuthFilter.java
+++ b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/server/auth/AuthFilter.java
@@ -61,24 +61,6 @@ public abstract class AuthFilter implements Filter, Authenticator {
/** WWW-Authenticate response header name (RFC 7235 §4.1). */
static final String WWW_AUTHENTICATE = "WWW-Authenticate";
- /**
- * Inspects the request and returns the authentication result.
- *
- * <p>
- * Three-state return contract:
- * <ul>
- * <li>{@link Optional#empty()} — this filter does not apply to the request (e.g. no
- * {@code Authorization} header for a bearer-token filter). The chain will continue to the next filter.
- * <li>{@link Optional#of(Object) Optional.of(AuthResult)} — authentication succeeded.
- * <li>throw {@link AuthenticationException} — credentials were present but invalid.
- * </ul>
- *
- * @param req The incoming HTTP request. Never <jk>null</jk>.
- * @return The authentication result, or {@link Optional#empty()} if this filter does not apply.
- * @throws AuthenticationException If the request carries recognizable credentials that are invalid.
- */
- public abstract Optional<AuthResult> authenticate(HttpServletRequest req) throws AuthenticationException;
-
/**
* Standalone-filter entry point.
*
diff --git a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/TestUtils.java b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/TestUtils.java
index 03094a7c60..ac2fc837a0 100644
--- a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/TestUtils.java
+++ b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/TestUtils.java
@@ -56,23 +56,6 @@ public class TestUtils extends Utils {
return exception;
}
- /**
- * Asserts that the specified executable throws an exception whose chained messages contain all of
- * the specified substrings.
- *
- * @param <T> The expected exception type.
- * @param expectedType The expected exception type.
- * @param expectedSubstrings The substrings expected in the exception message chain.
- * @param executable The code expected to throw.
- * @return The thrown exception.
- */
- public static <T extends Throwable> T assertThrowsWithMessage(Class<T> expectedType, List<String> expectedSubstrings, org.junit.jupiter.api.function.Executable executable) {
- var exception = assertThrows(expectedType, executable);
- var messages = getMessages(exception);
- expectedSubstrings.forEach(x -> assertTrue(messages.contains(x), "Expected message to contain: " + x + ".\nActual:\n" + messages));
- return exception;
- }
-
private static String getMessages(Throwable t) {
return Stream.iterate(t, Objects::nonNull, Throwable::getCause).map(Throwable::getMessage).collect(Collectors.joining("\n"));
}
diff --git a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/arg/RestArgResolvers_Test.java b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/arg/RestArgResolvers_Test.java
index ce05bdbe81..24e297f7de 100644
--- a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/arg/RestArgResolvers_Test.java
+++ b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/arg/RestArgResolvers_Test.java
@@ -254,10 +254,19 @@ class RestArgResolvers_Test extends TestBase {
"QueryArg.create must return null when @Query is absent");
}
- @Test void a03_queryArg_create_throwsWhenNameMissing() {
- var pi = firstParam(Fixture.class, "queryNoName");
- assertThrows(ArgException.class, () -> QueryArg.create(pi, EMPTY_AWL),
- "QueryArg must throw ArgException when @Query has no name/value");
+ static Stream<Arguments> abc03_namedArg_create_throwsWhenNameMissing() {
+ return Stream.of(
+ Arguments.of("@Query", "queryNoName", (Function<ParameterInfo, Object>) p -> QueryArg.create(p, EMPTY_AWL)),
+ Arguments.of("@Header", "headerNoName", (Function<ParameterInfo, Object>) p -> HeaderArg.create(p, EMPTY_AWL)),
+ Arguments.of("@FormData", "formDataNoName", (Function<ParameterInfo, Object>) p -> FormDataArg.create(p, EMPTY_AWL))
+ );
+ }
+
+ @ParameterizedTest @MethodSource("abc03_namedArg_create_throwsWhenNameMissing")
+ void a03_b03_c03_namedArg_create_throwsWhenNameMissing(String annotation, String fixtureMethod, Function<ParameterInfo, Object> factory) {
+ var pi = firstParam(Fixture.class, fixtureMethod);
+ assertThrows(ArgException.class, () -> factory.apply(pi),
+ "Arg must throw ArgException when " + annotation + " has no name/value");
}
// -----------------------------------------------------------------------------------------
@@ -277,12 +286,6 @@ class RestArgResolvers_Test extends TestBase {
"HeaderArg.create must return null when @Header is absent");
}
- @Test void b03_headerArg_create_throwsWhenNameMissing() {
- var pi = firstParam(Fixture.class, "headerNoName");
- assertThrows(ArgException.class, () -> HeaderArg.create(pi, EMPTY_AWL),
- "HeaderArg must throw ArgException when @Header has no name/value");
- }
-
// -----------------------------------------------------------------------------------------
// c — FormDataArg
// -----------------------------------------------------------------------------------------
@@ -300,12 +303,6 @@ class RestArgResolvers_Test extends TestBase {
"FormDataArg.create must return null when @FormData is absent");
}
- @Test void c03_formDataArg_create_throwsWhenNameMissing() {
- var pi = firstParam(Fixture.class, "formDataNoName");
- assertThrows(ArgException.class, () -> FormDataArg.create(pi, EMPTY_AWL),
- "FormDataArg must throw ArgException when @FormData has no name/value");
- }
-
// -----------------------------------------------------------------------------------------
// d — HasQueryArg
// -----------------------------------------------------------------------------------------
@@ -678,10 +675,10 @@ class RestArgResolvers_Test extends TestBase {
static Stream<Arguments> t_contextArgs_returnsNullForUnknownType() {
return Stream.of(
- Arguments.of("RestContextArgs", (Function<ParameterInfo, Object>) p -> RestContextArgs.create(p)),
- Arguments.of("RestOpContextArgs", (Function<ParameterInfo, Object>) p -> RestOpContextArgs.create(p)),
- Arguments.of("RestOpSessionArgs", (Function<ParameterInfo, Object>) p -> RestOpSessionArgs.create(p)),
- Arguments.of("RestSessionArgs", (Function<ParameterInfo, Object>) p -> RestSessionArgs.create(p))
+ Arguments.of("RestContextArgs", (Function<ParameterInfo, Object>) RestContextArgs::create),
+ Arguments.of("RestOpContextArgs", (Function<ParameterInfo, Object>) RestOpContextArgs::create),
+ Arguments.of("RestOpSessionArgs", (Function<ParameterInfo, Object>) RestOpSessionArgs::create),
+ Arguments.of("RestSessionArgs", (Function<ParameterInfo, Object>) RestSessionArgs::create)
);
}
diff --git a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/AuthFilterChain_Test.java b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/AuthFilterChain_Test.java
index b0b60759d2..e28250fa08 100644
--- a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/AuthFilterChain_Test.java
+++ b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/AuthFilterChain_Test.java
@@ -244,7 +244,7 @@ class AuthFilterChain_Test extends TestBase {
assertSame(ALICE, ((AuthenticatedRequestWrapper) capturing.captured).getUserPrincipal());
}
- @Test void e01_authenticateReturnsFoldedResult_noResponseWrite() throws Exception {
+ @Test void e01_authenticateReturnsFoldedResult_noResponseWrite() {
var chain = AuthFilterChain.create(null)
.append(succeeds(ALICE, "admin"))
.build();
@@ -253,14 +253,14 @@ class AuthFilterChain_Test extends TestBase {
assertTrue(r.orElseThrow().getRoles().contains("admin"));
}
- @Test void e02_authenticateNoMatch_returnsEmpty() throws Exception {
+ @Test void e02_authenticateNoMatch_returnsEmpty() {
var chain = AuthFilterChain.create(null)
.append(succeeds(ALICE), "/api/*")
.build();
assertTrue(chain.authenticate(req("/public/page")).isEmpty());
}
- @Test void e03_authenticateAllEmpty_returnsEmpty() throws Exception {
+ @Test void e03_authenticateAllEmpty_returnsEmpty() {
var chain = AuthFilterChain.create(null)
.append(empty())
.build();
@@ -271,11 +271,12 @@ class AuthFilterChain_Test extends TestBase {
var chain = AuthFilterChain.create(null)
.append(fails("token bad"))
.build();
- var e = assertThrows(AuthenticationException.class, () -> chain.authenticate(req("/")));
+ var r = req("/");
+ var e = assertThrows(AuthenticationException.class, () -> chain.authenticate(r));
assertTrue(e.getHeaders().stream().anyMatch(h -> "WWW-Authenticate".equalsIgnoreCase(h.getName())));
}
- @Test void e05_authenticateRoleUnionAcrossSuccesses() throws Exception {
+ @Test void e05_authenticateRoleUnionAcrossSuccesses() {
var chain = AuthFilterChain.create(null)
.append(succeeds(ALICE, "user"))
.append(succeeds(BOB, "admin"))
@@ -286,7 +287,7 @@ class AuthFilterChain_Test extends TestBase {
assertTrue(r.getRoles().contains("admin"));
}
- @Test void e06_aggregateWithNullMessageAndNoChallenge() throws Exception {
+ @Test void e06_aggregateWithNullMessageAndNoChallenge() {
// Failure with a null message and no WWW-Authenticate header: aggregate body collapses to null and no
// challenge header is emitted (exercises the empty-body / empty-wwwAuth branches of aggregate()).
AuthFilter bare = new AuthFilter() {
@@ -295,11 +296,12 @@ class AuthFilterChain_Test extends TestBase {
}
};
var chain = AuthFilterChain.create(null).append(bare).build();
- var e = assertThrows(AuthenticationException.class, () -> chain.authenticate(req("/")));
+ var r = req("/");
+ var e = assertThrows(AuthenticationException.class, () -> chain.authenticate(r));
assertTrue(e.getHeaders().stream().noneMatch(h -> "WWW-Authenticate".equalsIgnoreCase(h.getName())));
}
- @Test void e07_authenticateWithNullContextPath() throws Exception {
+ @Test void e07_authenticateWithNullContextPath() {
// contextPath == null must not NPE; path resolves to the raw URI.
var req = mock(HttpServletRequest.class);
when(req.getRequestURI()).thenReturn("/x");
@@ -308,7 +310,7 @@ class AuthFilterChain_Test extends TestBase {
assertSame(ALICE, chain.authenticate(req).orElseThrow().getPrincipal());
}
- @Test void e08_authenticateEmptyPathBecomesRoot() throws Exception {
+ @Test void e08_authenticateEmptyPathBecomesRoot() {
// URI equals contextPath → stripped path is empty → normalized to "/".
var req = mock(HttpServletRequest.class);
when(req.getRequestURI()).thenReturn("/myapp");
diff --git a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/RestAuthenticator_Test.java b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/RestAuthenticator_Test.java
index 9c8d4507eb..7ec2eccc87 100644
--- a/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/RestAuthenticator_Test.java
+++ b/juneau-rest/juneau-rest-server/src/test/java/org/apache/juneau/rest/server/auth/RestAuthenticator_Test.java
@@ -47,7 +47,7 @@ class RestAuthenticator_Test extends TestBase {
return mock(HttpServletRequest.class);
}
- @Test void a01_ofAdaptsAuthenticator() throws Exception {
+ @Test void a01_ofAdaptsAuthenticator() {
Authenticator inner = r -> opt(AuthResult.of(ALICE, "admin"));
var ra = RestAuthenticator.of(inner);
var result = ra.authenticateRaw(req()).orElseThrow();
@@ -55,7 +55,7 @@ class RestAuthenticator_Test extends TestBase {
assertTrue(result.getRoles().contains("admin"));
}
- @Test void a02_nullSentinelReturnsEmpty() throws Exception {
+ @Test void a02_nullSentinelReturnsEmpty() {
var ra = new RestAuthenticator.Null();
assertTrue(ra.authenticateRaw(req()).isEmpty());
assertTrue(ra.authenticate(null).isEmpty());
@@ -64,16 +64,17 @@ class RestAuthenticator_Test extends TestBase {
@Test void a03_ofPropagatesAuthenticationException() {
Authenticator inner = r -> { throw new AuthenticationException("bad"); };
var ra = RestAuthenticator.of(inner);
- assertThrows(AuthenticationException.class, () -> ra.authenticateRaw(req()));
+ var request = req();
+ assertThrows(AuthenticationException.class, () -> ra.authenticateRaw(request));
}
- @Test void a04_ofEmptyResult() throws Exception {
+ @Test void a04_ofEmptyResult() {
Authenticator inner = r -> opte();
var ra = RestAuthenticator.of(inner);
assertTrue(ra.authenticateRaw(req()).isEmpty());
}
- @Test void a05_baseAuthenticateRawDelegatesToRestRequestForm() throws Exception {
+ @Test void a05_baseAuthenticateRawDelegatesToRestRequestForm() {
// A subclass that does NOT override authenticateRaw exercises the base delegate (cast → authenticate(RestRequest)).
var ra = new RestAuthenticator() {
@Override public Optional<AuthResult> authenticate(RestRequest r) {
diff --git a/perf-baseline.txt b/perf-baseline.txt
index ff937709c5..92c7d09a0a 100644
--- a/perf-baseline.txt
+++ b/perf-baseline.txt
@@ -38,10 +38,17 @@
# ignored by the per-module perf-guard parser.
# ============================================================================
-suite = 136 # reactor wall-clock; carried from FINISHED-95 (re-measure post-migration).
-juneau-integration-tests/core = 60 # carried from FINISHED-139 single-module baseline (was juneau-utest).
-juneau-integration-tests/container.springboot = 3 # carried from FINISHED-139.
-juneau-integration-tests/container.jetty = 1 # carried from FINISHED-139.
+suite = 225 # updated baseline.
+juneau-integration-tests/core = 90 # updated baseline.
+juneau-integration-tests/container.springboot = 5 # updated baseline.
+juneau-integration-tests/container.jetty = 2 # updated baseline; fast shutdown restored by EphemeralJettyServerConfig.stopTimeout(ZERO).
+juneau-bean/juneau-bean-atom/core = 0.4
+juneau-bean/juneau-bean-common/core = 1.0
+juneau-bean/juneau-bean-html5/core = 3.5
+juneau-bean/juneau-bean-mcp/core = 0.4
+juneau-bean/juneau-bean-openapi-v3/core = 0.9
+juneau-bean/juneau-bean-swagger-v2/core = 0.8
+juneau-bean/juneau-bean-jsonschema/core = 0.7
# ─── [observability] ──────────────────────────────────────────────────────────
#