From 3ae6a5ff7b7ffe2d739dbfeb1b20ba7b9fef9446 Mon Sep 17 00:00:00 2001 From: Tom Wetjens Date: Wed, 30 Apr 2025 15:53:30 +0200 Subject: [PATCH] #153 Remove HttpStatusCode enum Signed-off-by: Tom Wetjens --- .../core/common/HttpStatusCode.java | 116 -------- .../exception/UftpConnectorException.java | 15 +- .../common/xsd/XsdValidationException.java | 22 ++ .../core/common/xsd/XsdValidator.java | 4 +- .../service/crypto/UftpCryptoException.java | 23 ++ .../service/crypto/UftpCryptoService.java | 11 +- .../service/crypto/UftpSignException.java | 16 ++ .../service/crypto/UftpVerifyException.java | 20 ++ .../sending/UftpClientErrorException.java | 4 +- .../service/sending/UftpSendException.java | 16 +- .../sending/UftpSendMessageService.java | 50 ++-- .../sending/UftpServerErrorException.java | 4 +- .../service/serialization/UftpSerializer.java | 5 +- .../UftpSerializerException.java | 5 +- .../shapeshifter/core/UftpTestSupport.java | 169 ++++------- .../exception/UftpConnectorExceptionTest.java | 60 ---- .../core/common/xml/JAXBToolsTest.java | 180 ++++++------ .../core/common/xsd/XsdFactoryTest.java | 87 +++--- .../core/common/xsd/XsdSchemaPoolTest.java | 185 ++++++------ .../core/common/xsd/XsdValidatorTest.java | 108 ++++--- .../service/crypto/UftpCryptoServiceTest.java | 268 +++++++++--------- .../sending/UftpSendMessageServiceTest.java | 73 +++-- .../serialization/UftpSerializerTest.java | 150 +++++----- .../handler/UftpNotImplementedException.java | 11 + .../handler/UftpPayloadDispatcher.java | 6 +- .../receiving/UftpInternalController.java | 16 +- .../receiving/UftpInternalControllerTest.java | 61 ++-- 27 files changed, 767 insertions(+), 918 deletions(-) delete mode 100644 core/src/main/java/org/lfenergy/shapeshifter/core/common/HttpStatusCode.java create mode 100644 core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidationException.java create mode 100644 core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoException.java create mode 100644 core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpSignException.java create mode 100644 core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpVerifyException.java delete mode 100644 core/src/test/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorExceptionTest.java create mode 100644 spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpNotImplementedException.java diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/common/HttpStatusCode.java b/core/src/main/java/org/lfenergy/shapeshifter/core/common/HttpStatusCode.java deleted file mode 100644 index d9f5a95..0000000 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/common/HttpStatusCode.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.lfenergy.shapeshifter.core.common; - -import lombok.Getter; - -@Getter -public enum HttpStatusCode { - - //1xx: Informational - CONTINUE(100, "Continue"), - SWITCHING_PROTOCOLS(101, "Switching Protocols"), - PROCESSING(102, "Processing"), - EARLY_HINTS(103, "Early Hints"), - - //2xx: Success - OK(200, "OK"), - CREATED(201, "Created"), - ACCEPTED(202, "Accepted"), - NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"), - NO_CONTENT(204, "No Content"), - RESET_CONTENT(205, "Reset Content"), - PARTIAL_CONTENT(206, "Partial Content"), - MULTI_STATUS(207, "Multi-Status"), - ALREADY_REPORTED(208, "Already Reported"), - IM_USED(226, "IM Used"), - - //3xx: Redirection - MULTIPLE_CHOICES(300, "Multiple Choice"), - MOVED_PERMANENTLY(301, "Moved Permanently"), - FOUND(302, "Found"), - SEE_OTHER(303, "See Other"), - NOT_MODIFIED(304, "Not Modified"), - USE_PROXY(305, "Use Proxy"), - TEMPORARY_REDIRECT(307, "Temporary Redirect"), - PERMANENT_REDIRECT(308, "Permanent Redirect"), - - //4xx: Client Error - BAD_REQUEST(400, "Bad Request"), - UNAUTHORIZED(401, "Unauthorized"), - PAYMENT_REQUIRED(402, "Payment Required"), - FORBIDDEN(403, "Forbidden"), - NOT_FOUND(404, "Not Found"), - METHOD_NOT_ALLOWED(405, "Method Not Allowed"), - NOT_ACCEPTABLE(406, "Not Acceptable"), - PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"), - REQUEST_TIMEOUT(408, "Request Timeout"), - CONFLICT(409, "Conflict"), - GONE(410, "Gone"), - LENGTH_REQUIRED(411, "Length Required"), - PRECONDITION_FAILED(412, "Precondition Failed"), - REQUEST_TOO_LONG(413, "Payload Too Large"), - REQUEST_URI_TOO_LONG(414, "URI Too Long"), - UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), - REQUESTED_RANGE_NOT_SATISFIABLE(416, "Range Not Satisfiable"), - EXPECTATION_FAILED(417, "Expectation Failed"), - MISDIRECTED_REQUEST(421, "Misdirected Request"), - UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"), - LOCKED(423, "Locked"), - FAILED_DEPENDENCY(424, "Failed Dependency"), - TOO_EARLY(425, "Too Early"), - UPGRADE_REQUIRED(426, "Upgrade Required"), - PRECONDITION_REQUIRED(428, "Precondition Required"), - TOO_MANY_REQUESTS(429, "Too Many Requests"), - REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"), - UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"), - - //5xx: Server Error - INTERNAL_SERVER_ERROR(500, "Internal Server Error"), - NOT_IMPLEMENTED(501, "Not Implemented"), - BAD_GATEWAY(502, "Bad Gateway"), - SERVICE_UNAVAILABLE(503, "Service Unavailable"), - GATEWAY_TIMEOUT(504, "Gateway Timeout"), - HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"), - VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates"), - INSUFFICIENT_STORAGE(507, "Insufficient Storage"), - LOOP_DETECTED(508, "Loop Detected"), - NOT_EXTENDED(510, "Not Extended"), - NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required"); - - private final int value; - private final String description; - - HttpStatusCode(int value, String description) { - this.value = value; - this.description = description; - } - - @Override - public String toString() { - return value + " " + description; - } - - public static HttpStatusCode getByValue(int value) { - for (HttpStatusCode status : values()) { - if (status.value == value) { - return status; - } - } - throw new IllegalArgumentException("Invalid status code: " + value); - } - - public boolean isSuccess() { - return value >= 200 && value < 300; - } - - public boolean isClientError() { - return value >= 400 && value < 500; - } - - public boolean isServerError() { - return value >= 500; - } - - public boolean isRedirect() { - return value >= 300 && value < 400; - } -} diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorException.java index 263b817..e026d09 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorException.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorException.java @@ -5,27 +5,16 @@ package org.lfenergy.shapeshifter.core.common.exception; import lombok.Getter; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; @Getter public class UftpConnectorException extends RuntimeException { - private final HttpStatusCode httpStatusCode; - public UftpConnectorException(String message) { - this(message, HttpStatusCode.INTERNAL_SERVER_ERROR, null); + super(message); } public UftpConnectorException(String message, Throwable cause) { - this(message, HttpStatusCode.INTERNAL_SERVER_ERROR, cause); - } - - public UftpConnectorException(String message, HttpStatusCode httpStatusCode) { - this(message, httpStatusCode, null); - } - - public UftpConnectorException(String message, HttpStatusCode httpStatusCode, Throwable cause) { super(message, cause); - this.httpStatusCode = httpStatusCode; } + } diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidationException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidationException.java new file mode 100644 index 0000000..de6d5be --- /dev/null +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidationException.java @@ -0,0 +1,22 @@ +// Copyright 2023 Contributors to the Shapeshifter project +// +// SPDX-License-Identifier: Apache-2.0 + +package org.lfenergy.shapeshifter.core.common.xsd; + +import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; + +/** + * Thrown when validation against XSD failed. + */ +public class XsdValidationException extends UftpConnectorException { + + public XsdValidationException(String message) { + super(message); + } + + public XsdValidationException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidator.java b/core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidator.java index ae804ff..0ec7de8 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidator.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidator.java @@ -11,8 +11,6 @@ import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Validator; import lombok.RequiredArgsConstructor; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; -import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; import org.xml.sax.SAXException; @RequiredArgsConstructor @@ -26,7 +24,7 @@ public void validate(final String xml, URL xsd) { final Validator validator = schemaProvider.getValidator(xsd); validator.validate(xmlSource); } catch (SAXException | IOException cause) { - throw new UftpConnectorException("XSD validation failed: " + cause.getMessage(), HttpStatusCode.BAD_REQUEST, cause); + throw new XsdValidationException("XSD validation failed: " + cause.getMessage(), cause); } } } diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoException.java new file mode 100644 index 0000000..6724761 --- /dev/null +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoException.java @@ -0,0 +1,23 @@ +// Copyright 2023 Contributors to the Shapeshifter project +// +// SPDX-License-Identifier: Apache-2.0 + +package org.lfenergy.shapeshifter.core.service.crypto; + +import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; + +/** + * Thrown when message verification failed. + */ +@SuppressWarnings("java:S110") // More than 5 parents is useful and intended in this case +public class UftpCryptoException extends UftpConnectorException { + + public UftpCryptoException(String message) { + super(message); + } + + public UftpCryptoException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoService.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoService.java index f04c829..aee9df4 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoService.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoService.java @@ -5,14 +5,13 @@ package org.lfenergy.shapeshifter.core.service.crypto; import com.goterl.lazysodium.LazySodiumJava; -import java.util.Base64; import lombok.RequiredArgsConstructor; import org.lfenergy.shapeshifter.api.SignedMessage; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; -import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; import org.lfenergy.shapeshifter.core.model.UftpParticipant; import org.lfenergy.shapeshifter.core.service.participant.ParticipantResolutionService; +import java.util.Base64; + @RequiredArgsConstructor public class UftpCryptoService { @@ -33,7 +32,7 @@ public SignedMessage signMessage(String payloadXml, UftpParticipant sender, Stri return signedMessage; } catch (Exception cause) { - throw new UftpConnectorException("Failed to sign message.", cause); + throw new UftpSignException("Failed to sign message.", cause); } finally { lazySodiumInstancePool.release(lazySodium); } @@ -44,7 +43,7 @@ public String verifySignedMessage(SignedMessage signedMessage) { String publicKey = participantService.getPublicKey(signedMessage.getSenderRole(), signedMessage.getSenderDomain()); return verifySignedMessage(signedMessage, publicKey); } catch (Exception cause) { - throw new UftpConnectorException("Failed to verify message.", HttpStatusCode.UNAUTHORIZED, cause); + throw new UftpVerifyException("Failed to verify message.", cause); } } @@ -57,7 +56,7 @@ public String verifySignedMessage(SignedMessage signedMessage, String publicKey) var unsealed = lazySodium.cryptoSignOpen(base64Body, factory.keyFromBase64String(publicKey)); if (unsealed == null) { - throw new UftpConnectorException("Failed to verify message. Message is not validly signed for given public key."); + throw new UftpVerifyException("Failed to verify message. Message is not validly signed for given public key."); } return unsealed; diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpSignException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpSignException.java new file mode 100644 index 0000000..0d9e3d5 --- /dev/null +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpSignException.java @@ -0,0 +1,16 @@ +// Copyright 2023 Contributors to the Shapeshifter project +// +// SPDX-License-Identifier: Apache-2.0 + +package org.lfenergy.shapeshifter.core.service.crypto; + +/** + * Thrown when message signing failed. + */ +public class UftpSignException extends UftpCryptoException { + + public UftpSignException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpVerifyException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpVerifyException.java new file mode 100644 index 0000000..2285274 --- /dev/null +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/crypto/UftpVerifyException.java @@ -0,0 +1,20 @@ +// Copyright 2023 Contributors to the Shapeshifter project +// +// SPDX-License-Identifier: Apache-2.0 + +package org.lfenergy.shapeshifter.core.service.crypto; + +/** + * Thrown when message verification failed. + */ +public class UftpVerifyException extends UftpCryptoException { + + public UftpVerifyException(String message) { + super(message); + } + + public UftpVerifyException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpClientErrorException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpClientErrorException.java index bce74f7..a2ef002 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpClientErrorException.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpClientErrorException.java @@ -4,15 +4,13 @@ package org.lfenergy.shapeshifter.core.service.sending; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; - /** * Exception thrown when an HTTP 4xx is received while sending an UFTP message. */ @SuppressWarnings("java:S110") // More than 5 parents useful and intended in this case public final class UftpClientErrorException extends UftpSendException { - public UftpClientErrorException(String message, HttpStatusCode httpStatusCode) { + public UftpClientErrorException(String message, int httpStatusCode) { super(message, httpStatusCode); } diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendException.java index 3c6bfe1..a7dce53 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendException.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendException.java @@ -4,27 +4,33 @@ package org.lfenergy.shapeshifter.core.service.sending; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; +import java.util.Optional; + /** * Base class for exceptions thrown when sending an UFTP message fails e.g. when a request fails because of an error response, or a low level I/O error. */ public class UftpSendException extends UftpConnectorException { + private final Integer httpStatusCode; + public UftpSendException(String message) { super(message); + this.httpStatusCode = null; } public UftpSendException(String message, Throwable cause) { super(message, cause); + this.httpStatusCode = null; } - public UftpSendException(String message, HttpStatusCode httpStatusCode) { - super(message, httpStatusCode); + public UftpSendException(String message, int httpStatusCode) { + super(message); + this.httpStatusCode = httpStatusCode; } - public UftpSendException(String message, HttpStatusCode httpStatusCode, Throwable cause) { - super(message, httpStatusCode, cause); + public Optional getHttpStatusCode() { + return Optional.ofNullable(httpStatusCode); } } diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageService.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageService.java index 0d0eba6..1b1d5a9 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageService.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageService.java @@ -4,25 +4,11 @@ package org.lfenergy.shapeshifter.core.service.sending; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpRequest.BodyPublishers; -import java.net.http.HttpResponse.BodyHandlers; -import java.text.MessageFormat; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - import lombok.NonNull; import lombok.extern.apachecommons.CommonsLog; import org.lfenergy.shapeshifter.api.PayloadMessageResponseType; import org.lfenergy.shapeshifter.api.PayloadMessageType; import org.lfenergy.shapeshifter.api.model.UftpParticipantInformation; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; import org.lfenergy.shapeshifter.core.model.SigningDetails; import org.lfenergy.shapeshifter.core.model.UftpMessage; import org.lfenergy.shapeshifter.core.service.ParticipantAuthorizationProvider; @@ -31,6 +17,18 @@ import org.lfenergy.shapeshifter.core.service.serialization.UftpSerializer; import org.lfenergy.shapeshifter.core.service.validation.UftpValidationService; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublishers; +import java.net.http.HttpResponse.BodyHandlers; +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + /** * Sends UFTP messages to recipients */ @@ -38,15 +36,15 @@ public class UftpSendMessageService { private static final int MAX_FOLLOW_REDIRECTS = 2; - private static final Set FOLLOW_REDIRECT_STATUS_CODES = EnumSet.of( + private static final Set FOLLOW_REDIRECT_STATUS_CODES = Set.of( // These redirect status codes are not followed: // - 300 Multiple Choices: not applicable to Shapeshifter // - 301 Moved Permanently: only for GET and HEAD // - 303 See Other: the redirect Location will always use GET // - 304 Not Modified: only for GET and HEAD (with If-None-Match or If-Modified-Since header) // - 305 Use Proxy: deprecated - HttpStatusCode.TEMPORARY_REDIRECT, - HttpStatusCode.PERMANENT_REDIRECT + 307, // Temporary Redirect + 308 // Permanent Redirect ); private static final String REDIRECT_LOCATION_HEADER_NAME = "Location"; @@ -153,25 +151,23 @@ private void send(String signedXml, String url, Map additionalHe var response = httpClient.send(request, BodyHandlers.ofString()); - var httpStatusCode = HttpStatusCode.getByValue(response.statusCode()); - - if (!httpStatusCode.isSuccess()) { + if (response.statusCode() >= 300) { // not success // According to the specification: redirects (responses with status code 3xx) should be honored in order to support load balancing - if (httpStatusCode.isRedirect() && FOLLOW_REDIRECT_STATUS_CODES.contains(httpStatusCode)) { + if (FOLLOW_REDIRECT_STATUS_CODES.contains(response.statusCode())) { if (maxFollowRedirects <= 0) { throw new UftpSendException(MessageFormat.format(MSG_TOO_MANY_REDIRECTS, url)); } var redirectUrl = response.headers().firstValue(REDIRECT_LOCATION_HEADER_NAME) - .orElseThrow(() -> new UftpServerErrorException(MessageFormat.format(MSG_MISSING_REDIRECT_LOCATION, url), httpStatusCode)); + .orElseThrow(() -> new UftpServerErrorException(MessageFormat.format(MSG_MISSING_REDIRECT_LOCATION, url), response.statusCode())); send(signedXml, redirectUrl, additionalHeaders, maxFollowRedirects - 1); - } else if (httpStatusCode.isClientError()) { - throw new UftpClientErrorException(MessageFormat.format(MSG_CLIENT_ERROR, response.statusCode(), url, response.body()), httpStatusCode); - } else if (httpStatusCode.isServerError()) { - throw new UftpServerErrorException(MessageFormat.format(MSG_SERVER_ERROR, response.statusCode(), url, response.body()), httpStatusCode); + } else if (response.statusCode() >= 400 && response.statusCode() < 500) { + throw new UftpClientErrorException(MessageFormat.format(MSG_CLIENT_ERROR, response.statusCode(), url, response.body()), response.statusCode()); + } else if (response.statusCode() >= 500 && response.statusCode() < 600) { + throw new UftpServerErrorException(MessageFormat.format(MSG_SERVER_ERROR, response.statusCode(), url, response.body()), response.statusCode()); } else { - throw new UftpSendException(MessageFormat.format(MSG_UNEXPECTED_RESPONSE_STATUS, response.statusCode(), url, response.body()), httpStatusCode); + throw new UftpSendException(MessageFormat.format(MSG_UNEXPECTED_RESPONSE_STATUS, response.statusCode(), url, response.body()), response.statusCode()); } } } catch (URISyntaxException | IllegalArgumentException e) { diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpServerErrorException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpServerErrorException.java index 01fe637..2561d23 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpServerErrorException.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/sending/UftpServerErrorException.java @@ -4,15 +4,13 @@ package org.lfenergy.shapeshifter.core.service.sending; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; - /** * Exception thrown when an HTTP 5xx is received while sending an UFTP message. */ @SuppressWarnings("java:S110") // More than 5 parents useful and intended in this case public final class UftpServerErrorException extends UftpSendException { - public UftpServerErrorException(String message, HttpStatusCode httpStatusCode) { + public UftpServerErrorException(String message, int httpStatusCode) { super(message, httpStatusCode); } diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializer.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializer.java index 4d3033c..062b432 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializer.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializer.java @@ -8,7 +8,6 @@ import org.lfenergy.shapeshifter.api.PayloadMessageType; import org.lfenergy.shapeshifter.api.SignedMessage; import org.lfenergy.shapeshifter.api.xsdinfo.UftpXsds; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; import org.lfenergy.shapeshifter.core.common.xml.XmlSerializer; import org.lfenergy.shapeshifter.core.common.xsd.XsdValidator; @@ -24,7 +23,7 @@ public SignedMessage fromSignedXml(String signedXml) { try { return serializer.fromXml(signedXml, SignedMessage.class); } catch (Exception cause) { - throw new UftpSerializerException("SignedMessage XML deserialization failed: " + cause.getMessage(), cause, HttpStatusCode.BAD_REQUEST); + throw new UftpSerializerException("SignedMessage XML deserialization failed: " + cause.getMessage(), cause); } } @@ -34,7 +33,7 @@ public PayloadMessageType fromPayloadXml(String payloadXml) { try { return serializer.fromXml(payloadXml, PayloadMessageType.class); } catch (Exception cause) { - throw new UftpSerializerException("Payload message XML deserialization failed: " + cause.getMessage(), cause, HttpStatusCode.BAD_REQUEST); + throw new UftpSerializerException("Payload message XML deserialization failed: " + cause.getMessage(), cause); } } diff --git a/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerException.java b/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerException.java index 96fe9b8..4c91443 100644 --- a/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerException.java +++ b/core/src/main/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerException.java @@ -4,7 +4,6 @@ package org.lfenergy.shapeshifter.core.service.serialization; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; /** @@ -12,8 +11,8 @@ */ public class UftpSerializerException extends UftpConnectorException { - public UftpSerializerException(String message, Throwable cause, HttpStatusCode status) { - super(message, status, cause); + public UftpSerializerException(String message, Throwable cause) { + super(message, cause); } } diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/UftpTestSupport.java b/core/src/test/java/org/lfenergy/shapeshifter/core/UftpTestSupport.java index 5cf24fd..b3ab2ae 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/UftpTestSupport.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/UftpTestSupport.java @@ -4,128 +4,61 @@ package org.lfenergy.shapeshifter.core; -import static org.assertj.core.api.Assertions.assertThat; +import org.lfenergy.shapeshifter.api.*; import java.util.Set; -import org.lfenergy.shapeshifter.api.AGRPortfolioQuery; -import org.lfenergy.shapeshifter.api.AGRPortfolioQueryResponse; -import org.lfenergy.shapeshifter.api.AGRPortfolioUpdate; -import org.lfenergy.shapeshifter.api.AGRPortfolioUpdateResponse; -import org.lfenergy.shapeshifter.api.DPrognosis; -import org.lfenergy.shapeshifter.api.DPrognosisResponse; -import org.lfenergy.shapeshifter.api.DSOPortfolioQuery; -import org.lfenergy.shapeshifter.api.DSOPortfolioQueryResponse; -import org.lfenergy.shapeshifter.api.DSOPortfolioUpdate; -import org.lfenergy.shapeshifter.api.DSOPortfolioUpdateResponse; -import org.lfenergy.shapeshifter.api.FlexMessageType; -import org.lfenergy.shapeshifter.api.FlexOffer; -import org.lfenergy.shapeshifter.api.FlexOfferResponse; -import org.lfenergy.shapeshifter.api.FlexOfferRevocation; -import org.lfenergy.shapeshifter.api.FlexOfferRevocationResponse; -import org.lfenergy.shapeshifter.api.FlexOrder; -import org.lfenergy.shapeshifter.api.FlexOrderResponse; -import org.lfenergy.shapeshifter.api.FlexRequest; -import org.lfenergy.shapeshifter.api.FlexRequestResponse; -import org.lfenergy.shapeshifter.api.FlexReservationUpdate; -import org.lfenergy.shapeshifter.api.FlexReservationUpdateResponse; -import org.lfenergy.shapeshifter.api.FlexSettlement; -import org.lfenergy.shapeshifter.api.FlexSettlementResponse; -import org.lfenergy.shapeshifter.api.Metering; -import org.lfenergy.shapeshifter.api.MeteringResponse; -import org.lfenergy.shapeshifter.api.PayloadMessageResponseType; -import org.lfenergy.shapeshifter.api.PayloadMessageType; -import org.lfenergy.shapeshifter.api.TestMessage; -import org.lfenergy.shapeshifter.api.TestMessageResponse; -import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; public class UftpTestSupport { - public static void assertException(UftpConnectorException thrown, - String message) { - assertException(thrown, message, 500); - } - - public static void assertExceptionCauseNotNull(UftpConnectorException thrown, - String message) { - assertExceptionCauseNotNull(thrown, message, 500); - } - - public static void assertException(UftpConnectorException thrown, - String message, Throwable rootCause) { - assertException(thrown, message, rootCause, 500); - } - - public static void assertException(UftpConnectorException thrown, - String message, int httpStatusCode) { - assertThat(thrown).hasMessage(message) - .hasNoCause(); - assertThat(thrown.getHttpStatusCode().getValue()).isEqualTo(httpStatusCode); - } - - public static void assertExceptionCauseNotNull(UftpConnectorException thrown, - String message, int httpStatusCode) { - assertThat(thrown).hasMessage(message); - assertThat(thrown.getCause()).isNotNull(); - assertThat(thrown.getHttpStatusCode().getValue()).isEqualTo(httpStatusCode); - } - - public static void assertException(UftpConnectorException thrown, - String message, Throwable rootCause, - int httpStatusCode) { - assertThat(thrown).hasMessage(message); - assertThat(thrown.getCause()).isSameAs(rootCause); - assertThat(thrown.getHttpStatusCode().getValue()).isEqualTo(httpStatusCode); - } - - public static Set> flexMessageTypes() { - return Set.of( - DPrognosis.class, - FlexReservationUpdate.class, - FlexRequest.class, - FlexOffer.class, - FlexOrder.class - ); - } - - public static Set> allMessageTypes() { - return Set.of( - // The root base class - PayloadMessageType.class, - - // Directly inherit from PayloadMessageType - TestMessage.class, - AGRPortfolioUpdate.class, - AGRPortfolioQuery.class, - FlexOfferRevocation.class, - FlexSettlement.class, - DSOPortfolioUpdate.class, - DSOPortfolioQuery.class, - Metering.class, - PayloadMessageResponseType.class, - FlexMessageType.class, - - // Directly inherit from PayloadMessageResponseType - TestMessageResponse.class, - AGRPortfolioUpdateResponse.class, - AGRPortfolioQueryResponse.class, - DPrognosisResponse.class, - FlexReservationUpdateResponse.class, - FlexRequestResponse.class, - FlexOfferResponse.class, - FlexOfferRevocationResponse.class, - FlexOrderResponse.class, - FlexSettlementResponse.class, - DSOPortfolioUpdateResponse.class, - DSOPortfolioQueryResponse.class, - MeteringResponse.class, - - // Directly inherit from FlexMessageType - DPrognosis.class, - FlexReservationUpdate.class, - FlexRequest.class, - FlexOffer.class, - FlexOrder.class - ); - } + public static Set> flexMessageTypes() { + return Set.of( + DPrognosis.class, + FlexReservationUpdate.class, + FlexRequest.class, + FlexOffer.class, + FlexOrder.class + ); + } + + public static Set> allMessageTypes() { + return Set.of( + // The root base class + PayloadMessageType.class, + + // Directly inherit from PayloadMessageType + TestMessage.class, + AGRPortfolioUpdate.class, + AGRPortfolioQuery.class, + FlexOfferRevocation.class, + FlexSettlement.class, + DSOPortfolioUpdate.class, + DSOPortfolioQuery.class, + Metering.class, + PayloadMessageResponseType.class, + FlexMessageType.class, + + // Directly inherit from PayloadMessageResponseType + TestMessageResponse.class, + AGRPortfolioUpdateResponse.class, + AGRPortfolioQueryResponse.class, + DPrognosisResponse.class, + FlexReservationUpdateResponse.class, + FlexRequestResponse.class, + FlexOfferResponse.class, + FlexOfferRevocationResponse.class, + FlexOrderResponse.class, + FlexSettlementResponse.class, + DSOPortfolioUpdateResponse.class, + DSOPortfolioQueryResponse.class, + MeteringResponse.class, + + // Directly inherit from FlexMessageType + DPrognosis.class, + FlexReservationUpdate.class, + FlexRequest.class, + FlexOffer.class, + FlexOrder.class + ); + } } diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorExceptionTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorExceptionTest.java deleted file mode 100644 index 0e30512..0000000 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/common/exception/UftpConnectorExceptionTest.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2023 Contributors to the Shapeshifter project -// -// SPDX-License-Identifier: Apache-2.0 - -package org.lfenergy.shapeshifter.core.common.exception; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class UftpConnectorExceptionTest { - - @Mock - private Throwable cause; - - @AfterEach - void noMore() { - Mockito.verifyNoMoreInteractions(cause); - } - - @Test - void testMessageConstruction() { - UftpConnectorException testSubject = new UftpConnectorException("test"); - assertThat(testSubject.getMessage()).isEqualTo("test"); - assertThat(testSubject.getCause()).isNull(); - assertThat(testSubject.getHttpStatusCode().getValue()).isEqualTo(500); - } - - @Test - void testMessageAndCauseConstruction() { - UftpConnectorException testSubject = new UftpConnectorException("test", cause); - assertThat(testSubject.getMessage()).isEqualTo("test"); - assertThat(testSubject.getCause()).isSameAs(cause); - assertThat(testSubject.getHttpStatusCode().getValue()).isEqualTo(500); - } - - @Test - void testMessageAndHttpStatusConstruction() { - UftpConnectorException testSubject = new UftpConnectorException("test", HttpStatusCode.BAD_REQUEST); - assertThat(testSubject.getMessage()).isEqualTo("test"); - assertThat(testSubject.getCause()).isNull(); - assertThat(testSubject.getHttpStatusCode().getValue()).isEqualTo(400); - } - - @Test - void testMessageCauseAndHttpStatusConstruction() { - UftpConnectorException testSubject = new UftpConnectorException("test", HttpStatusCode.BAD_REQUEST, cause); - assertThat(testSubject.getMessage()).isEqualTo("test"); - assertThat(testSubject.getCause()).isSameAs(cause); - assertThat(testSubject.getHttpStatusCode().getValue()).isEqualTo(400); - } - -} \ No newline at end of file diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xml/JAXBToolsTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xml/JAXBToolsTest.java index efa8311..e2a88c2 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xml/JAXBToolsTest.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xml/JAXBToolsTest.java @@ -4,11 +4,6 @@ package org.lfenergy.shapeshifter.core.common.xml; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.lfenergy.shapeshifter.core.UftpTestSupport.assertException; -import static org.lfenergy.shapeshifter.core.UftpTestSupport.assertExceptionCauseNotNull; - import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; @@ -21,93 +16,96 @@ import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + @ExtendWith(MockitoExtension.class) class JAXBToolsTest { - @InjectMocks - private JAXBTools jaxbTools; - - @Test - void getContext() { - final JAXBContext ctx1 = jaxbTools.getJAXBContext(JAXBTools.class); - final JAXBContext ctx2 = jaxbTools.getJAXBContext(UftpParticipant.class); - final JAXBContext ctx3 = jaxbTools.getJAXBContext(UftpParticipant.class); - - assertThat(ctx1).isNotNull(); - assertThat(ctx2).isNotNull(); - assertThat(ctx3).isNotNull(); - assertThat(ctx2).isNotSameAs(ctx1); - assertThat(ctx3).isNotSameAs(ctx1); - assertThat(ctx3).isSameAs(ctx2); - } - - @Test - void getContextThrowsOnNull() { - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> jaxbTools.getJAXBContext(null)); - - assertException(actual, "Type to (de)serialize must be specified"); - } - - @Test - void createMarshaller() { - final Marshaller m1 = jaxbTools.createMarshaller(JAXBTools.class); - final Marshaller m2 = jaxbTools.createMarshaller(UftpParticipant.class); - final Marshaller m3 = jaxbTools.createMarshaller(UftpParticipant.class); - - assertThat(m1).isNotNull(); - assertThat(m2).isNotNull(); - assertThat(m3).isNotNull(); - assertThat(m2).isNotSameAs(m1); - assertThat(m3).isNotSameAs(m1); - assertThat(m3).isNotSameAs(m2); - } - - @Test - void createMarshallerThrows() { - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> jaxbTools.createMarshaller(null)); - - assertExceptionCauseNotNull(actual, "Failed to create JAXB Marshaller for class: null"); - } - - @Test - void createUnmarshaller() { - final Unmarshaller m1 = jaxbTools.createUnmarshaller(UftpParticipant.class); - final Unmarshaller m2 = jaxbTools.createUnmarshaller(SigningDetails.class); - final Unmarshaller m3 = jaxbTools.createUnmarshaller(SigningDetails.class); - - assertThat(m1).isNotNull(); - assertThat(m2).isNotNull(); - assertThat(m3).isNotNull(); - assertThat(m2).isNotSameAs(m1); - assertThat(m3).isNotSameAs(m1); - assertThat(m3).isNotSameAs(m2); - } - - @Test - void createUnmarshallerThrows() { - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> jaxbTools.createUnmarshaller(null)); - - assertExceptionCauseNotNull(actual, "Failed to create JAXB unmarshaller for class: null"); - } - - @Test - void newJAXBResult() { - final JAXBResult m1 = jaxbTools.newJAXBResult(UftpParticipant.class); - final JAXBResult m2 = jaxbTools.newJAXBResult(SigningDetails.class); - final JAXBResult m3 = jaxbTools.newJAXBResult(SigningDetails.class); - - assertThat(m1).isNotNull(); - assertThat(m2).isNotNull(); - assertThat(m3).isNotNull(); - assertThat(m2).isNotSameAs(m1); - assertThat(m3).isNotSameAs(m1); - assertThat(m3).isNotSameAs(m2); - } - - @Test - void newJAXBResultThrowsOnNull() { - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> jaxbTools.newJAXBResult(null)); - - assertExceptionCauseNotNull(actual, "Failed to create JAXB Result for class: null"); - } + @InjectMocks + private JAXBTools jaxbTools; + + @Test + void getContext() { + final JAXBContext ctx1 = jaxbTools.getJAXBContext(JAXBTools.class); + final JAXBContext ctx2 = jaxbTools.getJAXBContext(UftpParticipant.class); + final JAXBContext ctx3 = jaxbTools.getJAXBContext(UftpParticipant.class); + + assertThat(ctx1).isNotNull(); + assertThat(ctx2).isNotNull(); + assertThat(ctx3).isNotNull(); + assertThat(ctx2).isNotSameAs(ctx1); + assertThat(ctx3).isNotSameAs(ctx1); + assertThat(ctx3).isSameAs(ctx2); + } + + @Test + void getContextThrowsOnNull() { + assertThatThrownBy(() -> jaxbTools.getJAXBContext(null)) + .isInstanceOf(UftpConnectorException.class) + .hasMessage("Type to (de)serialize must be specified"); + } + + @Test + void createMarshaller() { + final Marshaller m1 = jaxbTools.createMarshaller(JAXBTools.class); + final Marshaller m2 = jaxbTools.createMarshaller(UftpParticipant.class); + final Marshaller m3 = jaxbTools.createMarshaller(UftpParticipant.class); + + assertThat(m1).isNotNull(); + assertThat(m2).isNotNull(); + assertThat(m3).isNotNull(); + assertThat(m2).isNotSameAs(m1); + assertThat(m3).isNotSameAs(m1); + assertThat(m3).isNotSameAs(m2); + } + + @Test + void createMarshallerThrows() { + assertThatThrownBy(() -> jaxbTools.createMarshaller(null)) + .isInstanceOf(UftpConnectorException.class) + .hasMessage("Failed to create JAXB Marshaller for class: null"); + } + + @Test + void createUnmarshaller() { + final Unmarshaller m1 = jaxbTools.createUnmarshaller(UftpParticipant.class); + final Unmarshaller m2 = jaxbTools.createUnmarshaller(SigningDetails.class); + final Unmarshaller m3 = jaxbTools.createUnmarshaller(SigningDetails.class); + + assertThat(m1).isNotNull(); + assertThat(m2).isNotNull(); + assertThat(m3).isNotNull(); + assertThat(m2).isNotSameAs(m1); + assertThat(m3).isNotSameAs(m1); + assertThat(m3).isNotSameAs(m2); + } + + @Test + void createUnmarshallerThrows() { + assertThatThrownBy(() -> jaxbTools.createUnmarshaller(null)) + .isInstanceOf(UftpConnectorException.class) + .hasMessage("Failed to create JAXB unmarshaller for class: null"); + } + + @Test + void newJAXBResult() { + final JAXBResult m1 = jaxbTools.newJAXBResult(UftpParticipant.class); + final JAXBResult m2 = jaxbTools.newJAXBResult(SigningDetails.class); + final JAXBResult m3 = jaxbTools.newJAXBResult(SigningDetails.class); + + assertThat(m1).isNotNull(); + assertThat(m2).isNotNull(); + assertThat(m3).isNotNull(); + assertThat(m2).isNotSameAs(m1); + assertThat(m3).isNotSameAs(m1); + assertThat(m3).isNotSameAs(m2); + } + + @Test + void newJAXBResultThrowsOnNull() { + assertThatThrownBy(() -> jaxbTools.newJAXBResult(null)) + .isInstanceOf(UftpConnectorException.class) + .hasMessage("Failed to create JAXB Result for class: null"); + } } \ No newline at end of file diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdFactoryTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdFactoryTest.java index 684981c..0af41c4 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdFactoryTest.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdFactoryTest.java @@ -4,14 +4,6 @@ package org.lfenergy.shapeshifter.core.common.xsd; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.lfenergy.shapeshifter.core.UftpTestSupport.assertExceptionCauseNotNull; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import java.io.File; -import java.io.IOException; -import java.net.URL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,52 +12,59 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.io.File; +import java.io.IOException; +import java.net.URL; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verifyNoMoreInteractions; + @ExtendWith(MockitoExtension.class) class XsdFactoryTest { - @Mock - private XsdSchemaFactoryPool factoryPool; + @Mock + private XsdSchemaFactoryPool factoryPool; - @InjectMocks - private XsdFactory testSubject; + @InjectMocks + private XsdFactory testSubject; - @Mock - private IOException ioException; + @Mock + private IOException ioException; - @AfterEach - void noMore() { - verifyNoMoreInteractions(factoryPool, ioException); - } + @AfterEach + void noMore() { + verifyNoMoreInteractions(factoryPool, ioException); + } - @Test - void newXsdSchemaPool() throws Exception { - var url = new URL("file:///test.xsd"); - final XsdSchemaPool v1 = testSubject.newXsdSchemaPool(url); - final XsdSchemaPool v2 = testSubject.newXsdSchemaPool(url); + @Test + void newXsdSchemaPool() throws Exception { + var url = new URL("file:///test.xsd"); + final XsdSchemaPool v1 = testSubject.newXsdSchemaPool(url); + final XsdSchemaPool v2 = testSubject.newXsdSchemaPool(url); - assertThat(v1).isNotNull(); - assertThat(v2).isNotNull(); - assertThat(v2).isNotSameAs(v1); + assertThat(v1).isNotNull(); + assertThat(v2).isNotNull(); + assertThat(v2).isNotSameAs(v1); - assertThat(v1.getXsd()).isEqualTo(url); - assertThat(v1.getFactoryPool()).isSameAs(factoryPool); - } + assertThat(v1.getXsd()).isEqualTo(url); + assertThat(v1.getFactoryPool()).isSameAs(factoryPool); + } - @Test - void fileContentToString() { - final String content = testSubject.contentToString( - new File("src/test/resources/input.txt") - ); - assertThat(content).isEqualTo("BOE"); - } + @Test + void fileContentToString() { + final String content = testSubject.contentToString( + new File("src/test/resources/input.txt") + ); + assertThat(content).isEqualTo("BOE"); + } - @Test - void fileContentToString_throws() { - var file = new File("not exist.file"); - - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> - testSubject.contentToString(file)); + @Test + void fileContentToString_throws() { + var file = new File("not exist.file"); - assertExceptionCauseNotNull(actual, "Failed to read file content from 'not exist.file'."); - } + assertThatThrownBy(() -> testSubject.contentToString(file)) + .isInstanceOf(UftpConnectorException.class) + .hasMessage("Failed to read file content from 'not exist.file'."); + } } diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdSchemaPoolTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdSchemaPoolTest.java index a9eeedb..929ee68 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdSchemaPoolTest.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdSchemaPoolTest.java @@ -4,18 +4,6 @@ package org.lfenergy.shapeshifter.core.common.xsd; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.lfenergy.shapeshifter.core.UftpTestSupport.assertException; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import java.net.URL; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -25,88 +13,99 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import java.net.URL; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + @ExtendWith(MockitoExtension.class) class XsdSchemaPoolTest { - private static final String XXE_ATTACK = "xml/xxe/FlexRequestResponse_with_XXE_Attack.xml"; - private static final String XXE_ATTACK_SSRF = "xml/xxe/FlexRequestResponse_with_XXE_Attack_SSRF.xml"; - - @Mock - private XsdSchemaFactoryPool factoryPool; - @Mock - private SchemaFactory factory; - @Mock - private Schema schema; - - @AfterEach - void noMore() { - verifyNoMoreInteractions( - factoryPool, - factory, - schema - ); - } - - @Test - void construction() throws Exception { - var url = new URL("file:///test.xsd"); - final XsdSchemaPool testSubject = new XsdSchemaPool(url, factoryPool); - - assertThat(testSubject.getXsd()).isEqualTo(url); - assertThat(testSubject.getFactoryPool()).isSameAs(factoryPool); - } - - @Test - void create() throws Exception { - given(factoryPool.claim()).willReturn(factory); - - var url = new URL("file:///test.xsd"); - final XsdSchemaPool testSubject = new XsdSchemaPool(url, factoryPool); - given(factory.newSchema(url)).willReturn(schema); - - assertThat(testSubject.create()).isSameAs(schema); - - verify(factoryPool).release(factory); - } - - @Test - void create_throws() throws Exception { - given(factoryPool.claim()).willReturn(factory); - - var url = new URL("file:///test.xsd"); - final XsdSchemaPool testSubject = new XsdSchemaPool(url, factoryPool); - - var saxException = new SAXException("test"); - given(factory.newSchema(any(URL.class))).willThrow(saxException); - - UftpConnectorException actual = assertThrows(UftpConnectorException.class, testSubject::create); - - assertException(actual, "Creating new schema instance failed for XSD: file:/test.xsd", saxException); - - verify(factoryPool).release(factory); - } - - @Test - void create_violate_xxe_then_fail() { - doTestXXE(XXE_ATTACK, "DOCTYPE is disallowed when the feature \"http://apache.org/xml/features/disallow-doctype-decl\" set to true."); - } - - @Test - void create_violate_xxe_ssrf_then_fail() { - doTestXXE(XXE_ATTACK_SSRF, "DOCTYPE is disallowed when the feature \"http://apache.org/xml/features/disallow-doctype-decl\" set to true."); - } - - private void doTestXXE(String fileName, String errorMessage) { - var xsdSchemaFactoryPool = new XsdSchemaFactoryPool(); - - var url = this.getClass().getClassLoader().getResource(fileName); - final XsdSchemaPool testSubject = new XsdSchemaPool(url, xsdSchemaFactoryPool); - - assertThatThrownBy((() -> - testSubject.create())) - .isInstanceOf(UftpConnectorException.class) - .hasRootCauseInstanceOf(SAXParseException.class) - .rootCause() - .hasMessageContaining(errorMessage); - } + private static final String XXE_ATTACK = "xml/xxe/FlexRequestResponse_with_XXE_Attack.xml"; + private static final String XXE_ATTACK_SSRF = "xml/xxe/FlexRequestResponse_with_XXE_Attack_SSRF.xml"; + + @Mock + private XsdSchemaFactoryPool factoryPool; + @Mock + private SchemaFactory factory; + @Mock + private Schema schema; + + @AfterEach + void noMore() { + verifyNoMoreInteractions( + factoryPool, + factory, + schema + ); + } + + @Test + void construction() throws Exception { + var url = new URL("file:///test.xsd"); + final XsdSchemaPool testSubject = new XsdSchemaPool(url, factoryPool); + + assertThat(testSubject.getXsd()).isEqualTo(url); + assertThat(testSubject.getFactoryPool()).isSameAs(factoryPool); + } + + @Test + void create() throws Exception { + given(factoryPool.claim()).willReturn(factory); + + var url = new URL("file:///test.xsd"); + final XsdSchemaPool testSubject = new XsdSchemaPool(url, factoryPool); + given(factory.newSchema(url)).willReturn(schema); + + assertThat(testSubject.create()).isSameAs(schema); + + verify(factoryPool).release(factory); + } + + @Test + void create_throws() throws Exception { + given(factoryPool.claim()).willReturn(factory); + + var url = new URL("file:///test.xsd"); + final XsdSchemaPool testSubject = new XsdSchemaPool(url, factoryPool); + + var saxException = new SAXException("test"); + given(factory.newSchema(any(URL.class))).willThrow(saxException); + + assertThatThrownBy(testSubject::create) + .isInstanceOf(UftpConnectorException.class) + .hasMessage("Creating new schema instance failed for XSD: file:/test.xsd") + .hasCause(saxException); + + verify(factoryPool).release(factory); + } + + @Test + void create_violate_xxe_then_fail() { + doTestXXE(XXE_ATTACK, "DOCTYPE is disallowed when the feature \"http://apache.org/xml/features/disallow-doctype-decl\" set to true."); + } + + @Test + void create_violate_xxe_ssrf_then_fail() { + doTestXXE(XXE_ATTACK_SSRF, "DOCTYPE is disallowed when the feature \"http://apache.org/xml/features/disallow-doctype-decl\" set to true."); + } + + private void doTestXXE(String fileName, String errorMessage) { + var xsdSchemaFactoryPool = new XsdSchemaFactoryPool(); + + var url = this.getClass().getClassLoader().getResource(fileName); + final XsdSchemaPool testSubject = new XsdSchemaPool(url, xsdSchemaFactoryPool); + + assertThatThrownBy((testSubject::create)) + .isInstanceOf(UftpConnectorException.class) + .hasRootCauseInstanceOf(SAXParseException.class) + .rootCause() + .hasMessageContaining(errorMessage); + } } diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidatorTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidatorTest.java index 9a17bcc..efc202d 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidatorTest.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/common/xsd/XsdValidatorTest.java @@ -4,76 +4,72 @@ package org.lfenergy.shapeshifter.core.common.xsd; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.lfenergy.shapeshifter.core.UftpTestSupport.assertException; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import javax.xml.transform.Source; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import javax.xml.transform.Source; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; +import java.io.File; +import java.io.IOException; +import java.net.URL; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; + @ExtendWith(MockitoExtension.class) class XsdValidatorTest { - @Mock - private XsdSchemaProvider schemaProvider; - @Mock - private File xsdFile; - @Mock - private SchemaFactory schemaFactory; - @Mock - private Schema schema; - @Mock - private Validator validator; - @InjectMocks - private XsdValidator testSubject; - - @AfterEach - void noMore() { - verifyNoMoreInteractions( - schemaProvider, - xsdFile, - schemaFactory, - schema, - validator - ); - } + @Mock + private XsdSchemaProvider schemaProvider; + @Mock + private File xsdFile; + @Mock + private SchemaFactory schemaFactory; + @Mock + private Schema schema; + @Mock + private Validator validator; + @InjectMocks + private XsdValidator testSubject; - @Test - void validateXsd() throws Exception { - var url = new URL("file:///test.xsd"); - given(schemaProvider.getValidator(url)).willReturn(validator); - testSubject.validate("xml", url); + @AfterEach + void noMore() { + verifyNoMoreInteractions( + schemaProvider, + xsdFile, + schemaFactory, + schema, + validator + ); + } - verify(validator).validate(any(Source.class)); - } + @Test + void validateXsd() throws Exception { + var url = new URL("file:///test.xsd"); + given(schemaProvider.getValidator(url)).willReturn(validator); + testSubject.validate("xml", url); - @Test - void validateXsdThrows() throws Exception { - var url = new URL("file:///test.xsd"); - given(schemaProvider.getValidator(url)).willReturn(validator); + verify(validator).validate(any(Source.class)); + } - var ioException = new IOException("test"); - doThrow(ioException).when(validator).validate(any(Source.class)); + @Test + void validateXsdThrows() throws Exception { + var url = new URL("file:///test.xsd"); + given(schemaProvider.getValidator(url)).willReturn(validator); - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> - testSubject.validate("xml", url)); + var ioException = new IOException("test"); + doThrow(ioException).when(validator).validate(any(Source.class)); - assertException(actual, "XSD validation failed: test", ioException, 400); - } + assertThatThrownBy(() -> testSubject.validate("xml", url)) + .isInstanceOf(XsdValidationException.class) + .hasMessage("XSD validation failed: test"); + } } diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoServiceTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoServiceTest.java index c78cb61..ff89a7b 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoServiceTest.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/service/crypto/UftpCryptoServiceTest.java @@ -4,18 +4,9 @@ package org.lfenergy.shapeshifter.core.service.crypto; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.lfenergy.shapeshifter.core.UftpTestSupport.assertException; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - import com.goterl.lazysodium.LazySodiumJava; import com.goterl.lazysodium.exceptions.SodiumException; import com.goterl.lazysodium.utils.Key; -import java.nio.charset.StandardCharsets; -import java.util.Base64; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -28,130 +19,143 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + @ExtendWith(MockitoExtension.class) class UftpCryptoServiceTest { - public static final String PAYLOAD_XML = "PAYLOAD_XML"; - public static final String PRIVATE_KEY = "PRIVATE_KEY"; - public static final byte[] BODY = "BODY".getBytes(StandardCharsets.UTF_8); - public static final String BASE_64_BODY = Base64.getEncoder().encodeToString(BODY); - public static final String SENDER_DOMAIN = "SENDER_DOMAIN"; - public static final USEFRoleType SENDER_ROLE = USEFRoleType.DSO; - private static final String PUBLIC_KEY = "PUBLIC_KEY"; - - @Mock - private ParticipantResolutionService participantService; - @Mock - private LazySodiumFactory factory; - @Mock - private LazySodiumBase64Pool lazySodiumInstancePool; - - @InjectMocks - private UftpCryptoService testSubject; - - @Mock - private LazySodiumJava lazySodium; - @Mock - private UftpParticipant sender; - @Mock - private SodiumException sodiumException; - @Mock - private SignedMessage signedMessage; - @Mock - private Key publicKey; - @Mock - private RuntimeException runtimeException; - - @AfterEach - void noMore() { - verifyNoMoreInteractions( - participantService, - factory, - lazySodiumInstancePool, - lazySodium, - sender, - sodiumException, - signedMessage, - publicKey, - runtimeException - ); - } - - @Test - void signMessage() throws Exception { - given(lazySodiumInstancePool.claim()).willReturn(lazySodium); - given(lazySodium.cryptoSign(PAYLOAD_XML, PRIVATE_KEY)).willReturn(BASE_64_BODY); - given(sender.domain()).willReturn(SENDER_DOMAIN); - given(sender.role()).willReturn(SENDER_ROLE); - - var result = testSubject.signMessage(PAYLOAD_XML, sender, PRIVATE_KEY); - - assertThat(result.getSenderDomain()).isEqualTo(SENDER_DOMAIN); - assertThat(result.getSenderRole()).isEqualTo(SENDER_ROLE); - assertThat(result.getBody()).isEqualTo(BODY); - verify(lazySodiumInstancePool).release(lazySodium); - } - - @Test - void signMessageThrows() throws Exception { - given(lazySodiumInstancePool.claim()).willReturn(lazySodium); - given(lazySodium.cryptoSign(PAYLOAD_XML, PRIVATE_KEY)).willThrow(sodiumException); - - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> - testSubject.signMessage(PAYLOAD_XML, sender, PRIVATE_KEY)); - - assertException(actual, "Failed to sign message.", sodiumException); - verify(lazySodiumInstancePool).release(lazySodium); - } - - @Test - void verifySignedMessage() throws Exception { - given(signedMessage.getSenderDomain()).willReturn(SENDER_DOMAIN); - given(signedMessage.getSenderRole()).willReturn(SENDER_ROLE); - given(participantService.getPublicKey(SENDER_ROLE, SENDER_DOMAIN)).willReturn(PUBLIC_KEY); - given(signedMessage.getBody()).willReturn(BODY); - given(lazySodiumInstancePool.claim()).willReturn(lazySodium); - given(factory.keyFromBase64String(PUBLIC_KEY)).willReturn(publicKey); - given(lazySodium.cryptoSignOpen(BASE_64_BODY, publicKey)).willReturn(PAYLOAD_XML); - - var result = testSubject.verifySignedMessage(signedMessage); - - assertThat(result).isEqualTo(PAYLOAD_XML); - verify(lazySodiumInstancePool).release(lazySodium); - } - - @Test - void verifySignedMessageThrows() { - given(signedMessage.getSenderDomain()).willReturn(SENDER_DOMAIN); - given(signedMessage.getSenderRole()).willReturn(SENDER_ROLE); - given(participantService.getPublicKey(SENDER_ROLE, SENDER_DOMAIN)).willReturn(PUBLIC_KEY); - given(signedMessage.getBody()).willReturn(BODY); - given(lazySodiumInstancePool.claim()).willReturn(lazySodium); - given(factory.keyFromBase64String(PUBLIC_KEY)).willReturn(publicKey); - given(lazySodium.cryptoSignOpen(BASE_64_BODY, publicKey)).willThrow(runtimeException); - - UftpConnectorException actual = assertThrows(UftpConnectorException.class, () -> - testSubject.verifySignedMessage(signedMessage)); - - assertException(actual, "Failed to verify message.", runtimeException, 401); - verify(lazySodiumInstancePool).release(lazySodium); - } - - @Test - void verifySignedMessageReturnsNullWhenMessageNotValidlySignedWithPublicKey() { - given(signedMessage.getSenderDomain()).willReturn(SENDER_DOMAIN); - given(signedMessage.getSenderRole()).willReturn(SENDER_ROLE); - given(participantService.getPublicKey(SENDER_ROLE, SENDER_DOMAIN)).willReturn(PUBLIC_KEY); - given(signedMessage.getBody()).willReturn(BODY); - given(lazySodiumInstancePool.claim()).willReturn(lazySodium); - given(factory.keyFromBase64String(PUBLIC_KEY)).willReturn(publicKey); - given(lazySodium.cryptoSignOpen(BASE_64_BODY, publicKey)).willReturn(null); - - var exception = assertThrows(UftpConnectorException.class, () -> - testSubject.verifySignedMessage(signedMessage)); - - assertThat(exception).isInstanceOf(UftpConnectorException.class); - - verify(lazySodiumInstancePool).release(lazySodium); - } + public static final String PAYLOAD_XML = "PAYLOAD_XML"; + public static final String PRIVATE_KEY = "PRIVATE_KEY"; + public static final byte[] BODY = "BODY".getBytes(StandardCharsets.UTF_8); + public static final String BASE_64_BODY = Base64.getEncoder().encodeToString(BODY); + public static final String SENDER_DOMAIN = "SENDER_DOMAIN"; + public static final USEFRoleType SENDER_ROLE = USEFRoleType.DSO; + private static final String PUBLIC_KEY = "PUBLIC_KEY"; + + @Mock + private ParticipantResolutionService participantService; + @Mock + private LazySodiumFactory factory; + @Mock + private LazySodiumBase64Pool lazySodiumInstancePool; + + @InjectMocks + private UftpCryptoService testSubject; + + @Mock + private LazySodiumJava lazySodium; + @Mock + private UftpParticipant sender; + @Mock + private SodiumException sodiumException; + @Mock + private SignedMessage signedMessage; + @Mock + private Key publicKey; + @Mock + private RuntimeException runtimeException; + + @AfterEach + void noMore() { + verifyNoMoreInteractions( + participantService, + factory, + lazySodiumInstancePool, + lazySodium, + sender, + sodiumException, + signedMessage, + publicKey, + runtimeException + ); + } + + @Test + void signMessage() throws Exception { + given(lazySodiumInstancePool.claim()).willReturn(lazySodium); + given(lazySodium.cryptoSign(PAYLOAD_XML, PRIVATE_KEY)).willReturn(BASE_64_BODY); + given(sender.domain()).willReturn(SENDER_DOMAIN); + given(sender.role()).willReturn(SENDER_ROLE); + + var result = testSubject.signMessage(PAYLOAD_XML, sender, PRIVATE_KEY); + + assertThat(result.getSenderDomain()).isEqualTo(SENDER_DOMAIN); + assertThat(result.getSenderRole()).isEqualTo(SENDER_ROLE); + assertThat(result.getBody()).isEqualTo(BODY); + verify(lazySodiumInstancePool).release(lazySodium); + } + + @Test + void signMessageThrows() throws Exception { + given(lazySodiumInstancePool.claim()).willReturn(lazySodium); + given(lazySodium.cryptoSign(PAYLOAD_XML, PRIVATE_KEY)).willThrow(sodiumException); + + assertThatThrownBy(() -> testSubject.signMessage(PAYLOAD_XML, sender, PRIVATE_KEY)) + .isInstanceOf(UftpConnectorException.class) + .hasMessage("Failed to sign message.") + .hasCause(sodiumException); + + verify(lazySodiumInstancePool).release(lazySodium); + } + + @Test + void verifySignedMessage() throws Exception { + given(signedMessage.getSenderDomain()).willReturn(SENDER_DOMAIN); + given(signedMessage.getSenderRole()).willReturn(SENDER_ROLE); + given(participantService.getPublicKey(SENDER_ROLE, SENDER_DOMAIN)).willReturn(PUBLIC_KEY); + given(signedMessage.getBody()).willReturn(BODY); + given(lazySodiumInstancePool.claim()).willReturn(lazySodium); + given(factory.keyFromBase64String(PUBLIC_KEY)).willReturn(publicKey); + given(lazySodium.cryptoSignOpen(BASE_64_BODY, publicKey)).willReturn(PAYLOAD_XML); + + var result = testSubject.verifySignedMessage(signedMessage); + + assertThat(result).isEqualTo(PAYLOAD_XML); + verify(lazySodiumInstancePool).release(lazySodium); + } + + @Test + void verifySignedMessageThrows() { + given(signedMessage.getSenderDomain()).willReturn(SENDER_DOMAIN); + given(signedMessage.getSenderRole()).willReturn(SENDER_ROLE); + given(participantService.getPublicKey(SENDER_ROLE, SENDER_DOMAIN)).willReturn(PUBLIC_KEY); + given(signedMessage.getBody()).willReturn(BODY); + given(lazySodiumInstancePool.claim()).willReturn(lazySodium); + given(factory.keyFromBase64String(PUBLIC_KEY)).willReturn(publicKey); + given(lazySodium.cryptoSignOpen(BASE_64_BODY, publicKey)).willThrow(runtimeException); + + assertThatThrownBy(() -> + testSubject.verifySignedMessage(signedMessage)) + .isInstanceOf(UftpCryptoException.class) + .hasMessage("Failed to verify message.") + .hasCause(runtimeException); + + verify(lazySodiumInstancePool).release(lazySodium); + } + + @Test + void verifySignedMessageReturnsNullWhenMessageNotValidlySignedWithPublicKey() { + given(signedMessage.getSenderDomain()).willReturn(SENDER_DOMAIN); + given(signedMessage.getSenderRole()).willReturn(SENDER_ROLE); + given(participantService.getPublicKey(SENDER_ROLE, SENDER_DOMAIN)).willReturn(PUBLIC_KEY); + given(signedMessage.getBody()).willReturn(BODY); + given(lazySodiumInstancePool.claim()).willReturn(lazySodium); + given(factory.keyFromBase64String(PUBLIC_KEY)).willReturn(publicKey); + given(lazySodium.cryptoSignOpen(BASE_64_BODY, publicKey)).willReturn(null); + + var exception = assertThrows(UftpConnectorException.class, () -> + testSubject.verifySignedMessage(signedMessage)); + + assertThat(exception).isInstanceOf(UftpConnectorException.class); + + verify(lazySodiumInstancePool).release(lazySodium); + } } \ No newline at end of file diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageServiceTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageServiceTest.java index 914721f..0ba9451 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageServiceTest.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/service/sending/UftpSendMessageServiceTest.java @@ -4,30 +4,18 @@ package org.lfenergy.shapeshifter.core.service.sending; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.*; - import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import net.datafaker.Faker; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.lfenergy.shapeshifter.api.FlexRequest; import org.lfenergy.shapeshifter.api.FlexRequestResponse; import org.lfenergy.shapeshifter.api.SignedMessage; import org.lfenergy.shapeshifter.api.USEFRoleType; import org.lfenergy.shapeshifter.api.model.UftpParticipantInformation; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; import org.lfenergy.shapeshifter.core.model.SigningDetails; import org.lfenergy.shapeshifter.core.model.UftpParticipant; import org.lfenergy.shapeshifter.core.service.ParticipantAuthorizationProvider; @@ -42,6 +30,13 @@ import java.util.Locale; +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; + @ExtendWith(MockitoExtension.class) class UftpSendMessageServiceTest { @@ -176,14 +171,14 @@ void attemptToSendMessage_204_No_Content() { } @ParameterizedTest - @EnumSource(value = HttpStatusCode.class, names = {"TEMPORARY_REDIRECT", "PERMANENT_REDIRECT"}) - void attemptToSendMessage_3xx_followRedirect(HttpStatusCode statusCode) { + @ValueSource(ints={307,308}) + void attemptToSendMessage_3xx_followRedirect(int statusCode) { mockSerialisation(); mockSending(); stubFor(post(urlPathMatching(PATH_3XX + ".*")) .willReturn(aResponse() - .withStatus(statusCode.getValue()) + .withStatus(statusCode) .withHeader("Location", getEndpointURL(PATH_HAPPY_FLOW)))); mockParticipantServiceWithoutAuthorization(getEndpointURL(PATH_3XX)); @@ -196,14 +191,14 @@ void attemptToSendMessage_3xx_followRedirect(HttpStatusCode statusCode) { } @ParameterizedTest - @EnumSource(value = HttpStatusCode.class, names = {"TEMPORARY_REDIRECT", "PERMANENT_REDIRECT"}) - void attemptToSendMessage_3xx_followRedirect_thenError(HttpStatusCode statusCode) { + @ValueSource(ints={307,308}) + void attemptToSendMessage_3xx_followRedirect_thenError(int statusCode) { mockSerialisation(); mockSending(); stubFor(post(urlPathMatching(PATH_3XX + ".*")) .willReturn(aResponse() - .withStatus(statusCode.getValue()) + .withStatus(statusCode) .withHeader("Location", getEndpointURL(PATH_BAD_REQUEST)))); mockParticipantServiceWithoutAuthorization(getEndpointURL(PATH_3XX)); @@ -218,18 +213,18 @@ void attemptToSendMessage_3xx_followRedirect_thenError(HttpStatusCode statusCode assertThat(actual) .isInstanceOf(UftpClientErrorException.class) .hasMessage("Client error 400 received while sending UFTP message to " + getEndpointURL(PATH_BAD_REQUEST) + ": Bad Request"); - assertThat(actual.getHttpStatusCode()).isEqualTo(HttpStatusCode.BAD_REQUEST); + assertThat(actual.getHttpStatusCode()).contains(400); } @ParameterizedTest - @EnumSource(value = HttpStatusCode.class, names = {"TEMPORARY_REDIRECT", "PERMANENT_REDIRECT"}) - void attemptToSendMessage_3xx_followRedirect_locationHeaderMissing(HttpStatusCode statusCode) { + @ValueSource(ints={307,308}) + void attemptToSendMessage_3xx_followRedirect_locationHeaderMissing(int statusCode) { mockSerialisation(); mockSending(); stubFor(post(urlPathMatching(PATH_3XX + ".*")) .willReturn(aResponse() - .withStatus(statusCode.getValue()))); + .withStatus(statusCode))); mockParticipantServiceWithoutAuthorization(getEndpointURL(PATH_3XX)); @@ -241,18 +236,18 @@ void attemptToSendMessage_3xx_followRedirect_locationHeaderMissing(HttpStatusCod assertThat(actual) .isInstanceOf(UftpServerErrorException.class) .hasMessage("Redirect received without Location header while sending UFTP message to " + getEndpointURL(PATH_3XX)); - assertThat(actual.getHttpStatusCode()).isEqualTo(statusCode); + assertThat(actual.getHttpStatusCode()).contains(statusCode); } @ParameterizedTest - @EnumSource(value = HttpStatusCode.class, names = {"TEMPORARY_REDIRECT", "PERMANENT_REDIRECT"}) - void attemptToSendMessage_3xx_followRedirect_tooManyRedirects(HttpStatusCode statusCode) { + @ValueSource(ints={307,308}) + void attemptToSendMessage_3xx_followRedirect_tooManyRedirects(int statusCode) { mockSerialisation(); mockSending(); stubFor(post(urlPathMatching(PATH_3XX + ".*")) .willReturn(aResponse() - .withStatus(statusCode.getValue()) + .withStatus(statusCode) .withHeader("Location", getEndpointURL(PATH_3XX)))); var endpoint = getEndpointURL(PATH_3XX); @@ -272,14 +267,14 @@ void attemptToSendMessage_3xx_followRedirect_tooManyRedirects(HttpStatusCode sta } @ParameterizedTest - @EnumSource(value = HttpStatusCode.class, names = {"MOVED_PERMANENTLY", "FOUND", "SEE_OTHER", "MULTIPLE_CHOICES", "USE_PROXY", "NOT_MODIFIED"}) - void attemptToSendMessage_3xx_doNotFollowRedirect(HttpStatusCode statusCode) { + @ValueSource(ints={300,301,302,303,304,305}) + void attemptToSendMessage_3xx_doNotFollowRedirect(int statusCode) { mockSerialisation(); mockSending(); stubFor(post(urlPathMatching(PATH_3XX + ".*")) .willReturn(aResponse() - .withStatus(statusCode.getValue()) + .withStatus(statusCode) .withHeader("Location", getEndpointURL(PATH_HAPPY_FLOW)))); var endpoint = getEndpointURL(PATH_3XX); @@ -292,8 +287,8 @@ void attemptToSendMessage_3xx_doNotFollowRedirect(HttpStatusCode statusCode) { assertThat(actual) .isInstanceOf(UftpSendException.class) - .hasMessageContaining("Unexpected response status " + statusCode.getValue() + " received while sending UFTP message to " + endpoint); - assertThat(actual.getHttpStatusCode()).isEqualTo(statusCode); + .hasMessageContaining("Unexpected response status " + statusCode + " received while sending UFTP message to " + endpoint); + assertThat(actual.getHttpStatusCode()).contains(statusCode); } @Test @@ -302,7 +297,6 @@ void attemptToSendMessage_internalServerError() { mockSending(); var endpoint = getEndpointURL(PATH_INTERNAL_SERVER_ERROR); mockParticipantServiceWithoutAuthorization(endpoint); - var httpStatusCode = HttpStatusCode.INTERNAL_SERVER_ERROR; var actual = assertThrows(UftpSendException.class, () -> testSubject.attemptToSendMessage(flexRequest, details)); @@ -312,7 +306,7 @@ void attemptToSendMessage_internalServerError() { assertThat(actual) .isInstanceOf(UftpSendException.class) .hasMessage("Server error 500 received while sending UFTP message to " + endpoint + ": Internal Server Error"); - assertThat(actual.getHttpStatusCode()).isEqualTo(httpStatusCode); + assertThat(actual.getHttpStatusCode()).contains(500); } @Test @@ -322,8 +316,6 @@ void attemptToSendMessage_ResponseOnBadRequest() { var endpoint = getEndpointURL(PATH_BAD_REQUEST); mockParticipantServiceWithoutAuthorization(endpoint); - var httpStatusCode = HttpStatusCode.BAD_REQUEST; - var actual = assertThrows(UftpClientErrorException.class, () -> testSubject.attemptToSendMessage(flexRequest, details)); @@ -332,7 +324,7 @@ void attemptToSendMessage_ResponseOnBadRequest() { assertThat(actual) .isInstanceOf(UftpClientErrorException.class) .hasMessage("Client error 400 received while sending UFTP message to " + endpoint + ": Bad Request"); - assertThat(actual.getHttpStatusCode()).isEqualTo(httpStatusCode); + assertThat(actual.getHttpStatusCode()).contains(400); } @Test @@ -363,7 +355,7 @@ void attemptToSendMessage_MalformedUrl() { assertThat(actual) .isInstanceOf(UftpSendException.class) .hasMessage("Could not send UFTP message; invalid endpoint: unsupported URI " + endpoint); - assertThat(actual.getHttpStatusCode()).isEqualTo(HttpStatusCode.INTERNAL_SERVER_ERROR); + assertThat(actual.getHttpStatusCode()).isEmpty(); } @Test @@ -372,7 +364,6 @@ void attemptToSendMessage_connectFailed() { mockSending(); var endpoint = "http://localhost:1"; // something that will trigger a java.net.ConnectException mockParticipantServiceWithoutAuthorization(endpoint); - var httpStatusCode = HttpStatusCode.INTERNAL_SERVER_ERROR; var actual = assertThrows(UftpSendException.class, () -> testSubject.attemptToSendMessage(flexRequest, details)); @@ -382,7 +373,7 @@ void attemptToSendMessage_connectFailed() { assertThat(actual) .isInstanceOf(UftpSendException.class) .hasMessage("Unexpected I/O exception while sending UFTP message to " + endpoint + ": ConnectException: null"); - assertThat(actual.getHttpStatusCode()).isEqualTo(httpStatusCode); + assertThat(actual.getHttpStatusCode()).isEmpty(); } @Test diff --git a/core/src/test/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerTest.java b/core/src/test/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerTest.java index f0d7368..fc871f9 100644 --- a/core/src/test/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerTest.java +++ b/core/src/test/java/org/lfenergy/shapeshifter/core/service/serialization/UftpSerializerTest.java @@ -4,14 +4,6 @@ package org.lfenergy.shapeshifter.core.service.serialization; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.lfenergy.shapeshifter.core.UftpTestSupport.assertException; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -19,102 +11,110 @@ import org.lfenergy.shapeshifter.api.PayloadMessageType; import org.lfenergy.shapeshifter.api.SignedMessage; import org.lfenergy.shapeshifter.api.xsdinfo.UftpXsds; -import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; import org.lfenergy.shapeshifter.core.common.xml.XmlSerializer; import org.lfenergy.shapeshifter.core.common.xsd.XsdValidator; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + @ExtendWith(MockitoExtension.class) class UftpSerializerTest { - private static final String SIGNED_XML = "SIGNED_XML"; - private static final String FLEX_REQUEST_XML = ""; + private static final String SIGNED_XML = "SIGNED_XML"; + private static final String FLEX_REQUEST_XML = ""; - @Mock - private XmlSerializer serializer; - @Mock - private XsdValidator xsdValidator; - @InjectMocks - private UftpSerializer testSubject; + @Mock + private XmlSerializer serializer; + @Mock + private XsdValidator xsdValidator; + @InjectMocks + private UftpSerializer testSubject; - @Mock - private SignedMessage signedMessage; - @Mock - private FlexRequest flexRequest; - @Mock - private IOException ioException; + @Mock + private SignedMessage signedMessage; + @Mock + private FlexRequest flexRequest; + @Mock + private IOException ioException; - @AfterEach - void noMore() { - verifyNoMoreInteractions( - serializer, - xsdValidator, - signedMessage, - flexRequest, - ioException - ); - } + @AfterEach + void noMore() { + verifyNoMoreInteractions( + serializer, + xsdValidator, + signedMessage, + flexRequest, + ioException + ); + } - @Test - void fromSignedXml() { - given(serializer.fromXml(SIGNED_XML, SignedMessage.class)).willReturn(signedMessage); + @Test + void fromSignedXml() { + given(serializer.fromXml(SIGNED_XML, SignedMessage.class)).willReturn(signedMessage); - assertThat(testSubject.fromSignedXml(SIGNED_XML)).isEqualTo(signedMessage); + assertThat(testSubject.fromSignedXml(SIGNED_XML)).isEqualTo(signedMessage); - verify(xsdValidator).validate(SIGNED_XML, UftpXsds.COMMON.getUrl()); - } + verify(xsdValidator).validate(SIGNED_XML, UftpXsds.COMMON.getUrl()); + } - @Test - void fromSignedXml_throws() { - var exception = new RuntimeException("test"); - given(serializer.fromXml(SIGNED_XML, SignedMessage.class)).willThrow(exception); + @Test + void fromSignedXml_throws() { + var exception = new RuntimeException("test"); + given(serializer.fromXml(SIGNED_XML, SignedMessage.class)).willThrow(exception); - UftpConnectorException thrown = assertThrows(UftpConnectorException.class, () -> - testSubject.fromSignedXml(SIGNED_XML)); + assertThatThrownBy(() -> testSubject.fromSignedXml(SIGNED_XML)) + .isInstanceOf(UftpSerializerException.class) + .hasMessage("SignedMessage XML deserialization failed: test"); - assertException(thrown, "SignedMessage XML deserialization failed: test", exception, 400); - verify(xsdValidator).validate(SIGNED_XML, UftpXsds.COMMON.getUrl()); - } + verify(xsdValidator).validate(SIGNED_XML, UftpXsds.COMMON.getUrl()); + } - @Test - void fromPayloadXml() { - given(serializer.fromXml(FLEX_REQUEST_XML, PayloadMessageType.class)).willReturn(flexRequest); + @Test + void fromPayloadXml() { + given(serializer.fromXml(FLEX_REQUEST_XML, PayloadMessageType.class)).willReturn(flexRequest); - assertThat(testSubject.fromPayloadXml(FLEX_REQUEST_XML)).isEqualTo(flexRequest); + assertThat(testSubject.fromPayloadXml(FLEX_REQUEST_XML)).isEqualTo(flexRequest); - verify(xsdValidator).validate(FLEX_REQUEST_XML, UftpXsds.ALL.getUrl()); - } + verify(xsdValidator).validate(FLEX_REQUEST_XML, UftpXsds.ALL.getUrl()); + } - @Test - void fromPayloadXml_throws() { - var exception = new RuntimeException("test"); - given(serializer.fromXml(FLEX_REQUEST_XML, PayloadMessageType.class)).willThrow(exception); + @Test + void fromPayloadXml_throws() { + var exception = new RuntimeException("test"); + given(serializer.fromXml(FLEX_REQUEST_XML, PayloadMessageType.class)).willThrow(exception); - UftpConnectorException thrown = assertThrows(UftpConnectorException.class, () -> - testSubject.fromPayloadXml(FLEX_REQUEST_XML)); + assertThatThrownBy(() -> + testSubject.fromPayloadXml(FLEX_REQUEST_XML)) + .isInstanceOf(UftpSerializerException.class) + .hasMessage("Payload message XML deserialization failed: test"); - assertException(thrown, "Payload message XML deserialization failed: test", exception, 400); - verify(xsdValidator).validate(FLEX_REQUEST_XML, UftpXsds.ALL.getUrl()); - } + verify(xsdValidator).validate(FLEX_REQUEST_XML, UftpXsds.ALL.getUrl()); + } - @Test - void signedMessageToXml() { - given(serializer.toXml(signedMessage)).willReturn(SIGNED_XML); + @Test + void signedMessageToXml() { + given(serializer.toXml(signedMessage)).willReturn(SIGNED_XML); - assertThat(testSubject.toXml(signedMessage)).isEqualTo(SIGNED_XML); + assertThat(testSubject.toXml(signedMessage)).isEqualTo(SIGNED_XML); - verify(xsdValidator).validate(SIGNED_XML, UftpXsds.COMMON.getUrl()); - } + verify(xsdValidator).validate(SIGNED_XML, UftpXsds.COMMON.getUrl()); + } - @Test - void payloadMessageToXml() { - given(serializer.toXml(flexRequest)).willReturn(FLEX_REQUEST_XML); + @Test + void payloadMessageToXml() { + given(serializer.toXml(flexRequest)).willReturn(FLEX_REQUEST_XML); - assertThat(testSubject.toXml(flexRequest)).isEqualTo(FLEX_REQUEST_XML); + assertThat(testSubject.toXml(flexRequest)).isEqualTo(FLEX_REQUEST_XML); - verify(xsdValidator).validate(FLEX_REQUEST_XML, UftpXsds.ALL.getUrl()); - } + verify(xsdValidator).validate(FLEX_REQUEST_XML, UftpXsds.ALL.getUrl()); + } } diff --git a/spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpNotImplementedException.java b/spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpNotImplementedException.java new file mode 100644 index 0000000..434c86b --- /dev/null +++ b/spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpNotImplementedException.java @@ -0,0 +1,11 @@ +package org.lfenergy.shapeshifter.spring.service.handler; + +import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; + +public class UftpNotImplementedException extends UftpConnectorException { + + public UftpNotImplementedException(String message) { + super(message); + } + +} diff --git a/spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpPayloadDispatcher.java b/spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpPayloadDispatcher.java index 4554b12..6fdaf19 100644 --- a/spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpPayloadDispatcher.java +++ b/spring/src/main/java/org/lfenergy/shapeshifter/spring/service/handler/UftpPayloadDispatcher.java @@ -6,8 +6,6 @@ import lombok.extern.apachecommons.CommonsLog; import org.lfenergy.shapeshifter.api.PayloadMessageType; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; -import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; import org.lfenergy.shapeshifter.core.model.IncomingUftpMessage; import org.lfenergy.shapeshifter.core.model.OutgoingUftpMessage; import org.lfenergy.shapeshifter.core.service.handler.UftpPayloadHandler; @@ -54,7 +52,7 @@ public void notifyNewIncomingMessage(IncomingUftpMessage postUftpMessage( processor.onReceivedMessage(IncomingUftpMessage.create(new UftpParticipant(signedMessage), payloadMessage, transportXml, payloadXml)); return ResponseEntity.ok(null); + } catch (XsdValidationException e) { + return handleException(transportXml, e, HttpStatus.BAD_REQUEST); + } catch (UftpVerifyException e) { + return handleException(transportXml, e, HttpStatus.UNAUTHORIZED); } catch (DuplicateMessageException e) { return ResponseEntity.badRequest().body("Duplicate message"); - } catch (UftpConnectorException cause) { - return handleException(transportXml, cause); } catch (Exception cause) { - return handleException(transportXml, new UftpReceiveException(cause.getMessage(), cause)); + return handleException(transportXml, new UftpReceiveException(cause.getMessage(), cause), HttpStatus.INTERNAL_SERVER_ERROR); } } - private ResponseEntity handleException(String transportXml, UftpConnectorException cause) { + private ResponseEntity handleException(String transportXml, UftpConnectorException cause, HttpStatusCode httpStatusCode) { String error = "Failed to process received UFTP message. Error: " + cause.getMessage(); errorProcessor.onErrorDuringReceivedMessageReading(transportXml, cause); - return ResponseEntity.status(cause.getHttpStatusCode().getValue()).body(error); + return ResponseEntity.status(httpStatusCode).body(error); } } \ No newline at end of file diff --git a/spring/src/test/java/org/lfenergy/shapeshifter/spring/service/receiving/UftpInternalControllerTest.java b/spring/src/test/java/org/lfenergy/shapeshifter/spring/service/receiving/UftpInternalControllerTest.java index b61b1c1..3d261c6 100644 --- a/spring/src/test/java/org/lfenergy/shapeshifter/spring/service/receiving/UftpInternalControllerTest.java +++ b/spring/src/test/java/org/lfenergy/shapeshifter/spring/service/receiving/UftpInternalControllerTest.java @@ -16,11 +16,12 @@ import org.lfenergy.shapeshifter.api.PayloadMessageType; import org.lfenergy.shapeshifter.api.SignedMessage; import org.lfenergy.shapeshifter.api.USEFRoleType; -import org.lfenergy.shapeshifter.core.common.HttpStatusCode; import org.lfenergy.shapeshifter.core.common.exception.UftpConnectorException; +import org.lfenergy.shapeshifter.core.common.xsd.XsdValidationException; import org.lfenergy.shapeshifter.core.model.IncomingUftpMessage; import org.lfenergy.shapeshifter.core.service.UftpErrorProcessor; import org.lfenergy.shapeshifter.core.service.crypto.UftpCryptoService; +import org.lfenergy.shapeshifter.core.service.crypto.UftpVerifyException; import org.lfenergy.shapeshifter.core.service.receiving.ReceivedMessageProcessor; import org.lfenergy.shapeshifter.core.service.serialization.UftpSerializer; import org.mockito.ArgumentCaptor; @@ -54,10 +55,6 @@ class UftpInternalControllerTest { private SignedMessage signedMessage; @Mock private PayloadMessageType payloadMessage; - @Mock - private UftpConnectorException uftpException; - @Mock - private RuntimeException runtimeException; @Captor private ArgumentCaptor uftpExceptionCaptor; @Captor @@ -71,29 +68,62 @@ void noMore() { processor, errorProcessor, signedMessage, - payloadMessage, - uftpException, - runtimeException + payloadMessage ); } + @Test + void receiveUftpMessageXsdValidationException() { + var uftpException = new XsdValidationException(ERROR_MESSAGE); + given(deserializer.fromSignedXml(TRANSPORT_XML)).willThrow(uftpException); + + var result = testSubject.postUftpMessage(TRANSPORT_XML); + + assertThat(result.getStatusCode().value()).isEqualTo(400); + assertThat(result.getBody()).isEqualTo("Failed to process received UFTP message. Error: ERROR_MESSAGE"); + verify(errorProcessor).onErrorDuringReceivedMessageReading(TRANSPORT_XML, uftpException); + } + + @Test + void receiveUftpMessageUftpVerifyException() { + var uftpException = new UftpVerifyException(ERROR_MESSAGE); + given(deserializer.fromSignedXml(TRANSPORT_XML)).willThrow(uftpException); + + var result = testSubject.postUftpMessage(TRANSPORT_XML); + + assertThat(result.getStatusCode().value()).isEqualTo(401); + assertThat(result.getBody()).isEqualTo("Failed to process received UFTP message. Error: ERROR_MESSAGE"); + verify(errorProcessor).onErrorDuringReceivedMessageReading(TRANSPORT_XML, uftpException); + } + + @Test + void receiveUftpMessageUftpNotImplementedException() { + var uftpException = new UftpVerifyException(ERROR_MESSAGE); + given(deserializer.fromSignedXml(TRANSPORT_XML)).willThrow(uftpException); + + var result = testSubject.postUftpMessage(TRANSPORT_XML); + + assertThat(result.getStatusCode().value()).isEqualTo(501); + assertThat(result.getBody()).isEqualTo("Failed to process received UFTP message. Error: ERROR_MESSAGE"); + verify(errorProcessor).onErrorDuringReceivedMessageReading(TRANSPORT_XML, uftpException); + } + @Test void receiveUftpMessageUftpConnectorException() { + var uftpException = new UftpConnectorException(ERROR_MESSAGE); given(deserializer.fromSignedXml(TRANSPORT_XML)).willThrow(uftpException); - given(uftpException.getMessage()).willReturn(ERROR_MESSAGE); - given(uftpException.getHttpStatusCode()).willReturn(HttpStatusCode.CONFLICT); var result = testSubject.postUftpMessage(TRANSPORT_XML); - assertThat(result.getStatusCode().value()).isEqualTo(409); + assertThat(result.getStatusCode().value()).isEqualTo(500); assertThat(result.getBody()).isEqualTo("Failed to process received UFTP message. Error: ERROR_MESSAGE"); verify(errorProcessor).onErrorDuringReceivedMessageReading(TRANSPORT_XML, uftpException); } @Test void receiveUftpMessageOtherException() { - given(deserializer.fromSignedXml(TRANSPORT_XML)).willThrow(runtimeException); - given(runtimeException.getMessage()).willReturn(ERROR_MESSAGE); + var exception = new RuntimeException(ERROR_MESSAGE); + given(deserializer.fromSignedXml(TRANSPORT_XML)).willThrow(exception); var result = testSubject.postUftpMessage(TRANSPORT_XML); @@ -102,10 +132,7 @@ void receiveUftpMessageOtherException() { verify(errorProcessor).onErrorDuringReceivedMessageReading(eq(TRANSPORT_XML), uftpExceptionCaptor.capture()); assertThat(uftpExceptionCaptor.getAllValues()).hasSize(1); - assertThat(uftpExceptionCaptor.getValue()) - .hasMessage(ERROR_MESSAGE) - .hasCause(runtimeException) - .satisfies(exception -> assertThat(exception.getHttpStatusCode()).isEqualTo(HttpStatusCode.INTERNAL_SERVER_ERROR)); + assertThat(uftpExceptionCaptor.getValue()).isSameAs(exception); } @Test