From 84cebd372f6ebdaaef22653b36d98c55bacc27a0 Mon Sep 17 00:00:00 2001 From: Nic Munroe Date: Thu, 12 Sep 2024 15:36:36 -0700 Subject: [PATCH] IDE automated cleanup --- .../backstopper/apierror/ApiErrorBase.java | 2 +- .../projectspecificinfo/ProjectApiErrors.java | 4 +-- .../apierror/sample/SampleCoreApiError.java | 4 +-- .../sample/SampleProjectApiErrorsBase.java | 2 +- .../backstopper/exception/ApiException.java | 6 ++-- .../handler/ApiExceptionHandlerBase.java | 5 ++- .../GenericApiExceptionHandlerListener.java | 4 +-- .../backstopper/model/DefaultErrorDTO.java | 2 +- .../nike/backstopper/util/ApiErrorUtil.java | 3 +- .../apierror/ApiErrorBaseTest.java | 2 +- .../apierror/ApiErrorComparatorTest.java | 4 +-- .../apierror/ApiErrorWithMetadataTest.java | 6 ++-- .../apierror/SortedApiErrorSetTest.java | 6 ++-- .../ProjectApiErrorsTestBase.java | 12 +++---- .../range/IntegerRangeTest.java | 2 +- .../BarebonesCoreApiErrorForTesting.java | 2 +- .../testutil/ProjectApiErrorsForTesting.java | 2 +- .../exception/ApiExceptionTest.java | 32 ++++++++--------- .../handler/ApiExceptionHandlerBaseTest.java | 11 +++--- .../handler/ApiExceptionHandlerUtilsTest.java | 31 +++++++++-------- .../handler/ErrorResponseInfoTest.java | 6 +++- .../UnhandledExceptionHandlerBaseTest.java | 8 ++--- ...ApiExceptionHandlerListenerResultTest.java | 6 ++-- ...ataValidationErrorHandlerListenerTest.java | 34 ++++++++++++------- ...amNetworkExceptionHandlerListenerTest.java | 2 +- ...enericApiExceptionHandlerListenerTest.java | 2 +- ...ideValidationErrorHandlerListenerTest.java | 8 ++--- .../model/DefaultErrorContractDTOTest.java | 6 ++-- .../ClientDataValidationServiceTest.java | 21 ++++++------ ...ilFastServersideValidationServiceTest.java | 2 +- .../service/NoOpJsr303ValidatorTest.java | 4 +-- .../StringConvertsToClassTypeValidator.java | 12 ++----- ...tringConvertsToClassTypeValidatorTest.java | 10 +++--- ...tilWithDefaultErrorContractDTOSupport.java | 6 ++-- ...ithDefaultErrorContractDTOSupportTest.java | 2 +- ...equestInfoForLoggingServletApiAdapter.java | 2 +- ...ApiExceptionHandlerServletApiBaseTest.java | 11 ++++-- ...ledExceptionHandlerServletApiBaseTest.java | 9 ++++- ...stInfoForLoggingServletApiAdapterTest.java | 8 ++--- .../SanityCheckComponentTest.java | 2 +- ...BackstopperSpringWebFluxComponentTest.java | 2 +- ...FrameworkExceptionHandlerListenerTest.java | 2 +- ...bMvcFrameworkExceptionHandlerListener.java | 14 ++++---- .../handler/ClientfacingErrorITest.java | 4 +-- .../spring/SpringApiExceptionHandlerTest.java | 2 +- .../SpringApiExceptionHandlerUtilsTest.java | 4 +-- .../SpringUnhandledExceptionHandlerTest.java | 2 +- ...FrameworkExceptionHandlerListenerTest.java | 6 ++-- ...idationErrorToApiErrorHandlerListener.java | 3 +- ...mmonFrameworkExceptionHandlerListener.java | 24 +++++-------- ...FrameworkExceptionHandlerListenerTest.java | 8 ++--- .../java/com/nike/internal/util/Pair.java | 5 ++- .../com/nike/internal/util/StringUtils.java | 4 +-- .../error/SampleProjectApiError.java | 4 +-- .../error/SampleProjectApiError.java | 4 +-- .../reusable/error/SampleProjectApiError.java | 4 +-- 56 files changed, 196 insertions(+), 199 deletions(-) diff --git a/backstopper-core/src/main/java/com/nike/backstopper/apierror/ApiErrorBase.java b/backstopper-core/src/main/java/com/nike/backstopper/apierror/ApiErrorBase.java index 2b2d19e..dd8246b 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/apierror/ApiErrorBase.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/apierror/ApiErrorBase.java @@ -41,7 +41,7 @@ public ApiErrorBase(String name, String errorCode, String message, int httpStatu } this.metadata = (metadata.isEmpty()) - ? Collections.emptyMap() + ? Collections.emptyMap() : Collections.unmodifiableMap(new HashMap<>(metadata)); } diff --git a/backstopper-core/src/main/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrors.java b/backstopper-core/src/main/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrors.java index f25a422..4045b33 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrors.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrors.java @@ -336,7 +336,7 @@ public List getStatusCodePriorityOrder() { * the possibility of null being returned and have a strategy for picking a winner. */ public Integer determineHighestPriorityHttpStatusCode(Collection apiErrors) { - if (apiErrors == null || apiErrors.size() == 0) { + if (apiErrors == null || apiErrors.isEmpty()) { return null; } @@ -368,7 +368,7 @@ public Integer determineHighestPriorityHttpStatusCode(Collection apiEr logger.error( "None of the HTTP status codes in the ApiErrors passed to determineHighestPriorityHttpStatusCode() were" + " found in the getStatusCodePriorityOrder() list. Offending set of http status codes (these should be " - + "added to the getStatusCodePriorityOrder() list for this project): " + validStatusCodePossibilities + + "added to the getStatusCodePriorityOrder() list for this project): {}", validStatusCodePossibilities ); return null; diff --git a/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleCoreApiError.java b/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleCoreApiError.java index c3825e1..6741e0e 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleCoreApiError.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleCoreApiError.java @@ -20,7 +20,7 @@ /** * A sample/example of some core errors that many APIs are likely to need. Any given {@link ProjectApiErrors} could - * return these as its {@link ProjectApiErrors#getCoreApiErrors()} if the error codes and messages associated with these + * return these as its {@code ProjectApiErrors#getCoreApiErrors()} if the error codes and messages associated with these * are fine for your project (see {@link SampleProjectApiErrorsBase} for a base implementation that does exactly that). * *

In practice most organizations should copy/paste this class and customize the error codes and messages for their @@ -64,7 +64,7 @@ public enum SampleCoreApiError implements ApiError { SampleCoreApiError(int errorCode, String message, int httpStatusCode) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode )); } diff --git a/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleProjectApiErrorsBase.java b/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleProjectApiErrorsBase.java index 2eaf163..c732d65 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleProjectApiErrorsBase.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/apierror/sample/SampleProjectApiErrorsBase.java @@ -26,7 +26,7 @@ public abstract class SampleProjectApiErrorsBase extends ProjectApiErrors { private static final List SAMPLE_CORE_API_ERRORS_AS_LIST = - Arrays.asList(SampleCoreApiError.values()); + Arrays.asList(SampleCoreApiError.values()); @Override protected List getCoreApiErrors() { diff --git a/backstopper-core/src/main/java/com/nike/backstopper/exception/ApiException.java b/backstopper-core/src/main/java/com/nike/backstopper/exception/ApiException.java index 6c5109a..51a2c43 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/exception/ApiException.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/exception/ApiException.java @@ -253,9 +253,9 @@ public StackTraceLoggingBehavior getStackTraceLoggingBehavior() { */ @SuppressWarnings("WeakerAccess") public static class Builder { - private List apiErrors = new ArrayList<>(); - private List> extraDetailsForLogging = new ArrayList<>(); - private List>> extraResponseHeaders = new ArrayList<>(); + private final List apiErrors = new ArrayList<>(); + private final List> extraDetailsForLogging = new ArrayList<>(); + private final List>> extraResponseHeaders = new ArrayList<>(); private String message; private Throwable cause; private StackTraceLoggingBehavior stackTraceLoggingBehavior; diff --git a/backstopper-core/src/main/java/com/nike/backstopper/handler/ApiExceptionHandlerBase.java b/backstopper-core/src/main/java/com/nike/backstopper/handler/ApiExceptionHandlerBase.java index f14b312..219ae8e 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/handler/ApiExceptionHandlerBase.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/handler/ApiExceptionHandlerBase.java @@ -280,8 +280,7 @@ protected ErrorResponseInfo doHandleApiException( // Add connection type to our extra logging data if appropriate. This particular log message is here so it can // be done in one spot rather than trying to track down all the different places we're handling // NetworkExceptionBase subclasses (and possibly missing some by accident). - if (coreException instanceof NetworkExceptionBase) { - NetworkExceptionBase neb = ((NetworkExceptionBase)coreException); + if (coreException instanceof NetworkExceptionBase neb) { extraDetailsForLogging.add(Pair.of("connection_type", neb.getConnectionType())); } @@ -306,7 +305,7 @@ protected ErrorResponseInfo doHandleApiException( + "investigated and fixed. Search for %s=%s in the logs to find the log message that contains the " + "details of the request along with the full stack trace of the original exception. " + "unfiltered_api_errors=%s", - trackingLogKey, trackingUuid.toString(), utils.concatenateErrorCollection(clientErrors) + trackingLogKey, trackingUuid, utils.concatenateErrorCollection(clientErrors) )); filteredClientErrors = Collections.singletonList(genericServiceError); highestPriorityStatusCode = genericServiceError.getHttpStatusCode(); diff --git a/backstopper-core/src/main/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListener.java b/backstopper-core/src/main/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListener.java index 74e5af6..ba9a496 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListener.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListener.java @@ -24,11 +24,9 @@ public class GenericApiExceptionHandlerListener implements ApiExceptionHandlerLi @Override public ApiExceptionHandlerListenerResult shouldHandleException(Throwable ex) { // We only care about ApiExceptions. - if (!(ex instanceof ApiException)) + if (!(ex instanceof ApiException apiException)) return ApiExceptionHandlerListenerResult.ignoreResponse(); - ApiException apiException = ((ApiException)ex); - // Add all the ApiErrors from the exception. SortedApiErrorSet errors = new SortedApiErrorSet(); errors.addAll(apiException.getApiErrors()); diff --git a/backstopper-core/src/main/java/com/nike/backstopper/model/DefaultErrorDTO.java b/backstopper-core/src/main/java/com/nike/backstopper/model/DefaultErrorDTO.java index 29a2476..9403a39 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/model/DefaultErrorDTO.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/model/DefaultErrorDTO.java @@ -80,7 +80,7 @@ public DefaultErrorDTO(String code, String message, Map metadata if (metadata == null) metadata = Collections.emptyMap(); this.metadata = (metadata.isEmpty()) - ? Collections.emptyMap() + ? Collections.emptyMap() : Collections.unmodifiableMap(new HashMap<>(metadata)); } } diff --git a/backstopper-core/src/main/java/com/nike/backstopper/util/ApiErrorUtil.java b/backstopper-core/src/main/java/com/nike/backstopper/util/ApiErrorUtil.java index e649922..4ab7d1e 100644 --- a/backstopper-core/src/main/java/com/nike/backstopper/util/ApiErrorUtil.java +++ b/backstopper-core/src/main/java/com/nike/backstopper/util/ApiErrorUtil.java @@ -25,8 +25,7 @@ public static int generateApiErrorHashCode(ApiError apiError) { public static boolean isApiErrorEqual(ApiError apiError, Object o) { if (apiError == o) return true; if (apiError == null) return false; - if (o == null || !(o instanceof ApiError)) return false; - ApiError that = (ApiError) o; + if (o == null || !(o instanceof ApiError that)) return false; return apiError.getHttpStatusCode() == that.getHttpStatusCode() && Objects.equals(apiError.getName(), that.getName()) && Objects.equals(apiError.getErrorCode(), that.getErrorCode()) && diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorBaseTest.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorBaseTest.java index 5a85f90..1b4828b 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorBaseTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorBaseTest.java @@ -74,7 +74,7 @@ public void noMetadataStringErrorCodeConstructor_creates_as_expected() { // then assertThat(aeb.getName()).isEqualTo(name); - assertThat(aeb.getErrorCode()).isEqualTo(String.valueOf(errorCode)); + assertThat(aeb.getErrorCode()).isEqualTo(errorCode); assertThat(aeb.getMessage()).isEqualTo(message); assertThat(aeb.getHttpStatusCode()).isEqualTo(httpStatusCode); } diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorComparatorTest.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorComparatorTest.java index 6453702..33b7468 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorComparatorTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorComparatorTest.java @@ -19,7 +19,7 @@ * Tests the functionality of {@link com.nike.backstopper.apierror.ApiErrorComparator} */ public class ApiErrorComparatorTest { - private ApiErrorComparator comparator = new ApiErrorComparator(); + private final ApiErrorComparator comparator = new ApiErrorComparator(); @Test public void should_return_0_for_reference_equality() { @@ -109,7 +109,7 @@ public void should_return_0_if_names_and_metadata_are_equal() { public void should_use_hashCode_comparison_when_names_are_equal_and_metadata_is_different() { // given ApiError apiError = new ApiErrorBase(UUID.randomUUID().toString(), 42, "foo", 400); - ApiError errorWithMetadata = new ApiErrorWithMetadata(apiError, Pair.of("bar", (Object)UUID.randomUUID().toString())); + ApiError errorWithMetadata = new ApiErrorWithMetadata(apiError, Pair.of("bar", UUID.randomUUID().toString())); assertThat(apiError.hashCode()).isNotEqualTo(errorWithMetadata.hashCode()); // when diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorWithMetadataTest.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorWithMetadataTest.java index 61bb3ec..3117b57 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorWithMetadataTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/ApiErrorWithMetadataTest.java @@ -97,7 +97,7 @@ public void constructor_throws_IllegalArgumentException_if_delegate_is_null() { @Test public void convenience_constructor_throws_IllegalArgumentException_if_delegate_is_null() { // when - Throwable ex = catchThrowable(() -> new ApiErrorWithMetadata(null, Pair.of("foo", (Object)"bar"))); + Throwable ex = catchThrowable(() -> new ApiErrorWithMetadata(null, Pair.of("foo", "bar"))); // then assertThat(ex) @@ -152,7 +152,7 @@ public void convenience_constructor_supports_delegate_with_null_or_empty_metadat @Test public void constructor_supports_null_or_empty_extra_metadata(boolean useNull) { // given - Map extraMetadataToUse = (useNull) ? null : Collections.emptyMap(); + Map extraMetadataToUse = (useNull) ? null : Collections.emptyMap(); // when ApiErrorWithMetadata awm = new ApiErrorWithMetadata(delegateWithMetadata, extraMetadataToUse); @@ -270,7 +270,7 @@ public void equals_returns_expected_result(boolean changeName, boolean changeErr changeMetadata? metadata2 : metadata); ApiErrorWithMetadata awm = new ApiErrorWithMetadata(aeb, extraMetadata); - ApiErrorWithMetadata awm2 = new ApiErrorWithMetadata(aeb2, hasExtraMetadata? extraMetadata : Collections.emptyMap()); + ApiErrorWithMetadata awm2 = new ApiErrorWithMetadata(aeb2, hasExtraMetadata? extraMetadata : Collections.emptyMap()); // then assertThat(awm.equals(awm2)).isEqualTo(isEqual); diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/SortedApiErrorSetTest.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/SortedApiErrorSetTest.java index 6510767..eb556b4 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/SortedApiErrorSetTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/SortedApiErrorSetTest.java @@ -41,7 +41,7 @@ public void default_constructor_uses_ApiErrorComparator() { assertThat(set).isEmpty(); } - private Random random = new Random(); + private final Random random = new Random(); private ApiError generateRandomApiError() { return new ApiErrorBase(UUID.randomUUID().toString(), random.nextInt(), UUID.randomUUID().toString(), random.nextInt()); @@ -128,8 +128,8 @@ public void singletonSortedSetOf_returns_singleton_set_with_supplied_arg_and_def public void default_config_supports_multiple_errors_that_differ_only_by_metadata() { // given ApiError baseError = new ApiErrorBase(UUID.randomUUID().toString(), 42, "foo", 400); - ApiError errorWithMetadata1 = new ApiErrorWithMetadata(baseError, Pair.of("foo", (Object)"bar")); - ApiError errorWithMetadata2 = new ApiErrorWithMetadata(baseError, Pair.of("foo", (Object)"notbar")); + ApiError errorWithMetadata1 = new ApiErrorWithMetadata(baseError, Pair.of("foo", "bar")); + ApiError errorWithMetadata2 = new ApiErrorWithMetadata(baseError, Pair.of("foo", "notbar")); SortedApiErrorSet set = new SortedApiErrorSet(); assertThat(set).isEmpty(); diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrorsTestBase.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrorsTestBase.java index b12b3eb..1d462af 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrorsTestBase.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/ProjectApiErrorsTestBase.java @@ -65,7 +65,7 @@ public void determineHighestPriorityHttpStatusCodeShouldReturnNullForNullErrorCo @Test public void determineHighestPriorityHttpStatusCodeShouldReturnNullForEmptyErrorCollection() { - assertThat(getProjectApiErrors().determineHighestPriorityHttpStatusCode(Collections.emptyList()), nullValue()); + assertThat(getProjectApiErrors().determineHighestPriorityHttpStatusCode(Collections.emptyList()), nullValue()); } @Test @@ -200,7 +200,7 @@ public void convertToApiErrorShouldUseFallbackOnInvalidValue() { @Test(expected = IllegalStateException.class) public void verifyErrorsAreInRangeShouldThrowExceptionIfListIncludesNonCoreApiErrorAndRangeIsNull() { - ProjectApiErrorsForTesting.withProjectSpecificData(Collections.singletonList(new ApiErrorBase("blah", 99001, "stuff", 400)), null); + ProjectApiErrorsForTesting.withProjectSpecificData(Collections.singletonList(new ApiErrorBase("blah", 99001, "stuff", 400)), null); } @Test @@ -224,7 +224,7 @@ public void verifyErrorsAreInRangeShouldNotThrowExceptionIfListIncludesCoreApiEr @Test(expected = IllegalStateException.class) public void verifyErrorsAreInRangeShouldThrowExceptionIfListIncludesErrorOutOfRange() { ProjectApiErrorsForTesting.withProjectSpecificData( - Collections.singletonList(new ApiErrorBase("blah", 1, "stuff", 400)), + Collections.singletonList(new ApiErrorBase("blah", 1, "stuff", 400)), new ProjectSpecificErrorCodeRange() { @Override public boolean isInRange(ApiError error) { @@ -305,11 +305,7 @@ private boolean areWrappersOfEachOther(ApiError error1, ApiError error2) { boolean errorCodeMatches = Objects.equals(error1.getErrorCode(), error2.getErrorCode()); boolean messageMatches = Objects.equals(error1.getMessage(), error2.getMessage()); boolean httpStatusCodeMatches = error1.getHttpStatusCode() == error2.getHttpStatusCode(); - if (errorCodeMatches && messageMatches && httpStatusCodeMatches) { - return true; - } - - return false; + return errorCodeMatches && messageMatches && httpStatusCodeMatches; } @Test diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/range/IntegerRangeTest.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/range/IntegerRangeTest.java index 33c01fb..911e13f 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/range/IntegerRangeTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/projectspecificinfo/range/IntegerRangeTest.java @@ -18,7 +18,7 @@ @RunWith(DataProviderRunner.class) public class IntegerRangeTest { - private IntegerRange rangeOfOneToFour = IntegerRange.of(1, 4); + private final IntegerRange rangeOfOneToFour = IntegerRange.of(1, 4); @Test public void constructor_throws_exception_if_upper_range_less_than_lower_range() { diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/BarebonesCoreApiErrorForTesting.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/BarebonesCoreApiErrorForTesting.java index 9984eef..07cf64c 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/BarebonesCoreApiErrorForTesting.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/BarebonesCoreApiErrorForTesting.java @@ -49,7 +49,7 @@ public enum BarebonesCoreApiErrorForTesting implements ApiError { } BarebonesCoreApiErrorForTesting(int errorCode, String message, int httpStatusCode) { - this(new ApiErrorBase("delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode)); + this(new ApiErrorBase("delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode)); } @Override diff --git a/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/ProjectApiErrorsForTesting.java b/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/ProjectApiErrorsForTesting.java index 91cd7a1..a181bac 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/ProjectApiErrorsForTesting.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/apierror/testutil/ProjectApiErrorsForTesting.java @@ -16,7 +16,7 @@ */ public abstract class ProjectApiErrorsForTesting extends ProjectApiErrors { - private static final List BAREBONES_CORE_API_ERRORS_AS_LIST = Arrays.asList(BarebonesCoreApiErrorForTesting.values()); + private static final List BAREBONES_CORE_API_ERRORS_AS_LIST = Arrays.asList(BarebonesCoreApiErrorForTesting.values()); public static ProjectApiErrorsForTesting withProjectSpecificData(final List projectSpecificErrors, final ProjectSpecificErrorCodeRange projectSpecificErrorCodeRange) { diff --git a/backstopper-core/src/test/java/com/nike/backstopper/exception/ApiExceptionTest.java b/backstopper-core/src/test/java/com/nike/backstopper/exception/ApiExceptionTest.java index 5393374..2857731 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/exception/ApiExceptionTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/exception/ApiExceptionTest.java @@ -27,23 +27,23 @@ @RunWith(DataProviderRunner.class) public class ApiExceptionTest { - private ApiError apiError1 = BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR; - private ApiError apiError2 = BarebonesCoreApiErrorForTesting.SERVERSIDE_VALIDATION_ERROR; - private ApiError apiError3 = BarebonesCoreApiErrorForTesting.TYPE_CONVERSION_ERROR; - private ApiError apiError4 = BarebonesCoreApiErrorForTesting.OUTSIDE_DEPENDENCY_RETURNED_AN_UNRECOVERABLE_ERROR; + private final ApiError apiError1 = BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR; + private final ApiError apiError2 = BarebonesCoreApiErrorForTesting.SERVERSIDE_VALIDATION_ERROR; + private final ApiError apiError3 = BarebonesCoreApiErrorForTesting.TYPE_CONVERSION_ERROR; + private final ApiError apiError4 = BarebonesCoreApiErrorForTesting.OUTSIDE_DEPENDENCY_RETURNED_AN_UNRECOVERABLE_ERROR; - private Pair logPair1 = Pair.of("key1", "val1"); - private Pair logPair2 = Pair.of("key2", "val2"); - private Pair logPair3 = Pair.of("key3", "val3"); - private Pair logPair4 = Pair.of("key4", "val4"); + private final Pair logPair1 = Pair.of("key1", "val1"); + private final Pair logPair2 = Pair.of("key2", "val2"); + private final Pair logPair3 = Pair.of("key3", "val3"); + private final Pair logPair4 = Pair.of("key4", "val4"); - private Pair> headerPair1 = Pair.of("h1", singletonList("v1")); - private Pair> headerPair2 = Pair.of("h2", Arrays.asList("v2.1", "v2.2")); - private Pair> headerPair3 = Pair.of("h3", singletonList("v3")); - private Pair> headerPair4 = Pair.of("h4", Arrays.asList("v4.1", "v4.2")); + private final Pair> headerPair1 = Pair.of("h1", singletonList("v1")); + private final Pair> headerPair2 = Pair.of("h2", Arrays.asList("v2.1", "v2.2")); + private final Pair> headerPair3 = Pair.of("h3", singletonList("v3")); + private final Pair> headerPair4 = Pair.of("h4", Arrays.asList("v4.1", "v4.2")); - private String exceptionMessage = "some ex msg"; - private Exception cause = new Exception("intentional test exception"); + private final String exceptionMessage = "some ex msg"; + private final Exception cause = new Exception("intentional test exception"); @DataProvider(value = { "true | FORCE_STACK_TRACE", @@ -188,7 +188,7 @@ public void no_cause_constructors_fail_when_passed_null_or_empty_apiErrors_list( // given List> logInfoList = Collections.emptyList(); List>> responseHeaders = Collections.emptyList(); - List apiErrors = (useNull) ? null : Collections.emptyList(); + List apiErrors = (useNull) ? null : Collections.emptyList(); // expect if (useConstructorWithResponseHeaders) @@ -210,7 +210,7 @@ public void with_cause_constructors_fail_when_passed_null_or_empty_apiErrors_lis // given List> logInfoList = Collections.emptyList(); List>> responseHeaders = Collections.emptyList(); - List apiErrors = (useNull) ? null : Collections.emptyList(); + List apiErrors = (useNull) ? null : Collections.emptyList(); // expect if (useConstructorWithResponseHeaders) diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerBaseTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerBaseTest.java index 9db4930..f625682 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerBaseTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerBaseTest.java @@ -262,9 +262,9 @@ public void shouldFilterOutLowerPriorityErrorsWhenGivenErrorsWithMixedHttpStatus @Test public void shouldDeduplicateRepeatedErrors() throws UnexpectedMajorExceptionHandlingError { - List repeatedErrors = Arrays.asList(testProjectApiErrors.getGenericServiceError(), testProjectApiErrors.getGenericServiceError(), testProjectApiErrors.getGenericServiceError()); + List repeatedErrors = Arrays.asList(testProjectApiErrors.getGenericServiceError(), testProjectApiErrors.getGenericServiceError(), testProjectApiErrors.getGenericServiceError()); ErrorResponseInfo result = handler.maybeHandleException(ApiException.newBuilder().withApiErrors(repeatedErrors).build(), reqMock); - validateResponse(result, Arrays.asList((ApiError)testProjectApiErrors.getGenericServiceError())); + validateResponse(result, singletonList(testProjectApiErrors.getGenericServiceError())); } @Test @@ -337,7 +337,8 @@ public void handleExceptionShouldAddErrorIdToResponseHeader() { ApiExceptionHandlerBase handler = new TestApiExceptionHandler(); ErrorResponseInfo result = handler.doHandleApiException(singletonSortedSetOf(CUSTOM_API_ERROR), new ArrayList>(), null, new Exception(), reqMock); - assertThat(result.headersToAddToResponse.get("error_uid"), is(Arrays.asList(result.frameworkRepresentationObj.erv.error_id))); + assertThat(result.headersToAddToResponse.get("error_uid"), is( + singletonList(result.frameworkRepresentationObj.erv.error_id))); } @Test @@ -629,7 +630,7 @@ public void unwrapAndFindCoreException_returns_passed_in_arg_if_exception_has_ca } private static class CustomExceptionOfDoom extends Exception { } - private static ApiError CUSTOM_API_ERROR = new ApiErrorBase("CUSTOM_API_ERROR", 99042, "some message", 400); + private static final ApiError CUSTOM_API_ERROR = new ApiErrorBase("CUSTOM_API_ERROR", 99042, "some message", 400); private static class CustomExceptionOfDoomHandlerListener implements ApiExceptionHandlerListener { @Override @@ -652,7 +653,7 @@ public void shouldIgnoreUnknownExceptionTypes() throws UnexpectedMajorExceptionH @Test public void shouldUseCustomHandlerListenersIfSet() throws UnexpectedMajorExceptionHandlingError { ErrorResponseInfo result = handler.maybeHandleException(new CustomExceptionOfDoom(), reqMock); - validateResponse(result, Arrays.asList(CUSTOM_API_ERROR)); + validateResponse(result, singletonList(CUSTOM_API_ERROR)); } private static class TestApiExceptionHandler extends ApiExceptionHandlerBase { diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerUtilsTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerUtilsTest.java index e92e222..83868f6 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerUtilsTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerUtilsTest.java @@ -51,7 +51,7 @@ public class ApiExceptionHandlerUtilsTest { private RequestInfoForLogging reqMock; private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private ApiExceptionHandlerUtils impl = DEFAULT_IMPL; + private final ApiExceptionHandlerUtils impl = DEFAULT_IMPL; @Before public void setupMethod() { @@ -172,7 +172,7 @@ private void verifyBuildErrorMessageForLogs(boolean requestHasDtraceId, String d when(reqMock.getHeader(fh.headerName)).thenReturn(fh.headerValues.get(0)); } - List contributingErrors = Arrays.asList(BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.GENERIC_BAD_REQUEST); + List contributingErrors = Arrays.asList(BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.GENERIC_BAD_REQUEST); int httpStatusCodeToUse = testProjectApiErrors.determineHighestPriorityHttpStatusCode(contributingErrors); Exception exceptionCause = new Exception(); @@ -217,7 +217,7 @@ private void verifyBuildErrorMessageForLogs(boolean requestHasDtraceId, String d @Test public void buildErrorMessageForLogsReturnsExpectedStringForMissingDtraceId() { verifyBuildErrorMessageForLogs(false, null, null); - verifyBuildErrorMessageForLogs(false, null, Arrays.asList(Pair.of("foo", "bar"))); + verifyBuildErrorMessageForLogs(false, null, List.of(Pair.of("foo", "bar"))); } @Test @@ -316,7 +316,7 @@ public void buildErrorMessageForLogs_includes_orig_forwarded_request_uri_when_av @Test public void parseSpecificHeaderToStringShouldWorkForHappyPathWithOneHeaderVal() { - when(reqMock.getHeaders("foo")).thenReturn(Arrays.asList("fooval")); + when(reqMock.getHeaders("foo")).thenReturn(List.of("fooval")); String result = impl.parseSpecificHeaderToString(reqMock, "foo"); assertThat(result, is("foo=fooval")); @@ -341,7 +341,7 @@ public void parseSpecificHeaderToStringShouldReturnBlankStringIfHeadersIsNull() @Test public void parseSpecificHeaderToStringShouldReturnBlankStringIfHeadersIsEmpty() { - when(reqMock.getHeaders("foo")).thenReturn(Collections.emptyList()); + when(reqMock.getHeaders("foo")).thenReturn(Collections.emptyList()); String result = impl.parseSpecificHeaderToString(reqMock, "foo"); assertThat(result, is("")); @@ -360,10 +360,10 @@ public void parseSpecificHeaderToStringShouldReturnBlankStringIfUnexpectedExcept @Test public void parseRequestHeadersToStringShouldWorkForHappyPath() { when(reqMock.getHeadersMap()).thenReturn(new TreeMap<>(MapBuilder.>builder() - .put("header1", Arrays.asList("h1val")) + .put("header1", List.of("h1val")) .put("header2", Arrays.asList("h2val1", "h2val2")) .build())); - when(reqMock.getHeaders("header1")).thenReturn(Arrays.asList("h1val")); + when(reqMock.getHeaders("header1")).thenReturn(List.of("h1val")); when(reqMock.getHeaders("header2")).thenReturn(Arrays.asList("h2val1", "h2val2")); String result = impl.parseRequestHeadersToString(reqMock); @@ -374,11 +374,11 @@ public void parseRequestHeadersToStringShouldWorkForHappyPath() { public void parseRequestHeadersToStringShouldWorkForSpecialHeadersPath() { ApiExceptionHandlerUtils customImpl = new ApiExceptionHandlerUtils(true, new HashSet<>(Arrays.asList("Authorization", "X-Some-Alt-Authorization")), null); when(reqMock.getHeadersMap()).thenReturn(new TreeMap<>(MapBuilder.>builder() - .put("Authorization", Arrays.asList("secret secret")) - .put("X-Some-Alt-Authorization", Arrays.asList("secret1 secret2")) + .put("Authorization", List.of("secret secret")) + .put("X-Some-Alt-Authorization", List.of("secret1 secret2")) .build())); - when(reqMock.getHeaders("Authorization")).thenReturn(Arrays.asList("secret secret")); - when(reqMock.getHeaders("X-Some-Alt-Authorization")).thenReturn(Arrays.asList("secret1 secret2")); + when(reqMock.getHeaders("Authorization")).thenReturn(List.of("secret secret")); + when(reqMock.getHeaders("X-Some-Alt-Authorization")).thenReturn(List.of("secret1 secret2")); String result = customImpl.parseRequestHeadersToString(reqMock); assertThat(result, is("Authorization=[MASKED],X-Some-Alt-Authorization=[MASKED]")); @@ -386,7 +386,7 @@ public void parseRequestHeadersToStringShouldWorkForSpecialHeadersPath() { @Test public void parseSpecificHeaderToStringShouldWorkForHeaderValInLowerCase() { - when(reqMock.getHeaders("authorization")).thenReturn(Arrays.asList("fooval")); + when(reqMock.getHeaders("authorization")).thenReturn(List.of("fooval")); String result = impl.parseSpecificHeaderToString(reqMock, "authorization"); assertThat(result, is("authorization=[MASKED]")); @@ -403,7 +403,7 @@ public void parseRequestHeadersToStringShouldReturnBlankStringIfHeadersMapIsNull @Test public void parseRequestHeadersToStringShouldReturnBlankStringIfHeaderNamesIsEmpty() { - when(reqMock.getHeadersMap()).thenReturn(Collections.>emptyMap()); + when(reqMock.getHeadersMap()).thenReturn(Collections.emptyMap()); String result = impl.parseRequestHeadersToString(reqMock); assertThat(result, is("")); @@ -421,13 +421,14 @@ public void parseRequestHeadersToStringShouldReturnBlankStringIfUnexpectedExcept @Test public void concatenateErrorCollectionShouldWorkWithOneItemInCollection() { - String result = impl.concatenateErrorCollection(Arrays.asList(BarebonesCoreApiErrorForTesting.MISSING_EXPECTED_CONTENT)); + String result = impl.concatenateErrorCollection( + List.of(BarebonesCoreApiErrorForTesting.MISSING_EXPECTED_CONTENT)); assertThat(result, is("MISSING_EXPECTED_CONTENT")); } @Test public void concatenateErrorCollectionShouldWorkWithMultipleItemsInCollection() { - String result = impl.concatenateErrorCollection(Arrays.asList(BarebonesCoreApiErrorForTesting.MISSING_EXPECTED_CONTENT, BarebonesCoreApiErrorForTesting.TYPE_CONVERSION_ERROR)); + String result = impl.concatenateErrorCollection(Arrays.asList(BarebonesCoreApiErrorForTesting.MISSING_EXPECTED_CONTENT, BarebonesCoreApiErrorForTesting.TYPE_CONVERSION_ERROR)); assertThat(result, is("MISSING_EXPECTED_CONTENT,TYPE_CONVERSION_ERROR")); } diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/ErrorResponseInfoTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/ErrorResponseInfoTest.java index d9e4ddd..f504502 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/ErrorResponseInfoTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/ErrorResponseInfoTest.java @@ -21,7 +21,11 @@ public class ErrorResponseInfoTest { @Test public void constructorSetsValues() { Object frameworkObj = new Object(); - Map> headersMap = MapBuilder.>builder().put("header1", Arrays.asList("val1")).put("header2", Arrays.asList("h2val1, h2val2")).build(); + Map> headersMap = MapBuilder + .>builder() + .put("header1", List.of("val1")) + .put("header2", List.of("h2val1, h2val2")) + .build(); ErrorResponseInfo responseInfo = new ErrorResponseInfo<>(42, frameworkObj, headersMap); assertThat(responseInfo.frameworkRepresentationObj, is(frameworkObj)); assertThat(responseInfo.headersToAddToResponse, is(headersMap)); diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerBaseTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerBaseTest.java index 91d4523..b7163e7 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerBaseTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerBaseTest.java @@ -57,8 +57,8 @@ public class UnhandledExceptionHandlerBaseTest { private RequestInfoForLogging reqMock; private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private List errorsExpectedToBeUsed = Collections.singletonList(BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR); - private int httpStatusCodeExpectedToBeUsed = testProjectApiErrors.determineHighestPriorityHttpStatusCode(errorsExpectedToBeUsed); + private final List errorsExpectedToBeUsed = Collections.singletonList(BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR); + private final int httpStatusCodeExpectedToBeUsed = testProjectApiErrors.determineHighestPriorityHttpStatusCode(errorsExpectedToBeUsed); private ApiExceptionHandlerUtils utilsSpy; @Before @@ -79,7 +79,7 @@ public void handleException_should_delegate_to_ApiExceptionHandlerUtils_for_buil @Override public Object answer(InvocationOnMock invocation) throws Throwable { StringBuilder sb = (StringBuilder) invocation.getArguments()[0]; - sb.append(UUID.randomUUID().toString()); + sb.append(UUID.randomUUID()); sbHolder.add(sb); return UUID.randomUUID().toString(); } @@ -294,7 +294,7 @@ protected ErrorResponseInfo generateLastDitchFallbackErrorResponseInfo( return new ErrorResponseInfo<>( projectApiErrors.getGenericServiceError().getHttpStatusCode(), new TestDTO(new DefaultErrorContractDTO(UUID.randomUUID().toString(), singletonList(projectApiErrors.getGenericServiceError()))), - Collections.>emptyMap() + Collections.emptyMap() ); } } diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/ApiExceptionHandlerListenerResultTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/ApiExceptionHandlerListenerResultTest.java index 7602679..f7db11e 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/ApiExceptionHandlerListenerResultTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/ApiExceptionHandlerListenerResultTest.java @@ -52,7 +52,7 @@ public void ignoreResponse_should_return_instance_with_correct_values() { @Test public void handleResponse_one_arg_should_work_as_expected(boolean useNull) { // given - SortedApiErrorSet errors = (useNull) ? null : new SortedApiErrorSet(Arrays.asList( + SortedApiErrorSet errors = (useNull) ? null : new SortedApiErrorSet(Arrays.asList( BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST )); @@ -90,7 +90,7 @@ private void verifyErrors(ApiExceptionHandlerListenerResult val, SortedApiErrorS @Test public void handleResponse_two_args_should_work_as_expected(boolean useNullErrors, boolean useNullExtraLogging) { // given - SortedApiErrorSet errors = (useNullErrors) ? null : new SortedApiErrorSet(Arrays.asList( + SortedApiErrorSet errors = (useNullErrors) ? null : new SortedApiErrorSet(Arrays.asList( BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST )); List> extraDetailsForLogging = (useNullExtraLogging) ? null : Arrays.asList( @@ -142,7 +142,7 @@ public void handleResponse_three_args_should_work_as_expected( boolean useNullErrors, boolean useNullExtraLogging, boolean useNullResponseHeaders ) { // given - SortedApiErrorSet errors = (useNullErrors) ? null : new SortedApiErrorSet(Arrays.asList( + SortedApiErrorSet errors = (useNullErrors) ? null : new SortedApiErrorSet(Arrays.asList( BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST )); List> extraDetailsForLogging = (useNullExtraLogging) ? null : Arrays.asList( diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ClientDataValidationErrorHandlerListenerTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ClientDataValidationErrorHandlerListenerTest.java index 2488efa..dc637b8 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ClientDataValidationErrorHandlerListenerTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ClientDataValidationErrorHandlerListenerTest.java @@ -44,8 +44,8 @@ public class ClientDataValidationErrorHandlerListenerTest extends ListenerTestBa private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private ClientDataValidationErrorHandlerListener listener = new ClientDataValidationErrorHandlerListener(testProjectApiErrors, - ApiExceptionHandlerUtils.DEFAULT_IMPL); + private final ClientDataValidationErrorHandlerListener listener = new ClientDataValidationErrorHandlerListener(testProjectApiErrors, + ApiExceptionHandlerUtils.DEFAULT_IMPL); @Test public void constructor_sets_projectApiErrors_and_utils_to_passed_in_args() { @@ -98,14 +98,14 @@ public void shouldIgnoreExceptionThatItDoesNotWantToHandle() { public void shouldReturnGENERIC_SERVICE_ERRORForClientDataValidationErrorThatHasNullViolations() { ClientDataValidationError ex = new ClientDataValidationError(null, null, null); ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); - validateResponse(result, true, Collections.singletonList(testProjectApiErrors.getGenericServiceError())); + validateResponse(result, true, Collections.singletonList(testProjectApiErrors.getGenericServiceError())); } @Test public void shouldReturnGENERIC_SERVICE_ERRORForClientDataValidationErrorThatHasEmptyViolations() { - ClientDataValidationError ex = new ClientDataValidationError(null, Collections.>emptyList(), null); + ClientDataValidationError ex = new ClientDataValidationError(null, Collections.emptyList(), null); ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); - validateResponse(result, true, Collections.singletonList(testProjectApiErrors.getGenericServiceError())); + validateResponse(result, true, Collections.singletonList(testProjectApiErrors.getGenericServiceError())); } @Test @@ -168,11 +168,15 @@ private ConstraintViolation setupConstraintViolation(Class offendingObje @Test public void shouldReturnGENERIC_SERVICE_ERRORForViolationThatDoesNotMapToApiError() { ConstraintViolation violation = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation", NotNull.class, "I_Am_Invalid"); - ClientDataValidationError ex = new ClientDataValidationError(Arrays.asList(new SomeValidatableObject("someArg1", "someArg2")), Collections.singletonList(violation), null); + ClientDataValidationError ex = new ClientDataValidationError( + List.of(new SomeValidatableObject("someArg1", "someArg2")), Collections.singletonList(violation), null); ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); validateResponse(result, true, Collections.singletonList( // We expect it to be the generic error, with some metadata about the field that had an issue - new ApiErrorWithMetadata(testProjectApiErrors.getGenericServiceError(), Pair.of("field", (Object)"path.to.violation")) + new ApiErrorWithMetadata( + testProjectApiErrors.getGenericServiceError(), + Pair.of("field", "path.to.violation") + ) )); } @@ -181,12 +185,16 @@ public void shouldReturnExpectedErrorsForViolationsThatMapToApiErrors() { ConstraintViolation violation1 = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation1", NotNull.class, "MISSING_EXPECTED_CONTENT"); ConstraintViolation violation2 = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation2", NotEmpty.class, "TYPE_CONVERSION_ERROR"); ClientDataValidationError ex = new ClientDataValidationError( - Collections.singletonList(new SomeValidatableObject("someArg1", "someArg2")), Arrays.asList(violation1, violation2), null); + Collections.singletonList(new SomeValidatableObject("someArg1", "someArg2")), Arrays.asList(violation1, violation2), null); ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); validateResponse(result, true, Arrays.asList( // We expect them to be the properly associated errors, with some metadata about the field that had an issue - new ApiErrorWithMetadata(BarebonesCoreApiErrorForTesting.MISSING_EXPECTED_CONTENT, Pair.of("field", (Object)"path.to.violation1")), - new ApiErrorWithMetadata(BarebonesCoreApiErrorForTesting.TYPE_CONVERSION_ERROR, Pair.of("field", (Object)"path.to.violation2")) + new ApiErrorWithMetadata(BarebonesCoreApiErrorForTesting.MISSING_EXPECTED_CONTENT, Pair.of("field", + "path.to.violation1" + )), + new ApiErrorWithMetadata(BarebonesCoreApiErrorForTesting.TYPE_CONVERSION_ERROR, Pair.of("field", + "path.to.violation2" + )) )); } @@ -211,14 +219,14 @@ public void shouldAddExtraLoggingDetailsForClientDataValidationError() { ); } - private static interface SomeValidationGroup {} + private interface SomeValidationGroup {} private static class SomeValidatableObject { @NotEmpty(message = "MISSING_EXPECTED_CONTENT") - private String arg1; + private final String arg1; @NotEmpty(message = "MISSING_EXPECTED_CONTENT") - private String arg2; + private final String arg2; public SomeValidatableObject(String arg1, String arg2) { this.arg1 = arg1; diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/DownstreamNetworkExceptionHandlerListenerTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/DownstreamNetworkExceptionHandlerListenerTest.java index 2c6bbab..69a1a2f 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/DownstreamNetworkExceptionHandlerListenerTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/DownstreamNetworkExceptionHandlerListenerTest.java @@ -36,7 +36,7 @@ public class DownstreamNetworkExceptionHandlerListenerTest extends ListenerTestBase { private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private DownstreamNetworkExceptionHandlerListener listener = new DownstreamNetworkExceptionHandlerListener(testProjectApiErrors); + private final DownstreamNetworkExceptionHandlerListener listener = new DownstreamNetworkExceptionHandlerListener(testProjectApiErrors); private static class HttpClientErrorExceptionForTests extends Exception { public final int statusCode; diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListenerTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListenerTest.java index 536f221..f966e86 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListenerTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/GenericApiExceptionHandlerListenerTest.java @@ -21,7 +21,7 @@ */ public class GenericApiExceptionHandlerListenerTest extends ListenerTestBase { - private GenericApiExceptionHandlerListener listener = new GenericApiExceptionHandlerListener(); + private final GenericApiExceptionHandlerListener listener = new GenericApiExceptionHandlerListener(); @Test public void shouldIgnoreExceptionThatItDoesNotWantToHandle() { diff --git a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ServersideValidationErrorHandlerListenerTest.java b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ServersideValidationErrorHandlerListenerTest.java index d8d712c..ce0b81f 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ServersideValidationErrorHandlerListenerTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/handler/listener/impl/ServersideValidationErrorHandlerListenerTest.java @@ -40,8 +40,8 @@ public class ServersideValidationErrorHandlerListenerTest extends ListenerTestBase { private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private ServersideValidationErrorHandlerListener listener = new ServersideValidationErrorHandlerListener(testProjectApiErrors, - ApiExceptionHandlerUtils.DEFAULT_IMPL); + private final ServersideValidationErrorHandlerListener listener = new ServersideValidationErrorHandlerListener(testProjectApiErrors, + ApiExceptionHandlerUtils.DEFAULT_IMPL); @Test public void constructor_sets_projectApiErrors_and_utils_to_passed_in_args() { @@ -149,9 +149,9 @@ public void shouldAddExtraLoggingDetailsForServersideValidationError() { private static class SomeValidatableObject { @NotEmpty(message = "INVALID_TRUSTED_HEADERS_ERROR") - private String arg1; + private final String arg1; @NotEmpty(message = "INVALID_TRUSTED_HEADERS_ERROR") - private String arg2; + private final String arg2; public SomeValidatableObject(String arg1, String arg2) { this.arg1 = arg1; diff --git a/backstopper-core/src/test/java/com/nike/backstopper/model/DefaultErrorContractDTOTest.java b/backstopper-core/src/test/java/com/nike/backstopper/model/DefaultErrorContractDTOTest.java index d8cfdd6..1eee9be 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/model/DefaultErrorContractDTOTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/model/DefaultErrorContractDTOTest.java @@ -47,9 +47,9 @@ public void shouldNotExplodeIfYouPassInNullErrorCollection() { @Test public void shouldCorrectlyTranslateApiErrorsToIndividualErrorViews() { - List apiErrors = Arrays.asList(BarebonesCoreApiErrorForTesting.NO_ACCEPTABLE_REPRESENTATION, - BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST, - BarebonesCoreApiErrorForTesting.OUTSIDE_DEPENDENCY_RETURNED_AN_UNRECOVERABLE_ERROR); + List apiErrors = Arrays.asList(BarebonesCoreApiErrorForTesting.NO_ACCEPTABLE_REPRESENTATION, + BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST, + BarebonesCoreApiErrorForTesting.OUTSIDE_DEPENDENCY_RETURNED_AN_UNRECOVERABLE_ERROR); DefaultErrorContractDTO erv = new DefaultErrorContractDTO(null, apiErrors); assertThat(erv.errors .size(), is(apiErrors.size())); diff --git a/backstopper-core/src/test/java/com/nike/backstopper/service/ClientDataValidationServiceTest.java b/backstopper-core/src/test/java/com/nike/backstopper/service/ClientDataValidationServiceTest.java index 29f09f2..9e81d26 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/service/ClientDataValidationServiceTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/service/ClientDataValidationServiceTest.java @@ -82,7 +82,7 @@ public void shouldDelegateValidateObjectsWithGroupsFailFastCollectionMethodWithN public void shouldDelegateValidateObjectsWithGroupsFailFastCollectionMethodWithEmptyGroups() { Object obj1 = new Object(); Object obj2 = new Object(); - validationServiceSpy.validateObjectsWithGroupsFailFast(Collections.>emptyList(), obj1, obj2); + validationServiceSpy.validateObjectsWithGroupsFailFast(Collections.emptyList(), obj1, obj2); verify(validationServiceSpy).validateObjectsWithGroupsFailFast((Class[])null, obj1, obj2); } @@ -94,13 +94,13 @@ public void validateObjectsWithGroupsFailFastShouldDoNothingIfObjectsArrayIsNull @Test public void validateObjectsWithGroupsFailFastShouldDoNothingIfObjectsArrayIsEmpty() { - validationServiceSpy.validateObjectsWithGroupsFailFast((Class[])null, new Object[0]); + validationServiceSpy.validateObjectsWithGroupsFailFast((Class[])null); verifyNoMoreInteractions(validatorMock); } @Test public void validateObjectsWithGroupsFailFastShouldValidatePassedInObjectsNoGroups() { - given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.>emptySet()); + given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.emptySet()); Object objToValidate1 = new Object(); Object objToValidate2 = new Object(); validationServiceSpy.validateObjectsWithGroupsFailFast((Class[])null, objToValidate1, objToValidate2); @@ -110,7 +110,7 @@ public void validateObjectsWithGroupsFailFastShouldValidatePassedInObjectsNoGrou @Test public void validateObjectsWithGroupsFailFastShouldValidatePassedInObjectsWithGroups() { - given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.>emptySet()); + given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.emptySet()); Object objToValidate1 = new Object(); Object objToValidate2 = new Object(); Class[] groups = new Class[]{Default.class, String.class}; @@ -121,7 +121,7 @@ public void validateObjectsWithGroupsFailFastShouldValidatePassedInObjectsWithGr @Test public void validateObjectsWithGroupsFailFastShouldNotThrowExceptionIfThereAreNoViolations() { - given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.>emptySet()); + given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.emptySet()); Object objToValidate = new Object(); validationServiceSpy.validateObjectsWithGroupsFailFast((Class[])null, objToValidate); verify(validatorMock).validate(objToValidate); @@ -129,9 +129,9 @@ public void validateObjectsWithGroupsFailFastShouldNotThrowExceptionIfThereAreNo @Test public void validateObjectsWithGroupsFailFastShouldNotValidateNullObjects() { - given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.>emptySet()); + given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.emptySet()); Object objToValidate = new Object(); - validationServiceSpy.validateObjectsWithGroupsFailFast((Class[])null, new Object[]{objToValidate, null}); + validationServiceSpy.validateObjectsWithGroupsFailFast((Class[])null, objToValidate, null); verify(validatorMock).validate(objToValidate); verifyNoMoreInteractions(validatorMock); } @@ -142,10 +142,11 @@ public void validateObjectsWithGroupsFailFastShouldThrowAppropriateExceptionWhen Object objToValidate2 = new Object(); Object objToValidate3 = new Object(); Class[] groups = new Class[]{Default.class, String.class}; - List> obj1Violations = Arrays.>asList(mock(ConstraintViolation.class)); - List> obj3Violations = Arrays.>asList(mock(ConstraintViolation.class), mock(ConstraintViolation.class)); + List> obj1Violations = + Collections.singletonList(mock(ConstraintViolation.class)); + List> obj3Violations = Arrays.asList(mock(ConstraintViolation.class), mock(ConstraintViolation.class)); given(validatorMock.validate(objToValidate1, groups)).willReturn(new HashSet<>(obj1Violations)); - given(validatorMock.validate(objToValidate2, groups)).willReturn(Collections.>emptySet()); + given(validatorMock.validate(objToValidate2, groups)).willReturn(Collections.emptySet()); given(validatorMock.validate(objToValidate3, groups)).willReturn(new HashSet<>(obj3Violations)); try { validationServiceSpy.validateObjectsWithGroupsFailFast(groups, objToValidate1, objToValidate2, objToValidate3); diff --git a/backstopper-core/src/test/java/com/nike/backstopper/service/FailFastServersideValidationServiceTest.java b/backstopper-core/src/test/java/com/nike/backstopper/service/FailFastServersideValidationServiceTest.java index b7fc288..a2dde67 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/service/FailFastServersideValidationServiceTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/service/FailFastServersideValidationServiceTest.java @@ -44,7 +44,7 @@ public void shouldNotThrowExceptionIfValidatorComesBackClean() { @Test(expected = ServersideValidationError.class) public void shouldThrowExceptionIfValidatorFindsConstraintViolations() { Object validateMe = new Object(); - when(validator.validate(validateMe)).thenReturn(Collections.>singleton(mock(ConstraintViolation.class))); + when(validator.validate(validateMe)).thenReturn(Collections.singleton(mock(ConstraintViolation.class))); validationService.validateObjectFailFast(validateMe); } } diff --git a/backstopper-core/src/test/java/com/nike/backstopper/service/NoOpJsr303ValidatorTest.java b/backstopper-core/src/test/java/com/nike/backstopper/service/NoOpJsr303ValidatorTest.java index c54cdf0..4cf7efb 100644 --- a/backstopper-core/src/test/java/com/nike/backstopper/service/NoOpJsr303ValidatorTest.java +++ b/backstopper-core/src/test/java/com/nike/backstopper/service/NoOpJsr303ValidatorTest.java @@ -17,8 +17,8 @@ */ public class NoOpJsr303ValidatorTest { - private Validator noOpValidator = NoOpJsr303Validator.SINGLETON_IMPL; - private FooClass constraintAnnotatedClass = new FooClass(); + private final Validator noOpValidator = NoOpJsr303Validator.SINGLETON_IMPL; + private final FooClass constraintAnnotatedClass = new FooClass(); @Test public void validation_methods_return_empty_sets() { diff --git a/backstopper-custom-validators/src/main/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidator.java b/backstopper-custom-validators/src/main/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidator.java index 448f325..3d0a15c 100644 --- a/backstopper-custom-validators/src/main/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidator.java +++ b/backstopper-custom-validators/src/main/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidator.java @@ -171,11 +171,7 @@ protected boolean validateAsLong(String value) { protected boolean validateAsFloat(String value) { try { Float floatValue = Float.parseFloat(value); - if (floatValue.isInfinite() || floatValue.isNaN()) - return false; - - // No error, so it can be successfully parsed to this primitive type. - return true; + return !floatValue.isInfinite() && !floatValue.isNaN(); } catch (Exception ex) { // Couldn't parse the given string into this primitive type, so it's not valid. @@ -186,11 +182,7 @@ protected boolean validateAsFloat(String value) { protected boolean validateAsDouble(String value) { try { Double doubleValue = Double.parseDouble(value); - if (doubleValue.isInfinite() || doubleValue.isNaN()) - return false; - - // No error, so it can be successfully parsed to this primitive type. - return true; + return !doubleValue.isInfinite() && !doubleValue.isNaN(); } catch (Exception ex) { // Couldn't parse the given string into this primitive type, so it's not valid. diff --git a/backstopper-custom-validators/src/test/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidatorTest.java b/backstopper-custom-validators/src/test/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidatorTest.java index 276d824..4ab879f 100644 --- a/backstopper-custom-validators/src/test/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidatorTest.java +++ b/backstopper-custom-validators/src/test/java/com/nike/backstopper/validation/constraints/impl/StringConvertsToClassTypeValidatorTest.java @@ -27,7 +27,7 @@ @RunWith(DataProviderRunner.class) public class StringConvertsToClassTypeValidatorTest { - private Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); + private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); private StringConvertsToClassTypeValidator validatorImpl; @@ -308,7 +308,7 @@ public void shouldNotValidateInvalidLongBoxed() { @Test public void shouldNotValidateLongBoxedForValueTooBigForLong() { - doValidationTest(newObj().withFooLongBoxed("9" + String.valueOf(Long.MAX_VALUE)), "9" + String.valueOf(Long.MAX_VALUE), Long.class, false); + doValidationTest(newObj().withFooLongBoxed("9" + Long.MAX_VALUE), "9" + Long.MAX_VALUE, Long.class, false); } @Test @@ -323,7 +323,7 @@ public void shouldNotValidateInvalidLong() { @Test public void shouldNotValidateLongForValueTooBigForLong() { - doValidationTest(newObj().withFooLong("9" + String.valueOf(Long.MAX_VALUE)), "9" + String.valueOf(Long.MAX_VALUE), long.class, false); + doValidationTest(newObj().withFooLong("9" + Long.MAX_VALUE), "9" + Long.MAX_VALUE, long.class, false); } // Float (boxed) and float (primitive) =============================================================== @@ -385,7 +385,7 @@ public void shouldNotValidateInvalidNanDoubleBoxed() { @Test public void shouldNotValidateDoubleBoxedForValueTooBigForDouble() { - doValidationTest(newObj().withFooDoubleBoxed("1" + String.valueOf(Double.MAX_VALUE)), "1" + String.valueOf(Double.MAX_VALUE), Double.class, false); + doValidationTest(newObj().withFooDoubleBoxed("1" + Double.MAX_VALUE), "1" + Double.MAX_VALUE, Double.class, false); } @Test @@ -405,7 +405,7 @@ public void shouldNotValidateInvalidNaNDouble() { @Test public void shouldNotValidateDoubleForValueTooBigForDouble() { - doValidationTest(newObj().withFooDouble("1" + String.valueOf(Double.MAX_VALUE)), "1" + String.valueOf(Double.MAX_VALUE), double.class, false); + doValidationTest(newObj().withFooDouble("1" + Double.MAX_VALUE), "1" + Double.MAX_VALUE, double.class, false); } // Boolean (boxed) and boolean (primitive) =============================================================== diff --git a/backstopper-jackson/src/main/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupport.java b/backstopper-jackson/src/main/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupport.java index 70585a5..941ba5e 100644 --- a/backstopper-jackson/src/main/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupport.java +++ b/backstopper-jackson/src/main/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupport.java @@ -139,8 +139,7 @@ protected MetadataPropertyWriter(BeanPropertyWriter base) { @Override public void serializeAsField(Object bean, JsonGenerator jgen, SerializerProvider prov) throws Exception { - if (bean instanceof DefaultErrorDTO) { - DefaultErrorDTO error = (DefaultErrorDTO) bean; + if (bean instanceof DefaultErrorDTO error) { if (error.metadata == null || error.metadata.isEmpty()) { return; // empty metadata. Don't serialize } @@ -157,8 +156,7 @@ protected SmartErrorCodePropertyWriter(BeanPropertyWriter base) { @Override public void serializeAsField(Object bean, JsonGenerator jgen, SerializerProvider prov) throws Exception { - if (bean instanceof DefaultErrorDTO) { - DefaultErrorDTO error = (DefaultErrorDTO) bean; + if (bean instanceof DefaultErrorDTO error) { try { int codeAsInt = Integer.parseInt(error.code); jgen.writeFieldName(_name); diff --git a/backstopper-jackson/src/test/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupportTest.java b/backstopper-jackson/src/test/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupportTest.java index dc6a4a8..f0e9147 100644 --- a/backstopper-jackson/src/test/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupportTest.java +++ b/backstopper-jackson/src/test/java/com/nike/backstopper/model/util/JsonUtilWithDefaultErrorContractDTOSupportTest.java @@ -264,7 +264,7 @@ public void ErrorContractSerializationFactory_findPropWriter_returns_null_if_it_ ErrorContractSerializationFactory impl = new ErrorContractSerializationFactory(null, true, true); // when - BeanPropertyWriter result = impl.findPropWriter(Collections.emptyList(), UUID.randomUUID().toString()); + BeanPropertyWriter result = impl.findPropWriter(Collections.emptyList(), UUID.randomUUID().toString()); // then assertThat(result).isNull(); diff --git a/backstopper-servlet-api/src/main/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapter.java b/backstopper-servlet-api/src/main/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapter.java index 04966aa..0a420c5 100644 --- a/backstopper-servlet-api/src/main/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapter.java +++ b/backstopper-servlet-api/src/main/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapter.java @@ -126,7 +126,7 @@ protected void safeCloseCloseable(Closeable closeable) { closeable.close(); } catch (Throwable e) { logger.warn("An error occurred closing a Closeable resource. closeable_classname=\"" - + closeable.getClass().getName() + "\", exception_during_close=\"" + e.toString() + "\""); + + closeable.getClass().getName() + "\", exception_during_close=\"" + e + "\""); } } } diff --git a/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerServletApiBaseTest.java b/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerServletApiBaseTest.java index 80c030a..9135b05 100644 --- a/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerServletApiBaseTest.java +++ b/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/ApiExceptionHandlerServletApiBaseTest.java @@ -40,7 +40,7 @@ public class ApiExceptionHandlerServletApiBaseTest { @Before public void beforeMethod() { instanceSpy = spy(new ApiExceptionHandlerServletApiBase(mock(ProjectApiErrors.class), - Collections.emptyList(), + Collections.emptyList(), ApiExceptionHandlerUtils.DEFAULT_IMPL) { @Override protected Object prepareFrameworkRepresentation(DefaultErrorContractDTO errorContractDTO, int httpStatusCode, Collection filteredClientErrors, @@ -62,7 +62,14 @@ public void maybeHandleExceptionReturnsSuperValue() throws UnexpectedMajorExcept @Test public void maybeHandleExceptionSetsHeadersAndStatusCodeOnServletResponse() throws UnexpectedMajorExceptionHandlingError { - ErrorResponseInfo expectedResponseInfo = new ErrorResponseInfo(42, null, MapBuilder.>builder().put("header1", Arrays.asList("h1val1")).put("header2", Arrays.asList("h2val1", "h2val2")).build()); + ErrorResponseInfo expectedResponseInfo = new ErrorResponseInfo( + 42, + null, + MapBuilder.>builder() + .put("header1", List.of("h1val1")) + .put("header2", Arrays.asList("h2val1", "h2val2")) + .build() + ); doReturn(expectedResponseInfo).when(instanceSpy).maybeHandleException(any(Throwable.class), any(RequestInfoForLogging.class)); instanceSpy.maybeHandleException(new Exception(), servletRequestMock, servletResponseMock); diff --git a/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerServletApiBaseTest.java b/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerServletApiBaseTest.java index 6966029..72b6605 100644 --- a/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerServletApiBaseTest.java +++ b/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/UnhandledExceptionHandlerServletApiBaseTest.java @@ -65,7 +65,14 @@ public void handleExceptionReturnsSuperValue() throws UnexpectedMajorExceptionHa @Test public void handleExceptionSetsHeadersAndStatusCodeOnServletResponse() throws UnexpectedMajorExceptionHandlingError { - ErrorResponseInfo expectedResponseInfo = new ErrorResponseInfo(42, null, MapBuilder.>builder().put("header1", Arrays.asList("h1val1")).put("header2", Arrays.asList("h2val1", "h2val2")).build()); + ErrorResponseInfo expectedResponseInfo = new ErrorResponseInfo( + 42, + null, + MapBuilder.>builder() + .put("header1", List.of("h1val1")) + .put("header2", Arrays.asList("h2val1", "h2val2")) + .build() + ); doReturn(expectedResponseInfo).when(instanceSpy).handleException(any(Throwable.class), any(RequestInfoForLogging.class)); instanceSpy.handleException(new Exception(), servletRequestMock, servletResponseMock); diff --git a/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapterTest.java b/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapterTest.java index 63654c0..2b1fda9 100644 --- a/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapterTest.java +++ b/backstopper-servlet-api/src/test/java/com/nike/backstopper/handler/adapter/RequestInfoForLoggingServletApiAdapterTest.java @@ -79,7 +79,7 @@ public void getQueryStringDelegatesToServletRequest() { @Test public void getHeaderMapDelegatesToServletRequestAndCachesResult() { Map> expectedHeaderMap = new TreeMap<>(MapBuilder.>builder() - .put("header1", Arrays.asList("h1val1")) + .put("header1", List.of("h1val1")) .put("header2", Arrays.asList("h2val1", "h2val2")) .build()); doReturn(Collections.enumeration(expectedHeaderMap.keySet())).when(requestMock).getHeaderNames(); @@ -102,7 +102,7 @@ public void getHeaderMapReturnsEmptyMapIfServletRequestHeaderNamesReturnsNull() @Test public void getHeaderMapIgnoresHeadersWhereServletRequestGetHeadersMethodReturnsNull() { Map> expectedHeaderMap = new TreeMap<>(MapBuilder.>builder() - .put("header1", Arrays.asList("h1val1")) + .put("header1", List.of("h1val1")) .build()); doReturn(Collections.enumeration(Arrays.asList("header1", "header2"))).when(requestMock).getHeaderNames(); doReturn(Collections.enumeration(expectedHeaderMap.get("header1"))).when(requestMock).getHeaders("header1"); @@ -120,7 +120,7 @@ public void getHeaderDelegatesToServletRequest() { @Test public void getHeadersDelegatesToServletRequest() { - Pair> header1 = Pair.of("header1", Arrays.asList("h1val1")); + Pair> header1 = Pair.of("header1", List.of("h1val1")); Pair> header2 = Pair.of("header2", Arrays.asList("h2val1", "h2val2")); Map> expectedHeaderMap = new TreeMap<>(MapBuilder.>builder() .put(header1.getKey(), header1.getValue()) @@ -139,7 +139,7 @@ public void getAttributeDelegatesToServletRequest() { String attributeName = "someattribute"; UUID expectedValue = UUID.randomUUID(); doReturn(expectedValue).when(requestMock).getAttribute(attributeName); - assertThat(adapter.getAttribute(attributeName), Is.is(expectedValue)); + assertThat(adapter.getAttribute(attributeName), Is.is(expectedValue)); } @Test diff --git a/backstopper-spring-boot3-webmvc/src/test/java/com/nike/backstopper/handler/springboot/componenttest/SanityCheckComponentTest.java b/backstopper-spring-boot3-webmvc/src/test/java/com/nike/backstopper/handler/springboot/componenttest/SanityCheckComponentTest.java index c598ccc..5b52f1d 100644 --- a/backstopper-spring-boot3-webmvc/src/test/java/com/nike/backstopper/handler/springboot/componenttest/SanityCheckComponentTest.java +++ b/backstopper-spring-boot3-webmvc/src/test/java/com/nike/backstopper/handler/springboot/componenttest/SanityCheckComponentTest.java @@ -266,7 +266,7 @@ enum SanityCheckProjectApiError implements ApiError { SanityCheckProjectApiError(int errorCode, String message, int httpStatusCode) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode )); } diff --git a/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/componenttest/BackstopperSpringWebFluxComponentTest.java b/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/componenttest/BackstopperSpringWebFluxComponentTest.java index c5cdb1d..bd38657 100644 --- a/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/componenttest/BackstopperSpringWebFluxComponentTest.java +++ b/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/componenttest/BackstopperSpringWebFluxComponentTest.java @@ -1228,7 +1228,7 @@ enum ComponentTestProjectApiError implements ApiError { ComponentTestProjectApiError(int errorCode, String message, int httpStatusCode) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode )); } diff --git a/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/listener/impl/OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java b/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/listener/impl/OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java index a434159..8f6ab86 100644 --- a/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/listener/impl/OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java +++ b/backstopper-spring-web-flux/src/test/java/com/nike/backstopper/handler/spring/webflux/listener/impl/OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java @@ -34,7 +34,7 @@ public class OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest { private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private OneOffSpringWebFluxFrameworkExceptionHandlerListener listener = + private final OneOffSpringWebFluxFrameworkExceptionHandlerListener listener = new OneOffSpringWebFluxFrameworkExceptionHandlerListener( testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL ); diff --git a/backstopper-spring-web-mvc/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListener.java b/backstopper-spring-web-mvc/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListener.java index 2e68ac0..74512cc 100644 --- a/backstopper-spring-web-mvc/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListener.java +++ b/backstopper-spring-web-mvc/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListener.java @@ -70,12 +70,11 @@ public OneOffSpringWebMvcFrameworkExceptionHandlerListener(ProjectApiErrors proj return handleError(projectApiErrors.getMethodNotAllowedApiError(), extraDetailsForLogging); } - if (ex instanceof MissingServletRequestPartException) { - MissingServletRequestPartException detailsEx = (MissingServletRequestPartException)ex; + if (ex instanceof MissingServletRequestPartException detailsEx) { return handleError( new ApiErrorWithMetadata( projectApiErrors.getMalformedRequestApiError(), - Pair.of("missing_required_part", (Object)detailsEx.getRequestPartName()) + Pair.of("missing_required_part", detailsEx.getRequestPartName()) ), extraDetailsForLogging ); @@ -95,13 +94,12 @@ protected ApiExceptionHandlerListenerResult handleServletRequestBindingException ApiError errorToUse = projectApiErrors.getMalformedRequestApiError(); // Add some extra context metadata if it's a MissingServletRequestParameterException. - if (ex instanceof MissingServletRequestParameterException) { - MissingServletRequestParameterException detailsEx = (MissingServletRequestParameterException)ex; - + if (ex instanceof MissingServletRequestParameterException detailsEx) { + errorToUse = new ApiErrorWithMetadata( errorToUse, - Pair.of("missing_param_name", (Object)detailsEx.getParameterName()), - Pair.of("missing_param_type", (Object)detailsEx.getParameterType()), + Pair.of("missing_param_name", detailsEx.getParameterName()), + Pair.of("missing_param_type", detailsEx.getParameterType()), Pair.of("required_location", "query_param") ); } diff --git a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/ClientfacingErrorITest.java b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/ClientfacingErrorITest.java index a2ad088..cae3588 100644 --- a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/ClientfacingErrorITest.java +++ b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/ClientfacingErrorITest.java @@ -336,10 +336,8 @@ public void throw4xxServerHttpStatusCodeException() { } private byte[] responseBodyForDownstreamServiceError() { - StringBuilder sb = new StringBuilder(); - sb.append("{\"result\":\"failure\",\"errorCode\":\"0x00000042\",\"errorMessage\":\"something bad happened\"}"); - return sb.toString().getBytes(); + return "{\"result\":\"failure\",\"errorCode\":\"0x00000042\",\"errorMessage\":\"something bad happened\"}".getBytes(); } @RequestMapping("/throwServerTimeoutException") diff --git a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerTest.java b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerTest.java index 4664fd8..94d78b1 100644 --- a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerTest.java +++ b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerTest.java @@ -37,7 +37,7 @@ public class SpringApiExceptionHandlerTest { @Before public void beforeMethod() { projectApiErrorsMock = mock(ProjectApiErrors.class); - listenerList = new ApiExceptionHandlerListenerList(Collections.emptyList()); + listenerList = new ApiExceptionHandlerListenerList(Collections.emptyList()); generalUtils = ApiExceptionHandlerUtils.DEFAULT_IMPL; springUtils = SpringApiExceptionHandlerUtils.DEFAULT_IMPL; handlerSpy = spy(new SpringApiExceptionHandler(projectApiErrorsMock, listenerList, generalUtils, springUtils)); diff --git a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerUtilsTest.java b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerUtilsTest.java index e236ceb..1fbde5e 100644 --- a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerUtilsTest.java +++ b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringApiExceptionHandlerUtilsTest.java @@ -38,8 +38,8 @@ public void setupMethod() { @Test public void generateModelAndViewForErrorResponseShouldGenerateModelAndViewWithErrorContractAsOnlyModelObject() throws JsonProcessingException { DefaultErrorContractDTO - erv = new DefaultErrorContractDTO("someRequestId", Arrays.asList(BarebonesCoreApiErrorForTesting.NO_ACCEPTABLE_REPRESENTATION, - BarebonesCoreApiErrorForTesting.UNSUPPORTED_MEDIA_TYPE)); + erv = new DefaultErrorContractDTO("someRequestId", Arrays.asList(BarebonesCoreApiErrorForTesting.NO_ACCEPTABLE_REPRESENTATION, + BarebonesCoreApiErrorForTesting.UNSUPPORTED_MEDIA_TYPE)); ModelAndView mav = new SpringApiExceptionHandlerUtils().generateModelAndViewForErrorResponse(erv, -1, null, null, null); assertThat(mav.getModel().size(), is(1)); diff --git a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringUnhandledExceptionHandlerTest.java b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringUnhandledExceptionHandlerTest.java index 350a17f..869784c 100644 --- a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringUnhandledExceptionHandlerTest.java +++ b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/SpringUnhandledExceptionHandlerTest.java @@ -116,7 +116,7 @@ public void resolveException_delegates_to_handleException() { Exception originalEx = new RuntimeException("kaboom"); ModelAndView modelAndViewMock = mock(ModelAndView.class); ErrorResponseInfo handleExceptionResult = - new ErrorResponseInfo<>(424, modelAndViewMock, Collections.>emptyMap()); + new ErrorResponseInfo<>(424, modelAndViewMock, Collections.emptyMap()); doReturn(handleExceptionResult).when(handlerSpy).handleException(originalEx, reqMock, responseMock); // when diff --git a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest.java b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest.java index 4b8b111..1057b65 100644 --- a/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest.java +++ b/backstopper-spring-web-mvc/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest.java @@ -50,7 +50,7 @@ public class OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest { private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private OneOffSpringWebMvcFrameworkExceptionHandlerListener listener = + private final OneOffSpringWebMvcFrameworkExceptionHandlerListener listener = new OneOffSpringWebMvcFrameworkExceptionHandlerListener( testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL ); @@ -156,8 +156,8 @@ public void shouldHandleException_returns_MALFORMED_REQUEST_for_ServletRequestBi boolean isMissingRequestParamEx ) { // given - String missingParamName = "someParam-" + UUID.randomUUID().toString(); - String missingParamType = "someParamType-" + UUID.randomUUID().toString(); + String missingParamName = "someParam-" + UUID.randomUUID(); + String missingParamType = "someParamType-" + UUID.randomUUID(); ServletRequestBindingException ex = (isMissingRequestParamEx) ? new MissingServletRequestParameterException(missingParamName, missingParamType) diff --git a/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java b/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java index cb71071..5630a96 100644 --- a/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java +++ b/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java @@ -58,8 +58,7 @@ public ConventionBasedSpringValidationErrorToApiErrorHandlerListener( @Override public ApiExceptionHandlerListenerResult shouldHandleException(Throwable ex) { - if (ex instanceof Errors) { - Errors errEx = (Errors) ex; + if (ex instanceof Errors errEx) { List errList = errEx.getAllErrors(); //noinspection ConstantValue if (errList != null && !errList.isEmpty()) { diff --git a/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListener.java b/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListener.java index 90f3ab3..4afa3d8 100644 --- a/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListener.java +++ b/backstopper-spring-web/src/main/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListener.java @@ -303,8 +303,7 @@ protected ApiExceptionHandlerListenerResult handleTypeMismatchException( // ResponseEntityExceptionHandler for verification. if (ex instanceof ConversionNotSupportedException) { // We can add even more context log details if it's a MethodArgumentConversionNotSupportedException. - if (ex instanceof MethodArgumentConversionNotSupportedException) { - MethodArgumentConversionNotSupportedException macnsEx = (MethodArgumentConversionNotSupportedException)ex; + if (ex instanceof MethodArgumentConversionNotSupportedException macnsEx) { extraDetailsForLogging.add(Pair.of("method_arg_name", macnsEx.getName())); extraDetailsForLogging.add(Pair.of("method_arg_target_param", macnsEx.getParameter().toString())); } @@ -315,8 +314,7 @@ protected ApiExceptionHandlerListenerResult handleTypeMismatchException( // All other TypeMismatchExceptions should be treated as a 400, and we can/should include the metadata. // We can add even more context log details if it's a MethodArgumentTypeMismatchException. - if (ex instanceof MethodArgumentTypeMismatchException) { - MethodArgumentTypeMismatchException matmEx = (MethodArgumentTypeMismatchException)ex; + if (ex instanceof MethodArgumentTypeMismatchException matmEx) { List> hOrQMetadata = extractExtraMetadataForHeaderOrQueryParamException(matmEx); if (hOrQMetadata != null) { for (Pair pair : hOrQMetadata) { @@ -516,22 +514,19 @@ protected void addExtraDetailsForLoggingForResponseStatusException( @NotNull ResponseStatusException ex, @NotNull List> extraDetailsForLogging ) { - if (ex instanceof MethodNotAllowedException) { - MethodNotAllowedException detailsEx = (MethodNotAllowedException)ex; + if (ex instanceof MethodNotAllowedException detailsEx) { extraDetailsForLogging.add( Pair.of("supported_methods", concatenateCollectionToString(detailsEx.getSupportedMethods())) ); } - if (ex instanceof NotAcceptableStatusException) { - NotAcceptableStatusException detailsEx = (NotAcceptableStatusException)ex; + if (ex instanceof NotAcceptableStatusException detailsEx) { extraDetailsForLogging.add( Pair.of("supported_media_types", concatenateCollectionToString(detailsEx.getSupportedMediaTypes())) ); } - if (ex instanceof ServerErrorException) { - ServerErrorException detailsEx = (ServerErrorException)ex; + if (ex instanceof ServerErrorException detailsEx) { extraDetailsForLogging.add( Pair.of("method_parameter", String.valueOf(detailsEx.getMethodParameter())) ); @@ -540,15 +535,13 @@ protected void addExtraDetailsForLoggingForResponseStatusException( ); } - if (ex instanceof ServerWebInputException) { - ServerWebInputException detailsEx = (ServerWebInputException)ex; + if (ex instanceof ServerWebInputException detailsEx) { extraDetailsForLogging.add( Pair.of("method_parameter", String.valueOf(detailsEx.getMethodParameter())) ); } - if (ex instanceof UnsupportedMediaTypeStatusException) { - UnsupportedMediaTypeStatusException detailsEx = (UnsupportedMediaTypeStatusException)ex; + if (ex instanceof UnsupportedMediaTypeStatusException detailsEx) { extraDetailsForLogging.add( Pair.of("supported_media_types", concatenateCollectionToString(detailsEx.getSupportedMediaTypes())) ); @@ -602,8 +595,7 @@ protected void addExtraDetailsForLoggingForResponseStatusException( @NotNull ResponseStatusException ex, @NotNull String[] exReasonWords, @NotNull String exReason ) { // Check for an exception type where we can get the info without parsing strings. - if (ex instanceof MissingRequestValueException) { - MissingRequestValueException detailsEx = (MissingRequestValueException)ex; + if (ex instanceof MissingRequestValueException detailsEx) { return new RequiredParamData( detailsEx.getName(), extractRequiredTypeNoInfoLeak(detailsEx.getType()), diff --git a/backstopper-spring-web/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java b/backstopper-spring-web/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java index 079a0bc..9343a1e 100644 --- a/backstopper-spring-web/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java +++ b/backstopper-spring-web/src/test/java/com/nike/backstopper/handler/spring/listener/impl/OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java @@ -90,7 +90,7 @@ public class OneOffSpringCommonFrameworkExceptionHandlerListenerTest extends ListenerTestBase { private static final ProjectApiErrors testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null); - private OneOffSpringCommonFrameworkExceptionHandlerListener listener = new OneOffListenerBasicImpl( + private final OneOffSpringCommonFrameworkExceptionHandlerListener listener = new OneOffListenerBasicImpl( testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL ); @@ -407,7 +407,7 @@ public void shouldHandleException_returns_MALFORMED_REQUEST_for_generic_HttpMess private enum HttpMessageNotReadableExceptionScenario { KNOWN_MESSAGE_FOR_MISSING_CONTENT( - new HttpMessageNotReadableException("Required request body is missing " + UUID.randomUUID().toString()), + new HttpMessageNotReadableException("Required request body is missing " + UUID.randomUUID()), ProjectApiErrors::getMissingExpectedContentApiError ), JSON_MAPPING_EXCEPTION_CAUSE_INDICATING_NO_CONTENT( @@ -1116,7 +1116,7 @@ public void shouldHandleException_handles_ServerErrorException_as_expected( ServerErrorException ex = (nullDetails) - ? new ServerErrorException("Some reason", (Throwable) null) + ? new ServerErrorException("Some reason", null) : new ServerErrorException("Some reason", details, null); List> expectedExtraDetailsForLogging = new ArrayList<>(); @@ -1207,7 +1207,7 @@ public void shouldHandleException_handles_MissingRequestValueException_as_expect paramIndex ); - String missingParamName = "some-param-" + UUID.randomUUID().toString(); + String missingParamName = "some-param-" + UUID.randomUUID(); MissingRequestValueException ex = new MissingRequestValueException( missingParamName, int.class, diff --git a/nike-internal-util/src/main/java/com/nike/internal/util/Pair.java b/nike-internal-util/src/main/java/com/nike/internal/util/Pair.java index e55ec34..872099f 100644 --- a/nike-internal-util/src/main/java/com/nike/internal/util/Pair.java +++ b/nike-internal-util/src/main/java/com/nike/internal/util/Pair.java @@ -140,8 +140,7 @@ public boolean equals(final Object obj) { if (obj == this) { return true; } - if (obj instanceof Map.Entry) { - final Map.Entry other = (Map.Entry) obj; + if (obj instanceof Map.Entry other) { return Objects.equals(getKey(), other.getKey()) && Objects.equals(getValue(), other.getValue()); } @@ -168,7 +167,7 @@ public int hashCode() { */ @Override public String toString() { - return new StringBuilder().append('(').append(getLeft()).append(',').append(getRight()).append(')').toString(); + return "(" + getLeft() + ',' + getRight() + ')'; } /** diff --git a/nike-internal-util/src/main/java/com/nike/internal/util/StringUtils.java b/nike-internal-util/src/main/java/com/nike/internal/util/StringUtils.java index 0287538..db271c4 100644 --- a/nike-internal-util/src/main/java/com/nike/internal/util/StringUtils.java +++ b/nike-internal-util/src/main/java/com/nike/internal/util/StringUtils.java @@ -64,7 +64,7 @@ public static String join(Collection iterable, String delimiter, String prefi for (Object obj : iterable) { if (!firstItem) sb.append(delimiter); - sb.append(String.valueOf(obj)); + sb.append(obj); firstItem = false; } @@ -140,7 +140,7 @@ public static boolean isBlank(final CharSequence cs) { return true; } for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(cs.charAt(i)) == false) { + if (!Character.isWhitespace(cs.charAt(i))) { return false; } } diff --git a/samples/sample-spring-boot3-webflux/src/main/java/com/nike/backstopper/springboot3webfluxsample/error/SampleProjectApiError.java b/samples/sample-spring-boot3-webflux/src/main/java/com/nike/backstopper/springboot3webfluxsample/error/SampleProjectApiError.java index 196b88b..6b543d9 100644 --- a/samples/sample-spring-boot3-webflux/src/main/java/com/nike/backstopper/springboot3webfluxsample/error/SampleProjectApiError.java +++ b/samples/sample-spring-boot3-webflux/src/main/java/com/nike/backstopper/springboot3webfluxsample/error/SampleProjectApiError.java @@ -70,14 +70,14 @@ public enum SampleProjectApiError implements ApiError { SampleProjectApiError(int errorCode, String message, int httpStatusCode) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode )); } @SuppressWarnings("unused") SampleProjectApiError(int errorCode, String message, int httpStatusCode, Map metadata) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode, metadata + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode, metadata )); } diff --git a/samples/sample-spring-boot3-webmvc/src/main/java/com/nike/backstopper/springboot3webmvcsample/error/SampleProjectApiError.java b/samples/sample-spring-boot3-webmvc/src/main/java/com/nike/backstopper/springboot3webmvcsample/error/SampleProjectApiError.java index 45ffe0e..492af40 100644 --- a/samples/sample-spring-boot3-webmvc/src/main/java/com/nike/backstopper/springboot3webmvcsample/error/SampleProjectApiError.java +++ b/samples/sample-spring-boot3-webmvc/src/main/java/com/nike/backstopper/springboot3webmvcsample/error/SampleProjectApiError.java @@ -55,14 +55,14 @@ public enum SampleProjectApiError implements ApiError { SampleProjectApiError(int errorCode, String message, int httpStatusCode) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode )); } @SuppressWarnings("unused") SampleProjectApiError(int errorCode, String message, int httpStatusCode, Map metadata) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode, metadata + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode, metadata )); } diff --git a/testonly/testonly-spring-webmvc-reusable-test-support/src/main/java/testonly/componenttest/spring/reusable/error/SampleProjectApiError.java b/testonly/testonly-spring-webmvc-reusable-test-support/src/main/java/testonly/componenttest/spring/reusable/error/SampleProjectApiError.java index 1181d61..32e4937 100644 --- a/testonly/testonly-spring-webmvc-reusable-test-support/src/main/java/testonly/componenttest/spring/reusable/error/SampleProjectApiError.java +++ b/testonly/testonly-spring-webmvc-reusable-test-support/src/main/java/testonly/componenttest/spring/reusable/error/SampleProjectApiError.java @@ -73,14 +73,14 @@ public enum SampleProjectApiError implements ApiError { SampleProjectApiError(int errorCode, String message, int httpStatusCode) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode )); } @SuppressWarnings("unused") SampleProjectApiError(int errorCode, String message, int httpStatusCode, Map metadata) { this(new ApiErrorBase( - "delegated-to-enum-wrapper-" + UUID.randomUUID().toString(), errorCode, message, httpStatusCode, metadata + "delegated-to-enum-wrapper-" + UUID.randomUUID(), errorCode, message, httpStatusCode, metadata )); }