From 003b0700de9e1f1b01656d33fc50bca36bc6d17a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B8rn=20Kv=C3=A5le?= Date: Tue, 29 Oct 2024 23:56:03 +0100 Subject: [PATCH 1/5] refactor(ApiGateway): Make HttpClient overridable in RequestInfo #NP-47966 --- .../commons/apigateway/ApiGatewayHandler.java | 14 +--- .../apigateway/ApiGatewayProxyHandler.java | 13 ++- .../apigateway/ApiS3GatewayHandler.java | 6 +- .../ApiS3PresignerGatewayHandler.java | 6 +- .../nva/commons/apigateway/RequestInfo.java | 40 +++++++--- .../apigateway/RestRequestHandler.java | 15 +++- .../apigateway/ApiGatewayHandlerTest.java | 24 +++--- .../commons/apigateway/RequestInfoTest.java | 79 ++++++++++++------- .../RequestInfoUtilityFunctionsTest.java | 11 ++- .../java/nva/commons/apigateway/VoidTest.java | 10 ++- .../commons/apigateway/testutils/Handler.java | 5 +- .../apigateway/testutils/ProxyHandler.java | 5 +- .../testutils/RawStringResponseHandler.java | 10 +-- .../testutils/HandlerRequestBuilderTest.java | 13 ++- 14 files changed, 155 insertions(+), 96 deletions(-) diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java index a6c67d40..8d22da54 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java @@ -17,6 +17,7 @@ import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; +import java.net.http.HttpClient; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; @@ -51,23 +52,16 @@ public abstract class ApiGatewayHandler extends RestRequestHandler { public static final String ORIGIN_DELIMITER = ","; public static final String FALLBACK_ORIGIN = "https://nva.sikt.no"; - private final ObjectMapper objectMapper; private Supplier> additionalSuccessHeadersSupplier; private boolean isBase64Encoded; public ApiGatewayHandler(Class iclass) { - this(iclass, new Environment()); + this(iclass, new Environment(), defaultRestObjectMapper, HttpClient.newBuilder().build()); } - public ApiGatewayHandler(Class iclass, Environment environment) { - this(iclass, environment, defaultRestObjectMapper); - this.additionalSuccessHeadersSupplier = Collections::emptyMap; - } - - public ApiGatewayHandler(Class iclass, Environment environment, ObjectMapper objectMapper) { - super(iclass, environment); - this.objectMapper = objectMapper; + public ApiGatewayHandler(Class iclass, Environment environment, ObjectMapper objectMapper, HttpClient httpClient) { + super(iclass, environment, objectMapper, httpClient); this.additionalSuccessHeadersSupplier = Collections::emptyMap; } diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java index e44f0212..ce78af13 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java @@ -1,7 +1,9 @@ package nva.commons.apigateway; +import static nva.commons.apigateway.RestConfig.defaultRestObjectMapper; import com.amazonaws.services.lambda.runtime.Context; import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.http.HttpClient; import nva.commons.apigateway.exceptions.ApiGatewayException; import nva.commons.core.Environment; import nva.commons.core.JacocoGenerated; @@ -18,17 +20,12 @@ public abstract class ApiGatewayProxyHandler extends ApiGatewayHandler iclass) { - this(iclass, new Environment()); + this(iclass, new Environment(), defaultRestObjectMapper, HttpClient.newBuilder().build()); } @JacocoGenerated - protected ApiGatewayProxyHandler(Class iclass, Environment environment) { - super(iclass, environment); - } - - @JacocoGenerated - protected ApiGatewayProxyHandler(Class iclass, Environment environment, ObjectMapper objectMapper) { - super(iclass, environment, objectMapper); + protected ApiGatewayProxyHandler(Class iclass, Environment environment, ObjectMapper objectMapper, HttpClient httpClient) { + super(iclass, environment, objectMapper, httpClient); } @Override diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java index 29ef22b1..461eeb96 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java @@ -2,6 +2,7 @@ import com.amazonaws.services.lambda.runtime.Context; import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.http.HttpClient; import java.time.Duration; import nva.commons.apigateway.exceptions.BadRequestException; import nva.commons.core.Environment; @@ -29,8 +30,9 @@ public ApiS3GatewayHandler(Class iclass, S3Client s3client, S3Presigner s3Presigner, Environment environment, - ObjectMapper objectMapper) { - super(iclass, s3Presigner, environment, objectMapper); + ObjectMapper objectMapper, + HttpClient httpClient) { + super(iclass, s3Presigner, environment, objectMapper, httpClient); this.s3client = s3client; } diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java index c29b6ae4..9c74a217 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java @@ -3,6 +3,7 @@ import com.amazonaws.services.lambda.runtime.Context; import com.fasterxml.jackson.databind.ObjectMapper; import java.net.HttpURLConnection; +import java.net.http.HttpClient; import java.time.Duration; import java.util.Map; import nva.commons.apigateway.exceptions.ApiGatewayException; @@ -31,8 +32,9 @@ public ApiS3PresignerGatewayHandler(Class iclass, S3Presigner s3Presigner) { public ApiS3PresignerGatewayHandler(Class iclass, S3Presigner s3Presigner, Environment environment, - ObjectMapper objectMapper) { - super(iclass, environment, objectMapper); + ObjectMapper objectMapper, + HttpClient httpClient) { + super(iclass, environment, objectMapper, httpClient); this.s3presigner = s3Presigner; } diff --git a/apigateway/src/main/java/nva/commons/apigateway/RequestInfo.java b/apigateway/src/main/java/nva/commons/apigateway/RequestInfo.java index e704ca1b..167340e5 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/RequestInfo.java +++ b/apigateway/src/main/java/nva/commons/apigateway/RequestInfo.java @@ -39,6 +39,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.HttpHeaders; import java.io.InputStream; import java.net.URI; @@ -55,7 +56,7 @@ import java.util.stream.Stream; import no.unit.nva.auth.CognitoUserInfo; import no.unit.nva.auth.FetchUserInfo; -import no.unit.nva.commons.json.JsonUtils; +import nva.commons.apigateway.exceptions.ApiIoException; import nva.commons.apigateway.exceptions.BadRequestException; import nva.commons.apigateway.exceptions.UnauthorizedException; import nva.commons.core.JacocoGenerated; @@ -63,6 +64,7 @@ import nva.commons.core.StringUtils; import nva.commons.core.attempt.Failure; import nva.commons.core.exceptions.ExceptionUtils; +import nva.commons.core.ioutils.IoUtils; import nva.commons.core.paths.UriWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,9 +73,9 @@ public class RequestInfo { public static final String ERROR_FETCHING_COGNITO_INFO = "Could not fetch user information from Cognito:{}"; - private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.newBuilder().build(); private static final Logger logger = LoggerFactory.getLogger(RequestInfo.class); - private final HttpClient httpClient; + private static final ObjectMapper mapper = defaultRestObjectMapper; + private HttpClient httpClient; private final Supplier cognitoUri; private final Supplier e2eTestsUserInfoUri; @JsonProperty(HEADERS_FIELD) @@ -100,29 +102,36 @@ public RequestInfo(HttpClient httpClient, Supplier cognitoUri, Supplier(); this.pathParameters = new HashMap<>(); this.queryParameters = new HashMap<>(); this.multiValueQueryStringParameters = new HashMap<>(); this.otherProperties = new LinkedHashMap<>(); // ordinary HashMap and ConcurrentHashMap fail. this.requestContext = defaultRestObjectMapper.createObjectNode(); - this.httpClient = DEFAULT_HTTP_CLIENT; + this.httpClient = HttpClient.newBuilder().build(); this.cognitoUri = DEFAULT_COGNITO_URI; this.e2eTestsUserInfoUri = RequestInfoConstants.E2E_TESTING_USER_INFO_ENDPOINT; } - public static RequestInfo fromRequest(InputStream requestStream) { - return attempt(() -> JsonUtils.dtoObjectMapper.readValue(requestStream, RequestInfo.class)).orElseThrow(); + public static RequestInfo fromRequest(InputStream requestStream, HttpClient httpClient) throws ApiIoException { + String inputString = IoUtils.streamToString(requestStream); + return fromString(inputString, httpClient); + } + + public static RequestInfo fromString(String inputString, HttpClient httpClient) throws ApiIoException { + var requestInfo = new ApiMessageParser<>(mapper).getRequestInfo(inputString); + requestInfo.setHttpClient(httpClient); + return requestInfo; } @JsonIgnore public String getHeader(String header) { return getHeaders().entrySet().stream() - .filter(entry -> entry.getKey().equalsIgnoreCase(header)) - .findFirst() - .map(Map.Entry::getValue) - .orElseThrow(() -> new IllegalArgumentException(MISSING_FROM_HEADERS + header)); + .filter(entry -> entry.getKey().equalsIgnoreCase(header)) + .findFirst() + .map(Map.Entry::getValue) + .orElseThrow(() -> new IllegalArgumentException(MISSING_FROM_HEADERS + header)); } @JsonIgnore @@ -199,6 +208,11 @@ public void setOtherProperties(Map otherProperties) { this.otherProperties = otherProperties; } + @JacocoGenerated + public void setHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + } + public Map getHeaders() { return headers; } @@ -340,7 +354,7 @@ public URI getPersonCristinId() throws UnauthorizedException { @JsonIgnore public URI getPersonAffiliation() throws UnauthorizedException { return extractPersonAffiliationForTests().or(this::fetchPersonAffiliation) - .orElseThrow(UnauthorizedException::new); + .orElseThrow(UnauthorizedException::new); } @JsonIgnore @@ -455,7 +469,7 @@ private List fetchAvailableRights() { return userInfo .map(CognitoUserInfo::getAccessRights) .map(accessRightEntryStr -> AccessRightEntry.fromCsvForCustomer(accessRightEntryStr, userInfo.get() - .getCurrentCustomer())) + .getCurrentCustomer())) .map(stream -> stream.collect(Collectors.toList())) .orElseGet(Collections::emptyList); } diff --git a/apigateway/src/main/java/nva/commons/apigateway/RestRequestHandler.java b/apigateway/src/main/java/nva/commons/apigateway/RestRequestHandler.java index 2a764071..74820e06 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/RestRequestHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/RestRequestHandler.java @@ -5,11 +5,13 @@ import static nva.commons.core.exceptions.ExceptionUtils.stackTraceInSingleLine; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.http.HttpClient; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -42,7 +44,9 @@ public abstract class RestRequestHandler implements RequestStreamHandler { protected final Environment environment; private static final Logger logger = LoggerFactory.getLogger(RestRequestHandler.class); private final transient Class iclass; - private final transient ApiMessageParser inputParser = new ApiMessageParser<>(); + private final transient ApiMessageParser inputParser; + protected final ObjectMapper objectMapper; + private final HttpClient httpClient; protected transient OutputStream outputStream; protected transient String allowedOrigin; @@ -130,9 +134,13 @@ private MediaType defaultResponseContentTypeWhenNotSpecifiedByClientRequest() { * @param iclass The class object of the input class. * @param environment the Environment from where the handler will read ENV variables. */ - public RestRequestHandler(Class iclass, Environment environment) { + public RestRequestHandler(Class iclass, Environment environment, ObjectMapper objectMapper, + HttpClient httpClient) { this.iclass = iclass; this.environment = environment; + this.inputParser = new ApiMessageParser<>(objectMapper); + this.objectMapper = objectMapper; + this.httpClient = httpClient; } @Override @@ -145,7 +153,8 @@ public void handleRequest(InputStream inputStream, OutputStream outputStream, Co inputObject = attempt(() -> parseInput(inputString)) .orElseThrow(this::parsingExceptionToBadRequestException); - RequestInfo requestInfo = inputParser.getRequestInfo(inputString); + RequestInfo requestInfo = RequestInfo.fromString(inputString, httpClient); + requestInfo.setHttpClient(httpClient); setAllowedOrigin(requestInfo); validateRequest(inputObject, requestInfo, context); diff --git a/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java b/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java index 144b89d6..a74303b9 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java @@ -47,6 +47,7 @@ import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URISyntaxException; +import java.net.http.HttpClient; import java.nio.file.Path; import java.util.List; import java.util.Map; @@ -89,6 +90,8 @@ class ApiGatewayHandlerTest { private static final String PATH = "path1/path2/path3"; private Context context; private Handler handler; + private HttpClient httpClient; + private Environment environment; public static Stream mediaTypeProvider() { return Stream.of(MediaTypes.APPLICATION_JSON_LD.toString(), MediaTypes.APPLICATION_DATACITE_XML.toString(), @@ -98,7 +101,10 @@ public static Stream mediaTypeProvider() { @BeforeEach public void setup() { context = new FakeContext(); - handler = new Handler(); + httpClient = mock(HttpClient.class); + environment = mock(Environment.class); + when(environment.readEnv("ALLOWED_ORIGIN")).thenReturn("*"); + handler = new Handler(defaultRestObjectMapper, environment, httpClient); } @Test @@ -394,7 +400,7 @@ void shouldReturnContentTypeMatchingSupportedMediaTypeWhenSupportedMediaTypeIsRe @Test void handlerSerializesBodyWithNonDefaultSerializationWhenDefaultSerializerIsOverridden() throws IOException { ObjectMapper spiedMapper = spy(defaultRestObjectMapper); - var handler = new Handler(spiedMapper); + var handler = new Handler(spiedMapper, environment, httpClient); var inputStream = requestWithHeaders(); var outputStream = outputStream(); handler.handleRequest(inputStream, outputStream, context); @@ -425,7 +431,7 @@ void handlerSendsRedirectionWhenItReceivesARedirectException() throws IOExceptio @Test void shouldReturnJsonObjectWhenClientAsksForJson() throws Exception { - var handler = new RawStringResponseHandler(dtoObjectMapper); + var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); var inputStream = requestWithHeaders(); var expected = objectMapper.convertValue(createBody(), RequestBody.class); var outputStream = outputStream(); @@ -439,7 +445,7 @@ void shouldReturnJsonObjectWhenClientAsksForJson() throws Exception { @Test void shouldReturnXmlObjectWhenClientAsksForXml() throws Exception { - var handler = new RawStringResponseHandler(dtoObjectMapper); + var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); var inputStream = requestWithAcceptXmlHeader(); var expected = objectMapper.convertValue(createBody(), RequestBody.class); var outputStream = outputStream(); @@ -457,7 +463,7 @@ void shouldReturnAllOriginsWhenEnvironmentAllowsAllOrigins() throws IOException var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn("*"); - var handler = new RawStringResponseHandler(environment, dtoObjectMapper); + var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -474,7 +480,7 @@ void shouldReturnNvaFrontendProdWhenEnvironmentIsEmpty() throws IOException { var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn(""); - var handler = new RawStringResponseHandler(environment, dtoObjectMapper); + var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -492,7 +498,7 @@ void shouldEchoAllowedOriginWhenEnvironmentContainsOrigin() throws IOException { var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn("localhost, " + originInHeader + ", some-place-else"); - var handler = new RawStringResponseHandler(environment, dtoObjectMapper); + var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -511,7 +517,7 @@ void shouldReturnOneOfTheAllowedOriginsInEnvironmentWhenRequestOriginIsNotWhiteL var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn("localhost, some-place-else"); - var handler = new RawStringResponseHandler(environment, dtoObjectMapper); + var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -529,7 +535,7 @@ void shouldReturnFirstElementInAllowedOriginsListWhenOriginIsMissing() throws IO var header2 = "https://example2.com"; var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn(header1 + ", " + header2); - var handler = new RawStringResponseHandler(environment, dtoObjectMapper); + var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); var inputStream = requestWithMissingOriginHeader(); var outputStream = outputStream(); handler.handleRequest(inputStream, outputStream, context); diff --git a/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java b/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java index b104747e..8ee54a49 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java @@ -34,6 +34,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.net.HttpHeaders; +import java.io.ByteArrayInputStream; +import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.nio.file.Path; @@ -272,7 +274,7 @@ void shouldReturnThatUserDoesNotHaveAccessRightForSpecificCustomerWhenUserDoesNo @Test void shouldReturnThatUserIsAuthorizedWhenRequestInfoContainsACustomerIdAndTheRequestedAccessRight() - throws JsonProcessingException { + throws JsonProcessingException, ApiIoException { var usersCustomer = randomUri(); var usersAccessRights = List.of(randomAccessRight(), randomAccessRight()); RequestInfo requestInfo = createRequestInfoForOfflineAuthorization(usersAccessRights, usersCustomer); @@ -283,7 +285,7 @@ void shouldReturnThatUserIsAuthorizedWhenRequestInfoContainsACustomerIdAndTheReq @Test void shouldReturnNotAuthorizedWhenRequestInfoDoesNotContainTheRequestedAccessRightAndCheckIsPerformedOffline() - throws JsonProcessingException { + throws JsonProcessingException, ApiIoException { var userCustomer = randomUri(); var usersAccessRights = List.of(MANAGE_DEGREE, MANAGE_IMPORT); var requestInfo = @@ -294,7 +296,7 @@ void shouldReturnNotAuthorizedWhenRequestInfoDoesNotContainTheRequestedAccessRig @Test void shouldReturnNotAuthorizedWhenRequestInfoDoesNotContainAccessRightsAndCheckIsPerformedOffline() - throws JsonProcessingException { + throws JsonProcessingException, ApiIoException { var userCustomer = randomUri(); var requestInfo = requestInfoWithCustomerId(userCustomer); var notAllocatedAccessRight = new AccessRightEntry(MANAGE_DEGREE, userCustomer); @@ -303,7 +305,14 @@ void shouldReturnNotAuthorizedWhenRequestInfoDoesNotContainAccessRightsAndCheckI } @Test - void shouldReturnMultiValueQueryValuesWhenProvided() throws JsonProcessingException { + void shouldReturnReturnBadRequestWhenObjectMapperFails(){ + var request = "This is not a valid request"; + assertThrows(ApiIoException.class, () -> RequestInfo.fromRequest(IoUtils.stringToStream(request), httpClient)); + } + + @Test + void shouldReturnMultiValueQueryValuesWhenProvided() + throws JsonProcessingException, ApiIoException { var key = randomString(); var value1 = randomString(); var value2 = randomString(); @@ -311,52 +320,62 @@ void shouldReturnMultiValueQueryValuesWhenProvided() throws JsonProcessingExcept var request = new HandlerRequestBuilder(dtoObjectMapper).withMultiValueQueryParameters( Map.of(key, List.of(value1, value2))).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); assertThat(requestInfo.getMultiValueQueryParameter(key), is(equalTo(List.of(value1, value2)))); } @Test - void isBackendClientShouldReturnTrueWhenScopeContainsTheBackendScope() throws JsonProcessingException { + void isBackendClientShouldReturnTrueWhenScopeContainsTheBackendScope() + throws JsonProcessingException, ApiIoException { var request = new HandlerRequestBuilder(dtoObjectMapper).withScope( BACKEND_SCOPE_AS_DEFINED_IN_IDENTITY_SERVICE).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); assertThat(requestInfo.clientIsInternalBackend(), is(true)); } @Test - void isBackendClientShouldReturnFalseWhenScopeContainsTheBackendScope() throws JsonProcessingException { + void isBackendClientShouldReturnFalseWhenScopeContainsTheBackendScope() + throws JsonProcessingException, ApiIoException { var request = new HandlerRequestBuilder(dtoObjectMapper).withScope(randomString()).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); assertThat(requestInfo.clientIsInternalBackend(), is(false)); } @Test - void isThirdPartyShouldReturnTrueWhenScopeContainsTheExternalIssuedUserPool() throws JsonProcessingException { + void isThirdPartyShouldReturnTrueWhenScopeContainsTheExternalIssuedUserPool() + throws JsonProcessingException, ApiIoException { var request = new HandlerRequestBuilder(dtoObjectMapper).withIssuer(EXTERNAL_USER_POOL_URL).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); assertThat(requestInfo.clientIsThirdParty(), is(true)); } @Test - void isThirdPartyShouldReturnFalseWhenScopeContainsOtherUserPool() throws JsonProcessingException { + void isThirdPartyShouldReturnFalseWhenScopeContainsOtherUserPool() + throws JsonProcessingException, ApiIoException { var issuer = RandomDataGenerator.randomUri().toString(); var request = new HandlerRequestBuilder(dtoObjectMapper).withIssuer(issuer).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); assertThat(requestInfo.clientIsThirdParty(), is(false)); } @Test - void getClientIdShouldReturnEmptyOptionalWhenClientIdIsNotInClaim() throws JsonProcessingException { + void getClientIdShouldReturnEmptyOptionalWhenClientIdIsNotInClaim() + throws JsonProcessingException, ApiIoException { var request = new HandlerRequestBuilder(dtoObjectMapper).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); assertThat(requestInfo.getClientId().isEmpty(), is(true)); } + private RequestInfo getRequestInfo(InputStream request) throws ApiIoException { + return RequestInfo.fromRequest(request, httpClient); + } + @Test - void getClientIdShouldReturnTheClientIdFromClaim() throws JsonProcessingException { + void getClientIdShouldReturnTheClientIdFromClaim() + throws JsonProcessingException, ApiIoException { var clientId = RandomDataGenerator.randomString(); var request = new HandlerRequestBuilder(dtoObjectMapper).withClientId(clientId).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); assertThat(requestInfo.getClientId().get(), is(equalTo(clientId))); } @@ -517,7 +536,7 @@ void shouldReturnTopLevelOrgCristinIdWhenCurrentCustomerHasBeenSelectedForPerson @Test void shouldReturnTopLevelOrgCristinIdWhenRequestsAuthorizerNodeContainsCorrespondingClaim() - throws JsonProcessingException { + throws JsonProcessingException, ApiIoException { var topOrgCristinId = randomUri(); var requestInfo = requestInfoWithAuthorizerClaim(topOrgCristinId.toString()); assertThat(requestInfo.getTopLevelOrgCristinId().orElseThrow(), is(equalTo(topOrgCristinId))); @@ -545,9 +564,9 @@ void shouldReadMultiValueQueryParameters() throws JsonProcessingException { } @Test - void shouldLogWarningWhenAuthenticationFails() throws JsonProcessingException { + void shouldLogWarningWhenAuthenticationFails() throws JsonProcessingException, ApiIoException { var request = new HandlerRequestBuilder(dtoObjectMapper).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = getRequestInfo(request); var logger = LogUtils.getTestingAppenderForRootLogger(); requestInfo.userIsAuthorized(randomAccessRight()); assertThat(logger.getMessages(), containsString(AUTHORIZATION_FAILURE_WARNING)); @@ -674,7 +693,8 @@ void shouldLogFailureWhenFailingToFetchInfoFromCognito() { } @Test - void shouldReturnListOfAccessRightsAvailableForUser() throws JsonProcessingException { + void shouldReturnListOfAccessRightsAvailableForUser() + throws JsonProcessingException, ApiIoException { var usersCustomer = randomUri(); var accessRights = List.of(MANAGE_DEGREE, MANAGE_IMPORT, MANAGE_NVI); var accessRightsForCustomer = accessRights.stream() @@ -699,15 +719,17 @@ void shouldReturnEmptyListWhenAccessRightsCognitoStringIsEmpty() { assertThat(accessRights, is(emptyIterable())); } - private RequestInfo requestInfoWithCustomerId(URI userCustomer) throws JsonProcessingException { + private RequestInfo requestInfoWithCustomerId(URI userCustomer) throws JsonProcessingException, + ApiIoException { var request = new HandlerRequestBuilder(dtoObjectMapper).build(); - return RequestInfo.fromRequest(request); + return getRequestInfo(request); } - private RequestInfo requestInfoWithAuthorizerClaim(String claim) throws JsonProcessingException { + private RequestInfo requestInfoWithAuthorizerClaim(String claim) throws JsonProcessingException, + ApiIoException { var request = new HandlerRequestBuilder(dtoObjectMapper).withAuthorizerClaim( CognitoUserInfo.TOP_LEVEL_ORG_CRISTIN_ID_CLAIM, claim).build(); - return RequestInfo.fromRequest(request); + return getRequestInfo(request); } private CognitoUserInfo createCognitoUserEntry(URI usersCustomer, Set accessRightsForCustomer) { @@ -788,11 +810,11 @@ private Supplier failingUri() { } private RequestInfo createRequestInfoForOfflineAuthorization(List accessRights, URI userCustomer) - throws JsonProcessingException { + throws JsonProcessingException, ApiIoException { var requestStream = new HandlerRequestBuilder(dtoObjectMapper) .withAccessRights(userCustomer, accessRights.toArray(AccessRight[]::new)) .build(); - return RequestInfo.fromRequest(requestStream); + return getRequestInfo(requestStream); } private String bearerToken(String userAccessToken) { @@ -801,8 +823,7 @@ private String bearerToken(String userAccessToken) { private RequestInfo extractAccessRightsFromApiGatewayEvent() throws ApiIoException { String event = IoUtils.stringFromResources(RequestInfoTest.AWS_SAMPLE_PROXY_EVENT); - ApiMessageParser apiMessageParser = new ApiMessageParser<>(); - return apiMessageParser.getRequestInfo(event); + return getRequestInfo(new ByteArrayInputStream(event.getBytes())); } private void checkForNonNullMap(Path resourceFile, Function getObject) diff --git a/apigateway/src/test/java/nva/commons/apigateway/RequestInfoUtilityFunctionsTest.java b/apigateway/src/test/java/nva/commons/apigateway/RequestInfoUtilityFunctionsTest.java index c7c3cd8b..b31fdd3a 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/RequestInfoUtilityFunctionsTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/RequestInfoUtilityFunctionsTest.java @@ -6,12 +6,17 @@ import static nva.commons.apigateway.RequestInfoConstants.MISSING_FROM_REQUEST_CONTEXT; import static nva.commons.apigateway.RestConfig.defaultRestObjectMapper; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.fasterxml.jackson.core.JsonPointer; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import java.net.http.HttpClient; import java.util.List; import java.util.Map; +import no.unit.nva.testutils.HandlerRequestBuilder; +import nva.commons.apigateway.exceptions.ApiIoException; import nva.commons.apigateway.exceptions.BadRequestException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -25,8 +30,10 @@ public class RequestInfoUtilityFunctionsTest { public static String VALUE = "value"; @BeforeEach - public void setUp() { - RequestInfo spiedObject = new RequestInfo(); + public void setUp() throws JsonProcessingException, ApiIoException { + var request = new HandlerRequestBuilder(defaultRestObjectMapper).build(); + var httpClient = mock(HttpClient.class); + RequestInfo spiedObject = RequestInfo.fromRequest(request, httpClient); requestInfo = spy(spiedObject); } diff --git a/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java b/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java index de8924be..9d6af6eb 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java @@ -1,6 +1,7 @@ package nva.commons.apigateway; import static nva.commons.apigateway.ApiGatewayHandler.ALLOWED_ORIGIN_ENV; +import static nva.commons.apigateway.RestConfig.defaultRestObjectMapper; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; @@ -12,6 +13,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; +import java.net.http.HttpClient; import java.nio.file.Path; import no.unit.nva.stubs.FakeContext; import nva.commons.apigateway.exceptions.ApiGatewayException; @@ -31,6 +33,7 @@ public class VoidTest { private Environment environment; private Context context; + private HttpClient httpClient; /** * Setup. @@ -42,6 +45,7 @@ public void setup() { context = new FakeContext(); when(environment.readEnv(anyString())).thenReturn(SOME_ENV_VALUE); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn("*"); + httpClient = mock(HttpClient.class); } @DisplayName("handleRequest returns success when input class is void and body field is missing from " @@ -67,7 +71,7 @@ public void handleRequestReturnsSuccessWhenInputClassIsVoidAndBodyFieldIsAnEmpty private ByteArrayOutputStream responseFromVoidHandler(String missingBodyRequest) throws IOException { InputStream input = IoUtils.inputStreamFromResources(Path.of(APIGATEWAY_MESSAGES_FOLDER, missingBodyRequest)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - VoidHandler handler = new VoidHandler(environment); + VoidHandler handler = new VoidHandler(environment, httpClient); handler.handleRequest(input, outputStream, context); return outputStream; } @@ -76,8 +80,8 @@ private class VoidHandler extends ApiGatewayHandler { public static final String SAMPLE_STRING = "sampleString"; - public VoidHandler(Environment environment) { - super(Void.class, environment); + public VoidHandler(Environment environment, HttpClient httpClient) { + super(Void.class, environment, defaultRestObjectMapper, httpClient); } @Override diff --git a/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java b/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java index 09018fac..46b8388c 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java +++ b/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.HttpHeaders; import java.net.HttpURLConnection; +import java.net.http.HttpClient; import java.util.Collections; import java.util.Map; import nva.commons.apigateway.ApiGatewayHandler; @@ -28,8 +29,8 @@ public Handler() { * * @param mapper Object Mapper */ - public Handler(ObjectMapper mapper) { - super(RequestBody.class, new Environment(), mapper); + public Handler(ObjectMapper mapper,Environment environment, HttpClient httpClient) { + super(RequestBody.class, environment, mapper, httpClient); } @Override diff --git a/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java b/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java index 8f17a610..ed4d6ac2 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java +++ b/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java @@ -4,6 +4,7 @@ import com.amazonaws.services.lambda.runtime.Context; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.HttpHeaders; +import java.net.http.HttpClient; import java.util.Collections; import java.util.Map; import nva.commons.apigateway.ApiGatewayProxyHandler; @@ -29,8 +30,8 @@ public ProxyHandler() { * * @param mapper Object Mapper */ - public ProxyHandler(ObjectMapper mapper) { - super(RequestBody.class, new Environment(), mapper); + public ProxyHandler(ObjectMapper mapper, Environment environment, HttpClient httpClient) { + super(RequestBody.class, environment, mapper, httpClient); } @Override diff --git a/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java b/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java index 6008fe86..dfe33df8 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java +++ b/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java @@ -10,6 +10,7 @@ import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import java.net.HttpURLConnection; +import java.net.http.HttpClient; import java.util.Collections; import java.util.List; import java.util.Map; @@ -34,15 +35,10 @@ public RawStringResponseHandler() { * * @param mapper Object Mapper */ - public RawStringResponseHandler(ObjectMapper mapper) { - super(RequestBody.class, new Environment(), mapper); + public RawStringResponseHandler(ObjectMapper mapper, Environment environment, HttpClient httpClient) { + super(RequestBody.class, environment, mapper, httpClient); } - public RawStringResponseHandler(Environment environment, ObjectMapper mapper) { - super(RequestBody.class, environment, mapper); - } - - @Override protected String processInput(RequestBody input, RequestInfo requestInfo, Context context) throws ApiGatewayException { diff --git a/nvatestutils/src/test/java/no/unit/nva/testutils/HandlerRequestBuilderTest.java b/nvatestutils/src/test/java/no/unit/nva/testutils/HandlerRequestBuilderTest.java index 90580bf5..ca26f139 100644 --- a/nvatestutils/src/test/java/no/unit/nva/testutils/HandlerRequestBuilderTest.java +++ b/nvatestutils/src/test/java/no/unit/nva/testutils/HandlerRequestBuilderTest.java @@ -12,6 +12,7 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; +import static org.mockito.Mockito.mock; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; @@ -20,10 +21,12 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; +import java.net.http.HttpClient; import java.util.Map; import java.util.Optional; import no.unit.nva.commons.json.JsonUtils; import nva.commons.apigateway.RequestInfo; +import nva.commons.apigateway.exceptions.ApiIoException; import nva.commons.apigateway.exceptions.UnauthorizedException; import nva.commons.core.ioutils.IoUtils; import org.junit.jupiter.api.Test; @@ -51,6 +54,7 @@ class HandlerRequestBuilderTest { private static final String HTTP_METHOD = "httpMethod"; // Can not use ObjectMapper from nva-commons because it would create a circular dependency private final ObjectMapper objectMapper = new ObjectMapper(); + private final HttpClient httpClient = mock(HttpClient.class); @Test void buildReturnsEmptyRequestOnNoArguments() throws Exception { @@ -147,21 +151,22 @@ void buildReturnsRequestWithRequestContextWithCustomerIdClaimWhenWithCustomerId( } @Test - void buildReturnsPersonsFeideIdWhenSet() throws JsonProcessingException { + void buildReturnsPersonsFeideIdWhenSet() throws JsonProcessingException, ApiIoException { var expectedFeideId = randomString(); var request = new HandlerRequestBuilder(objectMapper) .withFeideId(expectedFeideId) .build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = RequestInfo.fromRequest(request, httpClient); assertThat(requestInfo.getFeideId().isPresent(), is(true)); assertThat(requestInfo.getFeideId().orElseThrow(), is(equalTo(expectedFeideId))); } @Test - void buildReturnsEmptyOptionalWhenFeideIdNotSet() throws JsonProcessingException { + void buildReturnsEmptyOptionalWhenFeideIdNotSet() + throws JsonProcessingException, ApiIoException { var request = new HandlerRequestBuilder(objectMapper).build(); - var requestInfo = RequestInfo.fromRequest(request); + var requestInfo = RequestInfo.fromRequest(request, httpClient); assertThat(requestInfo.getFeideId().isPresent(), is(false)); assertThat(requestInfo.getFeideId(), is(equalTo(Optional.empty()))); From 2982f4775a18c56b4d4f290c3afa2a20fe81a4d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B8rn=20Kv=C3=A5le?= Date: Wed, 30 Oct 2024 09:59:15 +0100 Subject: [PATCH 2/5] refactor ApiGatewayHandlerTest --- .../apigateway/ApiGatewayHandlerTest.java | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java b/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java index a74303b9..8164dd71 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java @@ -431,7 +431,7 @@ void handlerSendsRedirectionWhenItReceivesARedirectException() throws IOExceptio @Test void shouldReturnJsonObjectWhenClientAsksForJson() throws Exception { - var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + var handler = getRawStringResponseHandler(); var inputStream = requestWithHeaders(); var expected = objectMapper.convertValue(createBody(), RequestBody.class); var outputStream = outputStream(); @@ -445,7 +445,7 @@ void shouldReturnJsonObjectWhenClientAsksForJson() throws Exception { @Test void shouldReturnXmlObjectWhenClientAsksForXml() throws Exception { - var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + var handler = getRawStringResponseHandler(); var inputStream = requestWithAcceptXmlHeader(); var expected = objectMapper.convertValue(createBody(), RequestBody.class); var outputStream = outputStream(); @@ -460,10 +460,9 @@ void shouldReturnXmlObjectWhenClientAsksForXml() throws Exception { @Test void shouldReturnAllOriginsWhenEnvironmentAllowsAllOrigins() throws IOException { - var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn("*"); - var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + var handler = getRawStringResponseHandler(); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -477,10 +476,9 @@ void shouldReturnAllOriginsWhenEnvironmentAllowsAllOrigins() throws IOException @Test void shouldReturnNvaFrontendProdWhenEnvironmentIsEmpty() throws IOException { - var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn(""); - var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + var handler = getRawStringResponseHandler(); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -495,10 +493,9 @@ void shouldReturnNvaFrontendProdWhenEnvironmentIsEmpty() throws IOException { @Test void shouldEchoAllowedOriginWhenEnvironmentContainsOrigin() throws IOException { var originInHeader = "https://example.com"; - var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn("localhost, " + originInHeader + ", some-place-else"); - var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + var handler = getRawStringResponseHandler(); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -510,14 +507,17 @@ void shouldEchoAllowedOriginWhenEnvironmentContainsOrigin() throws IOException { assertThat(responseHeaders.get(VARY), containsString("Origin")); } + private RawStringResponseHandler getRawStringResponseHandler() { + return new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + } + @Test void shouldReturnOneOfTheAllowedOriginsInEnvironmentWhenRequestOriginIsNotWhiteListed() throws IOException { var originInHeader = "https://example.com"; - var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn("localhost, some-place-else"); - var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + var handler = getRawStringResponseHandler(); var inputStream = requestWithHeaders(); var outputStream = outputStream(); @@ -533,9 +533,8 @@ void shouldReturnOneOfTheAllowedOriginsInEnvironmentWhenRequestOriginIsNotWhiteL void shouldReturnFirstElementInAllowedOriginsListWhenOriginIsMissing() throws IOException { var header1 = "https://example1.com"; var header2 = "https://example2.com"; - var environment = mock(Environment.class); when(environment.readEnv(ALLOWED_ORIGIN_ENV)).thenReturn(header1 + ", " + header2); - var handler = new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + var handler = getRawStringResponseHandler(); var inputStream = requestWithMissingOriginHeader(); var outputStream = outputStream(); handler.handleRequest(inputStream, outputStream, context); From 11f2946979eb0abdf0c4c3dc8b96bbaf71ac9b95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B8rn=20Kv=C3=A5le?= Date: Wed, 30 Oct 2024 09:59:33 +0100 Subject: [PATCH 3/5] bump version --- buildSrc/src/main/groovy/nvacommons.java-conventions.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/groovy/nvacommons.java-conventions.gradle b/buildSrc/src/main/groovy/nvacommons.java-conventions.gradle index becd876c..1d710d6d 100644 --- a/buildSrc/src/main/groovy/nvacommons.java-conventions.gradle +++ b/buildSrc/src/main/groovy/nvacommons.java-conventions.gradle @@ -9,7 +9,7 @@ plugins { } group 'com.github.bibsysdev' -version = '1.40.21' +version = '1.41.0' java { sourceCompatibility = JavaVersion.VERSION_17 From a873fd9cf588d7caa09986e3ee1c2b2f799052c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B8rn=20Kv=C3=A5le?= Date: Wed, 30 Oct 2024 10:09:58 +0100 Subject: [PATCH 4/5] fix shouldReturnApiIoExceptionWhenObjectMapperFails --- .../src/test/java/nva/commons/apigateway/RequestInfoTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java b/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java index 8ee54a49..fd9f799e 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/RequestInfoTest.java @@ -305,7 +305,7 @@ void shouldReturnNotAuthorizedWhenRequestInfoDoesNotContainAccessRightsAndCheckI } @Test - void shouldReturnReturnBadRequestWhenObjectMapperFails(){ + void shouldReturnApiIoExceptionWhenObjectMapperFails(){ var request = "This is not a valid request"; assertThrows(ApiIoException.class, () -> RequestInfo.fromRequest(IoUtils.stringToStream(request), httpClient)); } From 6cd6b2374a94e1934e1891eae59099cc52315d2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B8rn=20Kv=C3=A5le?= Date: Wed, 30 Oct 2024 10:48:49 +0100 Subject: [PATCH 5/5] remove mapper from constructor --- .../commons/apigateway/ApiGatewayHandler.java | 6 +++--- .../apigateway/ApiGatewayProxyHandler.java | 8 +++----- .../apigateway/ApiS3GatewayHandler.java | 4 +--- .../ApiS3PresignerGatewayHandler.java | 4 +--- .../apigateway/ApiGatewayHandlerTest.java | 19 ++----------------- .../java/nva/commons/apigateway/VoidTest.java | 3 +-- .../commons/apigateway/testutils/Handler.java | 7 ++----- .../apigateway/testutils/ProxyHandler.java | 7 ++----- .../testutils/RawStringResponseHandler.java | 6 ++---- 9 files changed, 17 insertions(+), 47 deletions(-) diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java index 8d22da54..3c1137f5 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayHandler.java @@ -57,11 +57,11 @@ public abstract class ApiGatewayHandler extends RestRequestHandler { private boolean isBase64Encoded; public ApiGatewayHandler(Class iclass) { - this(iclass, new Environment(), defaultRestObjectMapper, HttpClient.newBuilder().build()); + this(iclass, new Environment(), HttpClient.newBuilder().build()); } - public ApiGatewayHandler(Class iclass, Environment environment, ObjectMapper objectMapper, HttpClient httpClient) { - super(iclass, environment, objectMapper, httpClient); + public ApiGatewayHandler(Class iclass, Environment environment, HttpClient httpClient) { + super(iclass, environment, defaultRestObjectMapper, httpClient); this.additionalSuccessHeadersSupplier = Collections::emptyMap; } diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java index ce78af13..eee628e5 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiGatewayProxyHandler.java @@ -1,8 +1,6 @@ package nva.commons.apigateway; -import static nva.commons.apigateway.RestConfig.defaultRestObjectMapper; import com.amazonaws.services.lambda.runtime.Context; -import com.fasterxml.jackson.databind.ObjectMapper; import java.net.http.HttpClient; import nva.commons.apigateway.exceptions.ApiGatewayException; import nva.commons.core.Environment; @@ -20,12 +18,12 @@ public abstract class ApiGatewayProxyHandler extends ApiGatewayHandler iclass) { - this(iclass, new Environment(), defaultRestObjectMapper, HttpClient.newBuilder().build()); + this(iclass, new Environment(), HttpClient.newBuilder().build()); } @JacocoGenerated - protected ApiGatewayProxyHandler(Class iclass, Environment environment, ObjectMapper objectMapper, HttpClient httpClient) { - super(iclass, environment, objectMapper, httpClient); + protected ApiGatewayProxyHandler(Class iclass, Environment environment, HttpClient httpClient) { + super(iclass, environment, httpClient); } @Override diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java index 461eeb96..0bd45f8c 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiS3GatewayHandler.java @@ -1,7 +1,6 @@ package nva.commons.apigateway; import com.amazonaws.services.lambda.runtime.Context; -import com.fasterxml.jackson.databind.ObjectMapper; import java.net.http.HttpClient; import java.time.Duration; import nva.commons.apigateway.exceptions.BadRequestException; @@ -30,9 +29,8 @@ public ApiS3GatewayHandler(Class iclass, S3Client s3client, S3Presigner s3Presigner, Environment environment, - ObjectMapper objectMapper, HttpClient httpClient) { - super(iclass, s3Presigner, environment, objectMapper, httpClient); + super(iclass, s3Presigner, environment, httpClient); this.s3client = s3client; } diff --git a/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java b/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java index 9c74a217..35e181ea 100644 --- a/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java +++ b/apigateway/src/main/java/nva/commons/apigateway/ApiS3PresignerGatewayHandler.java @@ -1,7 +1,6 @@ package nva.commons.apigateway; import com.amazonaws.services.lambda.runtime.Context; -import com.fasterxml.jackson.databind.ObjectMapper; import java.net.HttpURLConnection; import java.net.http.HttpClient; import java.time.Duration; @@ -32,9 +31,8 @@ public ApiS3PresignerGatewayHandler(Class iclass, S3Presigner s3Presigner) { public ApiS3PresignerGatewayHandler(Class iclass, S3Presigner s3Presigner, Environment environment, - ObjectMapper objectMapper, HttpClient httpClient) { - super(iclass, environment, objectMapper, httpClient); + super(iclass, environment, httpClient); this.s3presigner = s3Presigner; } diff --git a/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java b/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java index 8164dd71..49b71cb5 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/ApiGatewayHandlerTest.java @@ -26,17 +26,12 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.amazonaws.services.lambda.runtime.Context; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.xml.XmlMapper; @@ -104,7 +99,7 @@ public void setup() { httpClient = mock(HttpClient.class); environment = mock(Environment.class); when(environment.readEnv("ALLOWED_ORIGIN")).thenReturn("*"); - handler = new Handler(defaultRestObjectMapper, environment, httpClient); + handler = new Handler(environment, httpClient); } @Test @@ -397,16 +392,6 @@ void shouldReturnContentTypeMatchingSupportedMediaTypeWhenSupportedMediaTypeIsRe assertThat(response.getHeaders().get(CONTENT_TYPE), is(equalTo(mediaType))); } - @Test - void handlerSerializesBodyWithNonDefaultSerializationWhenDefaultSerializerIsOverridden() throws IOException { - ObjectMapper spiedMapper = spy(defaultRestObjectMapper); - var handler = new Handler(spiedMapper, environment, httpClient); - var inputStream = requestWithHeaders(); - var outputStream = outputStream(); - handler.handleRequest(inputStream, outputStream, context); - verify(spiedMapper, atLeast(1)).writeValueAsString(any()); - } - @Test void handlerSerializesWithIsBase64Encoded() throws IOException { var output = outputStream(); @@ -508,7 +493,7 @@ void shouldEchoAllowedOriginWhenEnvironmentContainsOrigin() throws IOException { } private RawStringResponseHandler getRawStringResponseHandler() { - return new RawStringResponseHandler(dtoObjectMapper, environment, httpClient); + return new RawStringResponseHandler(environment, httpClient); } @Test diff --git a/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java b/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java index 9d6af6eb..1c391893 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java +++ b/apigateway/src/test/java/nva/commons/apigateway/VoidTest.java @@ -1,7 +1,6 @@ package nva.commons.apigateway; import static nva.commons.apigateway.ApiGatewayHandler.ALLOWED_ORIGIN_ENV; -import static nva.commons.apigateway.RestConfig.defaultRestObjectMapper; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; @@ -81,7 +80,7 @@ private class VoidHandler extends ApiGatewayHandler { public static final String SAMPLE_STRING = "sampleString"; public VoidHandler(Environment environment, HttpClient httpClient) { - super(Void.class, environment, defaultRestObjectMapper, httpClient); + super(Void.class, environment, httpClient); } @Override diff --git a/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java b/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java index 46b8388c..a5aa7777 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java +++ b/apigateway/src/test/java/nva/commons/apigateway/testutils/Handler.java @@ -2,7 +2,6 @@ import static nva.commons.apigateway.RequestInfoConstants.PROXY_TAG; import com.amazonaws.services.lambda.runtime.Context; -import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.HttpHeaders; import java.net.HttpURLConnection; import java.net.http.HttpClient; @@ -26,11 +25,9 @@ public Handler() { /** * Constructor that overrides default serialization. - * - * @param mapper Object Mapper */ - public Handler(ObjectMapper mapper,Environment environment, HttpClient httpClient) { - super(RequestBody.class, environment, mapper, httpClient); + public Handler(Environment environment, HttpClient httpClient) { + super(RequestBody.class, environment, httpClient); } @Override diff --git a/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java b/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java index ed4d6ac2..cb3113b7 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java +++ b/apigateway/src/test/java/nva/commons/apigateway/testutils/ProxyHandler.java @@ -2,7 +2,6 @@ import static nva.commons.apigateway.RequestInfoConstants.PROXY_TAG; import com.amazonaws.services.lambda.runtime.Context; -import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.HttpHeaders; import java.net.http.HttpClient; import java.util.Collections; @@ -27,11 +26,9 @@ public ProxyHandler() { /** * Constructor that overrides default serialization. - * - * @param mapper Object Mapper */ - public ProxyHandler(ObjectMapper mapper, Environment environment, HttpClient httpClient) { - super(RequestBody.class, environment, mapper, httpClient); + public ProxyHandler(Environment environment, HttpClient httpClient) { + super(RequestBody.class, environment, httpClient); } @Override diff --git a/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java b/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java index dfe33df8..a330d51f 100644 --- a/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java +++ b/apigateway/src/test/java/nva/commons/apigateway/testutils/RawStringResponseHandler.java @@ -32,11 +32,9 @@ public RawStringResponseHandler() { /** * Constructor that overrides default serialization. - * - * @param mapper Object Mapper */ - public RawStringResponseHandler(ObjectMapper mapper, Environment environment, HttpClient httpClient) { - super(RequestBody.class, environment, mapper, httpClient); + public RawStringResponseHandler(Environment environment, HttpClient httpClient) { + super(RequestBody.class, environment, httpClient); } @Override