From c1a1a5130a4ecf755da72941ad3525beb919447f Mon Sep 17 00:00:00 2001 From: Christof Rabensteiner Date: Mon, 8 Jul 2019 18:02:37 +0200 Subject: Implement Zuse2App Services - Add zuse2app.wsdl contract. - Add MsgResponse as an type-agnostic view for DeliveryRequestStatus and DeliveryNotification messages. Reason: Both DeliveryNotification and DeliveryRequestStatus messages have similar fields and need to be treated similarly (e.g.: receive from msg service, store to repository, verify signature, store to file...). In order to prevent duplicated code, the wrapper interface provides a type-agnostic view onto these messages for depending components to operate on. - Add MsgResponseHandler interface; decides how to process MsgResponse. Also implement this handler with a multi-threaded single-node implementation. - Add MsgResponseSink interface; decides how to archive MsgResponse. - Implement and test SafeResponseToFileSink. Change Identifier for MsgResponses: - Before, DeliveryRequestStatus and DeliveryNotifications had their own repositories. Now, both types are stored in the same repository (the MsgResponse repository) to streamline the handling of MsgResponses. We need to change the identification of MsgReponses, otherwise the identifiers (AppDeliveryID) clash. - MsgResponses are not identified by: + - Rewrite StoreSOAPInterceptor to accommodate fact that, both DeliveryRequestStatus and DeliveryNotification messages have different IDs upon storage / retrieval. Restructure packages and components as follows: - client: All components that are involved when consuming a web service. - process: "fabric" of MoaZS; contains business logic that orchestrates back-end tasks of MoaZS's operational services, e.g.: by processing a delivery request. - service: Implementation of MoaZS's front-end services. Refactoring: - MoaZSException: Remove unused fields. Before: Store mzsrequest, tnvzresult, msgrequest and msgresult as members. Now: Only keep the fields that are needed later, e.g for generating a msg:DeliveryRequestStatus element. Add copy constructor to Builder. - Put storage of byte[] into a dedicated "BinaryRepository". Reason: This was useful in a former design. Now it's not really needed anymore. - Put "create Endpoint" code into EndpointFactory. Reason: Eliminate duplicated code when configuring a service. Testing: - Activate Stacktraces in surefire. --- pom.xml | 6 + src/main/java/at/gv/egiz/moazs/MoaZSException.java | 99 ++++++--- .../java/at/gv/egiz/moazs/client/MzsClient.java | 13 ++ .../java/at/gv/egiz/moazs/client/TnvzHelper.java | 233 +++++++++++++++++++++ .../at/gv/egiz/moazs/config/MzsServiceConfig.java | 30 --- .../at/gv/egiz/moazs/config/PreprocessConfig.java | 2 +- .../at/gv/egiz/moazs/config/RepositoryConfig.java | 32 +++ .../at/gv/egiz/moazs/config/ServicesConfig.java | 46 ++++ .../gv/egiz/moazs/pipeline/DeliveryPipeline.java | 17 -- .../pipeline/SingleThreadedDeliveryPipeline.java | 107 +++------- .../moazs/preprocess/ConfigProfileGenerator.java | 1 - .../moazs/preprocess/DeliveryRequestAugmenter.java | 1 - .../preprocess/MzsDeliveryRequestValidator.java | 74 +++++++ .../at/gv/egiz/moazs/process/DeliveryPipeline.java | 17 ++ .../gv/egiz/moazs/process/MsgResponseHandler.java | 7 + .../at/gv/egiz/moazs/process/MsgResponseSink.java | 11 + .../egiz/moazs/process/SafeResponseToFileSink.java | 84 ++++++++ .../moazs/process/SingleNodeResponseHandler.java | 26 +++ .../egiz/moazs/repository/DeliveryRepository.java | 10 +- .../repository/InMemoryDeliveryRepository.java | 37 +--- .../moazs/repository/RedisDeliveryRepository.java | 16 +- .../java/at/gv/egiz/moazs/scheme/MsgResponse.java | 15 ++ .../java/at/gv/egiz/moazs/scheme/MzsClient.java | 13 -- .../moazs/scheme/MzsDeliveryRequestValidator.java | 74 ------- .../java/at/gv/egiz/moazs/scheme/MzsService.java | 104 --------- .../java/at/gv/egiz/moazs/scheme/NameSpace.java | 9 +- .../gv/egiz/moazs/scheme/NotificationResponse.java | 67 ++++++ .../egiz/moazs/scheme/RequestStatusResponse.java | 87 ++++++++ .../java/at/gv/egiz/moazs/scheme/TnvzHelper.java | 232 -------------------- .../java/at/gv/egiz/moazs/service/MsgService.java | 74 +++++++ .../java/at/gv/egiz/moazs/service/MzsService.java | 112 ++++++++++ .../java/at/gv/egiz/moazs/util/ClientFactory.java | 4 +- .../at/gv/egiz/moazs/util/EndpointFactory.java | 41 ++++ .../at/gv/egiz/moazs/util/SSLContextCreator.java | 2 +- ...StoreSOAPBodyBinaryInRepositoryInterceptor.java | 38 ++-- .../gv/egiz/moazs/verify/MsgResponseVerifier.java | 59 ++++++ src/main/resources/application.yaml | 4 + src/main/resources/zusemsg/zuse2app_p2.wsdl | 81 +++++++ .../gv/egiz/moazs/ConfigProfileGeneratorTest.java | 2 +- .../egiz/moazs/DeliveryRequestAugmenterTest.java | 2 +- .../java/at/gv/egiz/moazs/ITMsgClientTest.java | 2 +- .../java/at/gv/egiz/moazs/ITMzsServiceTest.java | 5 +- .../gv/egiz/moazs/SafeResponseToFileSinkTest.java | 113 ++++++++++ .../moazs/SingleThreadedDeliveryPipelineTest.java | 78 ++++--- src/test/java/at/gv/egiz/moazs/TnvzHelperTest.java | 2 +- 45 files changed, 1413 insertions(+), 676 deletions(-) create mode 100644 src/main/java/at/gv/egiz/moazs/client/MzsClient.java create mode 100644 src/main/java/at/gv/egiz/moazs/client/TnvzHelper.java delete mode 100644 src/main/java/at/gv/egiz/moazs/config/MzsServiceConfig.java create mode 100644 src/main/java/at/gv/egiz/moazs/config/RepositoryConfig.java create mode 100644 src/main/java/at/gv/egiz/moazs/config/ServicesConfig.java delete mode 100644 src/main/java/at/gv/egiz/moazs/pipeline/DeliveryPipeline.java create mode 100644 src/main/java/at/gv/egiz/moazs/preprocess/MzsDeliveryRequestValidator.java create mode 100644 src/main/java/at/gv/egiz/moazs/process/DeliveryPipeline.java create mode 100644 src/main/java/at/gv/egiz/moazs/process/MsgResponseHandler.java create mode 100644 src/main/java/at/gv/egiz/moazs/process/MsgResponseSink.java create mode 100644 src/main/java/at/gv/egiz/moazs/process/SafeResponseToFileSink.java create mode 100644 src/main/java/at/gv/egiz/moazs/process/SingleNodeResponseHandler.java create mode 100644 src/main/java/at/gv/egiz/moazs/scheme/MsgResponse.java delete mode 100644 src/main/java/at/gv/egiz/moazs/scheme/MzsClient.java delete mode 100644 src/main/java/at/gv/egiz/moazs/scheme/MzsDeliveryRequestValidator.java delete mode 100644 src/main/java/at/gv/egiz/moazs/scheme/MzsService.java create mode 100644 src/main/java/at/gv/egiz/moazs/scheme/NotificationResponse.java create mode 100644 src/main/java/at/gv/egiz/moazs/scheme/RequestStatusResponse.java delete mode 100644 src/main/java/at/gv/egiz/moazs/scheme/TnvzHelper.java create mode 100644 src/main/java/at/gv/egiz/moazs/service/MsgService.java create mode 100644 src/main/java/at/gv/egiz/moazs/service/MzsService.java create mode 100644 src/main/java/at/gv/egiz/moazs/util/EndpointFactory.java create mode 100644 src/main/java/at/gv/egiz/moazs/verify/MsgResponseVerifier.java create mode 100644 src/main/resources/zusemsg/zuse2app_p2.wsdl create mode 100644 src/test/java/at/gv/egiz/moazs/SafeResponseToFileSinkTest.java diff --git a/pom.xml b/pom.xml index bd135fc..5ad5d11 100644 --- a/pom.xml +++ b/pom.xml @@ -196,6 +196,10 @@ ${project.basedir}/src/main/resources/zusetnvz/zuse2tnvz_p2.wsdl classpath:zusetnvz/app2zuse_p2.wsdl + + ${project.basedir}/src/main/resources/zusemsg/zuse2app_p2.wsdl + classpath:zusemsg/zuse2app_p2.wsdl + @@ -244,6 +248,8 @@ ${exclude-test-pattern} + false + false diff --git a/src/main/java/at/gv/egiz/moazs/MoaZSException.java b/src/main/java/at/gv/egiz/moazs/MoaZSException.java index 322f06b..1e86c22 100644 --- a/src/main/java/at/gv/egiz/moazs/MoaZSException.java +++ b/src/main/java/at/gv/egiz/moazs/MoaZSException.java @@ -1,10 +1,13 @@ package at.gv.egiz.moazs; -import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; -import at.gv.zustellung.msg.xsd.DeliveryRequestType; +import at.gv.zustellung.msg.xsd.DeliveryAnswerType; +import at.gv.zustellung.msg.xsd.PreAdviceNoteSentType; import at.gv.zustellung.tnvz.xsd.PersonResultType; import org.springframework.lang.Nullable; +import java.util.concurrent.ExecutorService; + + public class MoaZSException extends RuntimeException { public static final String ERROR_MZS_MIMETYPE_MISSMATCH = "8001"; @@ -14,25 +17,29 @@ public class MoaZSException extends RuntimeException { @Nullable private final String errorCode; @Nullable - private final PersonResultType tnvzResult; + private final PreAdviceNoteSentType preAdviceNoteSent; + @Nullable + private final String deliverySystem; @Nullable - private final DeliveryRequestStatusType msgResult; + private final String gz; @Nullable - private final DeliveryRequestType msgRequest; + private final String zsDeliveryID; @Nullable - private final at.gv.zustellung.app2mzs.xsd.DeliveryRequestType mzsRequest; + private final String appDeliveryID; - private MoaZSException(String message, Throwable cause, String errorCode, PersonResultType tnvzResult, - DeliveryRequestStatusType msgResult, DeliveryRequestType msgRequest, - at.gv.zustellung.app2mzs.xsd.DeliveryRequestType mzsRequest) { + private MoaZSException(String message, @Nullable Throwable cause, @Nullable String errorCode, @Nullable PreAdviceNoteSentType preAdviceNoteSent, + @Nullable String deliverySystem, @Nullable String gz, @Nullable String zsDeliveryID, + @Nullable String appDeliveryID) { super(message, cause); this.errorCode = errorCode; - this.tnvzResult = tnvzResult; - this.msgResult = msgResult; - this.msgRequest = msgRequest; - this.mzsRequest = mzsRequest; + this.preAdviceNoteSent = preAdviceNoteSent; + this.deliverySystem = deliverySystem; + this.gz = gz; + this.zsDeliveryID = zsDeliveryID; + this.appDeliveryID = appDeliveryID; } + public static MoaZSException moaZSException(String message, Throwable cause) { return moaZSExceptionBuilder(message).withCause(cause).build(); } @@ -63,23 +70,28 @@ public class MoaZSException extends RuntimeException { } @Nullable - public PersonResultType getTnvzResult() { - return tnvzResult; + public PreAdviceNoteSentType getPreAdviceNoteSent() { + return preAdviceNoteSent; + } + + @Nullable + public String getDeliverySystem() { + return deliverySystem; } @Nullable - public DeliveryRequestStatusType getMsgResult() { - return msgResult; + public String getGz() { + return gz; } @Nullable - public at.gv.zustellung.app2mzs.xsd.DeliveryRequestType getMzsRequest() { - return mzsRequest; + public String getZsDeliveryID() { + return zsDeliveryID; } @Nullable - public DeliveryRequestType getMsgRequest() { - return msgRequest; + public String getAppDeliveryID() { + return appDeliveryID; } public static class Builder { @@ -87,14 +99,26 @@ public class MoaZSException extends RuntimeException { private String message; private Throwable cause; private String errorCode; - private PersonResultType tnvzResult; - private DeliveryRequestStatusType msgResult; - private DeliveryRequestType msgRequest; - private at.gv.zustellung.app2mzs.xsd.DeliveryRequestType mzsRequest; + private PreAdviceNoteSentType preAdviceNoteSent; + private String deliverySystem; + private String gz; + private String zsDeliveryID; + private String appDeliveryID; private Builder() { } + public Builder(MoaZSException exception){ + this.message = exception.getMessage(); + this.cause = exception.getCause(); + this.errorCode = exception.getErrorCode(); + this.preAdviceNoteSent = exception.getPreAdviceNoteSent(); + this.deliverySystem = exception.getDeliverySystem(); + this.gz = exception.getGz(); + this.zsDeliveryID = exception.getZsDeliveryID(); + this.appDeliveryID = exception.getAppDeliveryID(); + } + public Builder withMessage(String message) { this.message = message; return this; @@ -115,28 +139,35 @@ public class MoaZSException extends RuntimeException { return this; } - public Builder withTnvzResult(PersonResultType tnvzResult) { - this.tnvzResult = tnvzResult; + public Builder withPreAdviceNoteSent(PersonResultType personResult) { + if (personResult.getError() != null) { + this.preAdviceNoteSent = personResult.getError().getPreAdviceNoteSent(); + } return this; } - public Builder withMsgResult(DeliveryRequestStatusType msgResult) { - this.msgResult = msgResult; + public Builder withDeliverySystem(at.gv.zustellung.app2mzs.xsd.DeliveryRequestType mzsRequest) { + this.deliverySystem = mzsRequest.getConfig().getMSGClient().getURL(); return this; } - public Builder withMsgRequest(DeliveryRequestType msgRequest) { - this.msgRequest = msgRequest; + + public Builder withAllParametersInAnswer(DeliveryAnswerType answer) { + this.deliverySystem = answer.getDeliverySystem(); + this.gz = answer.getGZ(); + this.zsDeliveryID = answer.getZSDeliveryID(); + this.appDeliveryID = answer.getAppDeliveryID(); return this; } - public Builder withMzsRequest(at.gv.zustellung.app2mzs.xsd.DeliveryRequestType mzsRequest) { - this.mzsRequest = mzsRequest; + public Builder withAppDeliveryID(String appDeliveryID) { + this.appDeliveryID = appDeliveryID; return this; } public MoaZSException build() { - return new MoaZSException(message, cause, errorCode, tnvzResult, msgResult, msgRequest, mzsRequest); + return new MoaZSException(message, cause, errorCode, preAdviceNoteSent, deliverySystem, gz, + zsDeliveryID, appDeliveryID); } } diff --git a/src/main/java/at/gv/egiz/moazs/client/MzsClient.java b/src/main/java/at/gv/egiz/moazs/client/MzsClient.java new file mode 100644 index 0000000..a8f1d27 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/client/MzsClient.java @@ -0,0 +1,13 @@ +package at.gv.egiz.moazs.client; + +import at.gv.zustellung.app2mzs.xsd.DeliveryResponseType; +import org.springframework.stereotype.Component; + +@Component +public class MzsClient { + + public void sendNotification(DeliveryResponseType responseType) { + throw new UnsupportedOperationException("Not implemented."); + } + +} diff --git a/src/main/java/at/gv/egiz/moazs/client/TnvzHelper.java b/src/main/java/at/gv/egiz/moazs/client/TnvzHelper.java new file mode 100644 index 0000000..884be3e --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/client/TnvzHelper.java @@ -0,0 +1,233 @@ +package at.gv.egiz.moazs.client; + +import at.gv.egiz.moazs.MoaZSException; +import at.gv.egiz.moazs.scheme.Mzs2MsgConverter; +import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; +import at.gv.zustellung.app2mzs.xsd.persondata.AbstractAddressType; +import at.gv.zustellung.msg.xsd.persondata.IdentificationType; +import at.gv.zustellung.msg.xsd.persondata.ObjectFactory; +import at.gv.zustellung.msg.xsd.persondata.PostalAddressType; +import at.gv.zustellung.tnvz.xsd.*; +import at.gv.zustellung.tnvz.xsd.QueryPersonRequest.QueryEntryList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.Nullable; +import javax.xml.bind.JAXBElement; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static at.gv.zustellung.tnvz.xsd.PersonQueryType.MetaData.metaDataBuilder; +import static at.gv.zustellung.tnvz.xsd.PersonQueryType.personQueryTypeBuilder; +import static at.gv.zustellung.tnvz.xsd.QueryPersonRequest.QueryEntryList.queryEntryListBuilder; +import static at.gv.zustellung.tnvz.xsd.QueryPersonRequest.queryPersonRequestBuilder; +import static at.gv.zustellung.tnvz.xsd.Receiver.receiverBuilder; +import static at.gv.zustellung.tnvz.xsd.Sender.senderBuilder; +import static java.lang.String.join; +import static java.util.stream.Collectors.toSet; + +@Component +public class TnvzHelper { + + private final Mzs2MsgConverter converter; + + private static final ObjectFactory FACTORY = new at.gv.zustellung.msg.xsd.persondata.ObjectFactory(); + private static final String ENTRY_ID = "entry-id"; + private static final String RECEIVER_NOT_ADRESSABLE_ERROR_MSG = "Receiver is not addressable. Reason: %s"; + private static final String MIMETYPE_MISSMATCH_ERROR_MSG = "Request contains attachment of type(s) %s, but " + + "receiver only accepts attachments of type(s) %s."; + private static final String MZS_NO_TNVZ_PERSON_QUERY_RESULTS_ERROR_MSG = "tnvz:QueryResultList was empty."; + + + @Autowired + public TnvzHelper(Mzs2MsgConverter converter) { + this.converter = converter; + } + + /** + * Performs all tasks related to making a request to the tnvz service: + * Derives a tnvz:QueryPersonRequest from the {@code mzsRequest}, sends the QueryPersonRequest to + * {@code tvnzPort}, validates the tnvz's response and extracts the {@code Identification} Element. + * @param mzsRequest Data source for the QueryPersonRequest + * @param tvnzPort Client for communicating with the tnvz service + * @param exceptionBuilder Utility to collect information and build a meaningful exception in case of errors. + * @throws MoaZSException in case of an error. + * @return + */ + public IdentificationType performQueryPersonRequest(DeliveryRequestType mzsRequest, + TNVZServicePort tvnzPort, + MoaZSException.Builder exceptionBuilder) { + + var tvnzQuery = buildQuery(mzsRequest); + var tvnzResponse = tvnzPort.queryPerson(tvnzQuery); + verifyResponse(tvnzResponse, exceptionBuilder); + + var tvnzResult = getResult(tvnzResponse); + var typesInRequest = extractListOfMimemtypesIn(mzsRequest); + checkMimetypes(tvnzResult, typesInRequest, exceptionBuilder); + + return tvnzResult.getSuccess().getIdentification(); + } + + private QueryPersonRequest buildQuery(DeliveryRequestType mzsRequest) { + + Sender sender = extractSender(mzsRequest.getSender()); + Receiver receiver = extractReceiver(mzsRequest.getReceiver()); + var metadata = extractMetaData(mzsRequest); + + PersonQueryType personQuery = personQueryTypeBuilder() + .withEntryID(ENTRY_ID) + .withSender(sender) + .withReceiver(receiver) + .withMetaData(metadata) + .build(); + + QueryEntryList entryList = queryEntryListBuilder() + .withQueryEntry(List.of(personQuery)) + .build(); + + return queryPersonRequestBuilder() + .withQueryEntryList(entryList) + .build(); + } + + private PersonQueryType.MetaData extractMetaData(DeliveryRequestType request) { + + var builder = metaDataBuilder(); + + var meta = request.getTnvzMetaData(); + + if (meta.getDeliveryQuality() != null) { + builder.withDeliveryQuality(meta.getDeliveryQuality()); + } else { + builder.withPrivateMessageQuality(meta.getPrivateMessageQuality()); + } + + return builder + .withOrigin(meta.getOrigin()) + .withPreAdviceNote(request.getReceiver().getPreAdviceNote()) + .withIgnorePostRedirectionOrder(meta.getIgnorePostRedirectionOrder()) + .build(); + } + + private Sender extractSender(DeliveryRequestType.Sender sender) { + + var corporateBody = sender.getCorporateBody(); + var mzsIdentification = corporateBody.getIdentification().get(0); + var msgIdentification = converter.convert(mzsIdentification); + + var msgPerson = FACTORY.createPerson(converter.convert(corporateBody)); + + return senderBuilder() + .withIdentification(msgIdentification) + .withPerson(msgPerson) + .build(); + } + + private Receiver extractReceiver(DeliveryRequestType.Receiver receiver) { + + var builder = receiverBuilder(); + + if (receiver.getIdentification() == null) { + builder + .withPerson(converter.convert(receiver.getPerson())) + .withAustrianAddressesOnly(receiver.getAustrianAddressesOnly()); + + var postalAddress = findPostalAddress(receiver.getAddress()); + if (postalAddress != null) + builder.withPostalAddress(postalAddress); + + if (receiver.getPreAdviceNote() != null) { + builder.withNotificationAddressList(receiver.getPreAdviceNote().getNotificationAddressList()); + } + } else { + builder.withIdentification(converter.convert(receiver.getIdentification())); + } + + return builder.build(); + } + + private @Nullable PostalAddressType findPostalAddress(List> addresses) { + + if (addresses == null) return null; + + for (JAXBElement address : addresses) { + if(address.getValue() instanceof at.gv.zustellung.app2mzs.xsd.persondata.PostalAddressType) { + var mzsPostalAddress = (at.gv.zustellung.app2mzs.xsd.persondata.PostalAddressType) address.getValue(); + return converter.convert(mzsPostalAddress); + } + } + + return null; + + } + + private Set extractListOfMimemtypesIn(DeliveryRequestType mzsRequest) { + return mzsRequest.getPayload().stream() + .map(DeliveryRequestType.Payload::getMIMEType) + .collect(toSet()); + } + + private void verifyResponse(QueryPersonResponse tvnzResponse, MoaZSException.Builder mzsBuilder) { + + var error = tvnzResponse.getError(); + if (error != null) { + throw mzsBuilder.withErrorCode(error.getCode()) + .withMessage(error.getText()) + .build(); + } + + var results = tvnzResponse.getQueryResultList().getQueryResult(); + if (results.isEmpty()) { + throw mzsBuilder.withErrorCode(MoaZSException.ERROR_MZS_NO_TNVZ_PERSON_QUERY_RESULTS) + .withMessage(MZS_NO_TNVZ_PERSON_QUERY_RESULTS_ERROR_MSG) + .build(); + } + + var tnvzResult = results.get(0); + mzsBuilder.withPreAdviceNoteSent(tnvzResult); + + if (tnvzResult.getError() != null) { + var info = tnvzResult.getError().getErrorInfo(); + throw mzsBuilder.withErrorCode(info.getCode()) + .withMessage(RECEIVER_NOT_ADRESSABLE_ERROR_MSG, info.getText()) + .build(); + } + } + + private PersonResultType getResult(QueryPersonResponse tvnzResponse) { + return tvnzResponse.getQueryResultList().getQueryResult().get(0); + } + + private void checkMimetypes(PersonResultType tnvzResult, Set typesInRequest, MoaZSException.Builder mzsBuilder) { + var mismatchedTypes = findMimeTypeMismatches(tnvzResult, typesInRequest); + if (!mismatchedTypes.isEmpty()) { + var acceptedTypesString = join(",", getAcceptedTypes(tnvzResult)); + var mismatchedTypesString = join(",", mismatchedTypes); + throw mzsBuilder.withErrorCode(MoaZSException.ERROR_MZS_MIMETYPE_MISSMATCH) + .withMessage(MIMETYPE_MISSMATCH_ERROR_MSG, mismatchedTypesString, acceptedTypesString) + .build(); + } + } + + private Collection findMimeTypeMismatches(PersonResultType result, Set typesInRequest) { + var acceptedTypes = getAcceptedTypes(result); + + if (acceptedTypes.contains("*/*")) { + return List.of(); + } + + var typesInRequestCopy = new HashSet<>(typesInRequest); + typesInRequestCopy.removeAll(acceptedTypes); + + return typesInRequestCopy; + } + + private List getAcceptedTypes(PersonResultType result) { + return result.getSuccess().getMimeTypeList().getMimeType(); + } + + +} diff --git a/src/main/java/at/gv/egiz/moazs/config/MzsServiceConfig.java b/src/main/java/at/gv/egiz/moazs/config/MzsServiceConfig.java deleted file mode 100644 index 9fd14eb..0000000 --- a/src/main/java/at/gv/egiz/moazs/config/MzsServiceConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package at.gv.egiz.moazs.config; - -import at.gv.egiz.moazs.scheme.MzsService; -import at.gv.zustellung.app2mzs.xsd.App2Mzs; -import org.apache.cxf.Bus; -import org.apache.cxf.jaxws.EndpointImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import javax.xml.ws.Endpoint; - -@Configuration -public class MzsServiceConfig { - - @Bean - @Autowired - public Endpoint endpoint(Bus bus, MzsService mzsService, App2Mzs app2mzs) { - EndpointImpl endpoint = new EndpointImpl(bus, mzsService); - endpoint.setAddress("/"); - endpoint.setServiceName(app2mzs.getServiceName()); - endpoint.setWsdlLocation(app2mzs.getWSDLDocumentLocation().toString()); - endpoint.publish(); - return endpoint; - } - - @Bean public App2Mzs app2mzs() { - return new App2Mzs(); - } -} diff --git a/src/main/java/at/gv/egiz/moazs/config/PreprocessConfig.java b/src/main/java/at/gv/egiz/moazs/config/PreprocessConfig.java index b24db28..76bfb30 100644 --- a/src/main/java/at/gv/egiz/moazs/config/PreprocessConfig.java +++ b/src/main/java/at/gv/egiz/moazs/config/PreprocessConfig.java @@ -1,6 +1,6 @@ package at.gv.egiz.moazs.config; -import at.gv.egiz.moazs.scheme.MzsDeliveryRequestValidator; +import at.gv.egiz.moazs.preprocess.MzsDeliveryRequestValidator; import at.gv.egiz.moazs.preprocess.*; import at.gv.zustellung.app2mzs.xsd.ConfigType; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/main/java/at/gv/egiz/moazs/config/RepositoryConfig.java b/src/main/java/at/gv/egiz/moazs/config/RepositoryConfig.java new file mode 100644 index 0000000..ee73b9e --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/config/RepositoryConfig.java @@ -0,0 +1,32 @@ +package at.gv.egiz.moazs.config; + +import at.gv.egiz.moazs.repository.BinaryRepository; +import at.gv.egiz.moazs.repository.InMemoryBinaryRepository; +import at.gv.egiz.moazs.scheme.NameSpace; +import at.gv.egiz.moazs.scheme.NotificationResponse; +import at.gv.egiz.moazs.scheme.RequestStatusResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import java.util.Map; + +@Configuration +@Profile("!cluster") +public class RepositoryConfig { + + @Value("${repository.expiresAfterWrite}") + private int expiresAfterWrite; + + @Bean + public BinaryRepository binaryRepository() { + return new InMemoryBinaryRepository(expiresAfterWrite); + } + + @Bean + public Map idSuffixes() { + return Map.of(NameSpace.MSG_DELIVERY_REQUEST_STATUS, RequestStatusResponse.getIdSuffix(), + NameSpace.MSG_DELIVERY_NOTIFICATION, NotificationResponse.getIdSuffix()); + } +} diff --git a/src/main/java/at/gv/egiz/moazs/config/ServicesConfig.java b/src/main/java/at/gv/egiz/moazs/config/ServicesConfig.java new file mode 100644 index 0000000..8e354ab --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/config/ServicesConfig.java @@ -0,0 +1,46 @@ +package at.gv.egiz.moazs.config; + +import at.gv.egiz.moazs.service.MsgService; +import at.gv.egiz.moazs.service.MzsService; +import at.gv.egiz.moazs.util.EndpointFactory; +import at.gv.egiz.moazs.util.StoreSOAPBodyBinaryInRepositoryInterceptor; +import at.gv.zustellung.app2mzs.xsd.App2Mzs; +import at.gv.zustellung.msg.xsd.Zuse2AppPortService; +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.message.Message; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.xml.ws.Endpoint; + +@Configuration +public class ServicesConfig { + + @Autowired + private EndpointFactory endpointFactory; + + @Bean + @Autowired + public Endpoint msgEndpoint(MsgService msgService, + Zuse2AppPortService zuse2app, + Interceptor msgInterceptor) { + return endpointFactory.create(msgService, zuse2app, msgInterceptor); + } + + @Bean + @Autowired + public Endpoint mzsEndpoint(MzsService mzsService, App2Mzs app2mzs) { + return endpointFactory.create(mzsService, app2mzs); + } + + @Bean + public Zuse2AppPortService zuse2App() { + return new Zuse2AppPortService(); + } + + @Bean public App2Mzs app2mzs() { + return new App2Mzs(); + } + +} diff --git a/src/main/java/at/gv/egiz/moazs/pipeline/DeliveryPipeline.java b/src/main/java/at/gv/egiz/moazs/pipeline/DeliveryPipeline.java deleted file mode 100644 index f32dfe2..0000000 --- a/src/main/java/at/gv/egiz/moazs/pipeline/DeliveryPipeline.java +++ /dev/null @@ -1,17 +0,0 @@ -package at.gv.egiz.moazs.pipeline; - - -public interface DeliveryPipeline { - - /** - * Performs all {@code DeliveryRequest}'s Back-End Tasks. - * - * Fetches {@code DeliveryRequest} referred by appDeliveryId from - * {@code DeliveryRepository}, makes sure that all necessary - * tasks (query tnvz, query msg, verify status) are executed and - * stores the response back to {@code DeliveryRepository}. - * @param appDeliveryId - */ - void processRequest(String appDeliveryId); - -} diff --git a/src/main/java/at/gv/egiz/moazs/pipeline/SingleThreadedDeliveryPipeline.java b/src/main/java/at/gv/egiz/moazs/pipeline/SingleThreadedDeliveryPipeline.java index 783df32..69065d7 100644 --- a/src/main/java/at/gv/egiz/moazs/pipeline/SingleThreadedDeliveryPipeline.java +++ b/src/main/java/at/gv/egiz/moazs/pipeline/SingleThreadedDeliveryPipeline.java @@ -1,17 +1,17 @@ -package at.gv.egiz.moazs.pipeline; +package at.gv.egiz.moazs.process; import at.gv.egiz.moazs.MoaZSException; -import at.gv.egiz.moazs.util.ClientFactory; +import at.gv.egiz.moazs.client.ClientFactory; +import at.gv.egiz.moazs.client.TnvzHelper; +import at.gv.egiz.moazs.repository.BinaryRepository; import at.gv.egiz.moazs.repository.DeliveryRepository; import at.gv.egiz.moazs.scheme.Mzs2MsgConverter; -import at.gv.egiz.moazs.scheme.NameSpace; -import at.gv.egiz.moazs.scheme.TnvzHelper; +import at.gv.egiz.moazs.scheme.RequestStatusResponse; +import at.gv.egiz.moazs.verify.MsgResponseVerifier; import at.gv.egiz.moazs.verify.SignatureVerifier; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; import at.gv.zustellung.msg.xsd.App2ZusePort; -import at.gv.zustellung.msg.xsd.DeliveryAnswerType; -import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; import at.gv.zustellung.tnvz.xsd.TNVZServicePort; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -19,10 +19,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import static at.gv.egiz.moazs.MoaZSException.moaZSExceptionBuilder; -import static at.gv.egiz.moazs.util.NullCoalesce.coalesce; -import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.Error.errorBuilder; -import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.deliveryRequestStatusTypeBuilder; -import static at.gv.zustellung.msg.xsd.ErrorInfoType.errorInfoTypeBuilder; +import static at.gv.egiz.moazs.scheme.RequestStatusResponse.generateErrorFromException; import static java.lang.String.format; @Component @@ -30,8 +27,11 @@ import static java.lang.String.format; public class SingleThreadedDeliveryPipeline implements DeliveryPipeline { private static final Logger log = Logger.getLogger(SingleThreadedDeliveryPipeline.class); + private static final String MZS_PIPELINE_ERROR_MSG = + "An error occured while processing the DeliveryRequest with AppDeliveryID=%s. "; private final DeliveryRepository repository; + private final BinaryRepository binaryRepository; private final TnvzHelper tnvzHelper; private final Mzs2MsgConverter converter; private final ClientFactory clientFactory; @@ -39,12 +39,13 @@ public class SingleThreadedDeliveryPipeline implements DeliveryPipeline { @Autowired public SingleThreadedDeliveryPipeline(DeliveryRepository repository, + BinaryRepository binaryStatusRepository, TnvzHelper tnvzHelper, Mzs2MsgConverter converter, ClientFactory clientFactory, - SignatureVerifier verifier - ) { + SignatureVerifier verifier) { this.repository = repository; + this.binaryRepository = binaryStatusRepository; this.tnvzHelper = tnvzHelper; this.converter = converter; this.clientFactory = clientFactory; @@ -58,89 +59,49 @@ public class SingleThreadedDeliveryPipeline implements DeliveryPipeline { try { var mzsRequest = repository.getDeliveryRequest(appDeliveryId).orElseThrow(); - exceptionBuilder.withMzsRequest(mzsRequest); + exceptionBuilder.withDeliverySystem(mzsRequest); at.gv.zustellung.msg.xsd.DeliveryRequestType msgRequest = buildMsgRequest(mzsRequest, exceptionBuilder); - exceptionBuilder.withMsgRequest(msgRequest); var msgClientParams = mzsRequest.getConfig().getMSGClient(); App2ZusePort client = clientFactory.create(msgClientParams, App2ZusePort.class); var status = client.delivery(msgRequest); - exceptionBuilder.withMsgResult(status); - verifySignedStatus(appDeliveryId, exceptionBuilder); - repository.add(status); + var response = new RequestStatusResponse(status); + exceptionBuilder.withAllParametersInAnswer(response.getAnswer()); - } catch (MoaZSException exception) { - - log.error(format("An error occured while processing the DeliveryRequest with AppDeliveryID=%s. ", - appDeliveryId), exception); - - var errorStatus = generateErrorStatus(exception, appDeliveryId); - repository.add(errorStatus); - } - } + verifySignedStatus(response.getResponseID(), exceptionBuilder); + repository.add(response); - private at.gv.zustellung.msg.xsd.DeliveryRequestType buildMsgRequest(DeliveryRequestType mzsRequest, - MoaZSException.Builder exceptionBuilder) { - if (mzsRequest.getConfig().isPerformQueryPersonRequest()) { - var tnvzClientParams = mzsRequest.getConfig().getTNVZClient(); - TNVZServicePort tvnzPort = clientFactory.create(tnvzClientParams, TNVZServicePort.class); - var identification = tnvzHelper.performQueryPersonRequest(mzsRequest, tvnzPort, exceptionBuilder); - return converter.convert(mzsRequest, identification); - } else { - return converter.convert(mzsRequest); + } catch (MoaZSException exception) { + log.error(format(MZS_PIPELINE_ERROR_MSG, appDeliveryId), exception); + var errorResponse = generateErrorFromException(exception); + repository.add(errorResponse); } } private void verifySignedStatus(String appDeliveryId, MoaZSException.Builder exceptionBuilder) throws MoaZSException { - try { - var signedStatus = repository.getSignedDeliveryRequestStatus(appDeliveryId).get(); + var signedStatus = binaryRepository.get(appDeliveryId).get(); verifier.verify(signedStatus); - } catch (Exception ex) { - throw exceptionBuilder.withMessage(format("Signature of DeliveryRequestStatus with AppDeliveryID=%s " + - " is not valid.", appDeliveryId)) + } catch (MoaZSException ex) { + throw exceptionBuilder.withMessage(format(MsgResponseVerifier.MOASP_SIGNATURE_INVALID_ERROR_MSG, appDeliveryId)) .withErrorCode(MoaZSException.ERROR_MOASP_SIGNATURE_INVALID) .withCause(ex) .build(); } } - private DeliveryRequestStatusType generateErrorStatus(MoaZSException exception, String appDeliveryId) { - - var infoBuilder = errorInfoTypeBuilder() - .withText(exception.getMessage()) - .withCode(exception.getErrorCode()); - - var errorBuilder = errorBuilder() - .withErrorInfo(infoBuilder.build()) - .withAppDeliveryID(appDeliveryId); - - if (exception.getMzsRequest() != null) { - errorBuilder.withDeliverySystem(exception.getMzsRequest().getConfig().getMSGClient().getURL()); - } - - if (exception.getTnvzResult() != null && exception.getTnvzResult().getError() != null) { - errorBuilder.withPreAdviceNoteSent(exception.getTnvzResult().getError().getPreAdviceNoteSent()); - } - - if (exception.getMsgResult() != null) { - var answer = getAnswerFromResult(exception.getMsgResult()); - errorBuilder.withGZ(answer.getGZ()); - errorBuilder.withZSDeliveryID(answer.getZSDeliveryID()); + private at.gv.zustellung.msg.xsd.DeliveryRequestType buildMsgRequest(DeliveryRequestType mzsRequest, + MoaZSException.Builder exceptionBuilder) throws MoaZSException { + if (mzsRequest.getConfig().isPerformQueryPersonRequest()) { + var tnvzClientParams = mzsRequest.getConfig().getTNVZClient(); + TNVZServicePort tvnzPort = clientFactory.create(tnvzClientParams, TNVZServicePort.class); + var identification = tnvzHelper.performQueryPersonRequest(mzsRequest, tvnzPort, exceptionBuilder); + return converter.convert(mzsRequest, identification); + } else { + return converter.convert(mzsRequest); } - - return deliveryRequestStatusTypeBuilder() - .withError(errorBuilder.build()) - .withVersion(NameSpace.MSG_VERSION) - .build(); - - } - - private DeliveryAnswerType getAnswerFromResult(DeliveryRequestStatusType msgResult) { - return coalesce(msgResult.getSuccess(), msgResult.getPartialSuccess(), msgResult.getError()).get(); } - } diff --git a/src/main/java/at/gv/egiz/moazs/preprocess/ConfigProfileGenerator.java b/src/main/java/at/gv/egiz/moazs/preprocess/ConfigProfileGenerator.java index d651570..5e81f0d 100644 --- a/src/main/java/at/gv/egiz/moazs/preprocess/ConfigProfileGenerator.java +++ b/src/main/java/at/gv/egiz/moazs/preprocess/ConfigProfileGenerator.java @@ -1,7 +1,6 @@ package at.gv.egiz.moazs.preprocess; import at.gv.egiz.moazs.MoaZSException; -import at.gv.egiz.moazs.scheme.MzsDeliveryRequestValidator; import at.gv.egiz.moazs.util.StringUtils; import at.gv.zustellung.app2mzs.xsd.ConfigType; import org.slf4j.Logger; diff --git a/src/main/java/at/gv/egiz/moazs/preprocess/DeliveryRequestAugmenter.java b/src/main/java/at/gv/egiz/moazs/preprocess/DeliveryRequestAugmenter.java index 783536c..eac7ea6 100644 --- a/src/main/java/at/gv/egiz/moazs/preprocess/DeliveryRequestAugmenter.java +++ b/src/main/java/at/gv/egiz/moazs/preprocess/DeliveryRequestAugmenter.java @@ -1,6 +1,5 @@ package at.gv.egiz.moazs.preprocess; -import at.gv.egiz.moazs.scheme.MzsDeliveryRequestValidator; import at.gv.zustellung.app2mzs.xsd.ConfigType; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/main/java/at/gv/egiz/moazs/preprocess/MzsDeliveryRequestValidator.java b/src/main/java/at/gv/egiz/moazs/preprocess/MzsDeliveryRequestValidator.java new file mode 100644 index 0000000..8f9cd27 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/preprocess/MzsDeliveryRequestValidator.java @@ -0,0 +1,74 @@ +package at.gv.egiz.moazs.preprocess; + +import at.gv.zustellung.app2mzs.xsd.ClientType; +import at.gv.zustellung.app2mzs.xsd.ConfigType; +import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; +import at.gv.zustellung.app2mzs.xsd.KeyStoreType; +import org.springframework.lang.Nullable; +import org.springframework.stereotype.Component; + +@Component +public class MzsDeliveryRequestValidator { + + /** + * Checks if the mandatory fields that are needed to send a tnvz:QueryPersonRequest are present. + * @param request + * @return true if mandatory fields are present. + */ + public boolean isTnvzComplete(DeliveryRequestType request) { + return !request.getConfig().isPerformQueryPersonRequest() || + (request.getTnvzMetaData() != null + && request.getSender().getCorporateBody() != null); + + + } + + /** + * Check if all mandatory fields of configuration are present. + * + * @param profile + * @return true if all mandatory fields are present. + */ + public boolean isConfigProfileComplete(@Nullable ConfigType profile) { + return profile != null + && profile.isPerformQueryPersonRequest() != null + && isTVNZClientConfigured(profile.getTNVZClient(), profile.isPerformQueryPersonRequest()) + && isMSGClientConfigured(profile.getMSGClient()); + } + + private boolean isTVNZClientConfigured(ClientType tnvzClient, Boolean isPerformQueryPersonRequest) { + return !isPerformQueryPersonRequest || (tnvzClient != null + && tnvzClient.getURL() != null + && tnvzClient.getReceiveTimeout() != null + && tnvzClient.getConnectionTimeout() != null + && isSSLConfigured(tnvzClient)); + } + + private boolean isMSGClientConfigured(ClientType msgClientParams) { + return msgClientParams != null + && msgClientParams.getURL() != null + && isSSLConfigured(msgClientParams) + && msgClientParams.getReceiveTimeout() != null + && msgClientParams.getConnectionTimeout() != null; + } + + private boolean isSSLConfigured(ClientType clientParams) { + return !clientParams.getURL().startsWith("https") || (clientParams.getSSL() != null + && clientParams.getSSL().isTrustAll() != null + && clientParams.getSSL().isLaxHostNameVerification() != null + && isKeyStoreConfigured(clientParams.getSSL().getKeyStore()) + && isTrustStoreConfigured(clientParams.getSSL().getTrustStore())); + } + + private boolean isKeyStoreConfigured(KeyStoreType keyStore) { + return keyStore == null || (keyStore.getPassword() != null + && keyStore.getFileType() != null + && keyStore.getFileName() != null); + } + + private boolean isTrustStoreConfigured(KeyStoreType trustStore) { + return trustStore == null || (trustStore.getPassword() != null + && "JKS".equals(trustStore.getFileType()) + && trustStore.getFileName() != null); + } +} diff --git a/src/main/java/at/gv/egiz/moazs/process/DeliveryPipeline.java b/src/main/java/at/gv/egiz/moazs/process/DeliveryPipeline.java new file mode 100644 index 0000000..506dd1f --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/process/DeliveryPipeline.java @@ -0,0 +1,17 @@ +package at.gv.egiz.moazs.process; + + +public interface DeliveryPipeline { + + /** + * Performs all {@code DeliveryRequest}'s Back-End Tasks. + * + * Fetches {@code DeliveryRequest} referred by appDeliveryId from + * {@code DeliveryRepository}, makes sure that all necessary + * tasks (query tnvz, query msg, verify status) are executed and + * stores the response back to {@code DeliveryRepository}. + * @param appDeliveryId + */ + void processRequest(String appDeliveryId); + +} diff --git a/src/main/java/at/gv/egiz/moazs/process/MsgResponseHandler.java b/src/main/java/at/gv/egiz/moazs/process/MsgResponseHandler.java new file mode 100644 index 0000000..5a7d39b --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/process/MsgResponseHandler.java @@ -0,0 +1,7 @@ +package at.gv.egiz.moazs.process; + +public interface MsgResponseHandler { + + void handle(String id); + +} diff --git a/src/main/java/at/gv/egiz/moazs/process/MsgResponseSink.java b/src/main/java/at/gv/egiz/moazs/process/MsgResponseSink.java new file mode 100644 index 0000000..67348fc --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/process/MsgResponseSink.java @@ -0,0 +1,11 @@ +package at.gv.egiz.moazs.process; + +import at.gv.egiz.moazs.scheme.MsgResponse; + +import java.util.concurrent.CompletableFuture; + +public interface MsgResponseSink { + + CompletableFuture handle(MsgResponse response); + +} diff --git a/src/main/java/at/gv/egiz/moazs/process/SafeResponseToFileSink.java b/src/main/java/at/gv/egiz/moazs/process/SafeResponseToFileSink.java new file mode 100644 index 0000000..ee32768 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/process/SafeResponseToFileSink.java @@ -0,0 +1,84 @@ +package at.gv.egiz.moazs.process; + +import at.gv.egiz.moazs.repository.BinaryRepository; +import at.gv.egiz.moazs.scheme.Marshaller; +import at.gv.egiz.moazs.scheme.MsgResponse; +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.CompletableFuture; + +import static java.lang.String.format; +import static java.util.concurrent.CompletableFuture.allOf; +import static java.util.concurrent.CompletableFuture.supplyAsync; + +@Component +public class SafeResponseToFileSink implements MsgResponseSink { + + private static final Logger log = LoggerFactory.getLogger(SafeResponseToFileSink.class); + private static final String SAFING_FAILED_MSG = "Could not save response with AppDeliveryId=%s."; + private static final SimpleDateFormat ISO_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + + private final Marshaller msgMarshaller; + private final BinaryRepository binaryRepository; + private final String root; + + + @Autowired + public SafeResponseToFileSink(Marshaller msgMarshaller, BinaryRepository binaryRepository, String root) { + this.msgMarshaller = msgMarshaller; + this.binaryRepository = binaryRepository; + this.root = root; + } + + @Override + public CompletableFuture handle(MsgResponse response) { + + var responseId = response.getResponseID(); + + var responsePath = generatePath(responseId, "xml"); + var storeResponseToFileSystemFuture = supplyAsync(() -> msgMarshaller.marshallXml(response.getResponse())) + .thenApply(responseString -> responseString.getBytes(StandardCharsets.UTF_8)) + .thenAccept(responseByteArray -> storeToFile(responsePath, responseByteArray)) + .exceptionally((ex) -> logException(ex, responseId)); + + var binaryResponsePath = generatePath(responseId, "binary.xml"); + var storeBinaryResponseToFileSystemFuture = supplyAsync(() -> binaryRepository.get(responseId).get()) + .thenAccept(binaryResponseByteArray -> storeToFile(binaryResponsePath, binaryResponseByteArray)) + .exceptionally((ex) -> logException(ex, responseId)); + + return allOf(storeResponseToFileSystemFuture, storeBinaryResponseToFileSystemFuture); + + } + + private String generatePath(String id, String suffix) { + var folder = sanitizeFileString(id); + var iso8601_now = ISO_FORMATTER.format(new Date()); + return format("%s/%s/%s.%s", root, folder, iso8601_now, suffix); + } + + private String sanitizeFileString(String fileString) { + return fileString.replaceAll("[^a-zA-Z0-9\\._\\-]", ""); + } + + private Void logException(Throwable ex, String appDeliveryID) { + log.error(format(SAFING_FAILED_MSG, appDeliveryID), ex); + return null; + } + + private void storeToFile(String path, byte[] content) { + try { + FileUtils.writeByteArrayToFile(new File(path), content); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/at/gv/egiz/moazs/process/SingleNodeResponseHandler.java b/src/main/java/at/gv/egiz/moazs/process/SingleNodeResponseHandler.java new file mode 100644 index 0000000..ec609cb --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/process/SingleNodeResponseHandler.java @@ -0,0 +1,26 @@ +package at.gv.egiz.moazs.process; + +import at.gv.egiz.moazs.verify.MsgResponseVerifier; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import static java.util.concurrent.CompletableFuture.supplyAsync; + +@Component +public class SingleNodeResponseHandler implements MsgResponseHandler { + + private final MsgResponseVerifier verifier; + private final MsgResponseSink sink; + + @Autowired + public SingleNodeResponseHandler(MsgResponseVerifier verifier, MsgResponseSink sink) { + this.verifier = verifier; + this.sink = sink; + } + + @Override + public void handle(String id) { + supplyAsync(() -> verifier.verify(id)) + .thenAcceptAsync((response) -> sink.handle(response)); + } +} diff --git a/src/main/java/at/gv/egiz/moazs/repository/DeliveryRepository.java b/src/main/java/at/gv/egiz/moazs/repository/DeliveryRepository.java index be61d1e..d0a8148 100644 --- a/src/main/java/at/gv/egiz/moazs/repository/DeliveryRepository.java +++ b/src/main/java/at/gv/egiz/moazs/repository/DeliveryRepository.java @@ -1,6 +1,8 @@ package at.gv.egiz.moazs.repository; +import at.gv.egiz.moazs.scheme.MsgResponse; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; +import at.gv.zustellung.msg.xsd.DeliveryNotificationType; import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; import org.springframework.stereotype.Repository; @@ -13,13 +15,9 @@ public interface DeliveryRepository { Optional getDeliveryRequest(String appDeliveryID); - void add(DeliveryRequestStatusType status); + void add(MsgResponse response); - Optional getDeliveryRequestStatus(String appDeliveryID); - - void addSignedDeliveryRequestStatus(byte[] bytes, String appDeliveryId); - - Optional getSignedDeliveryRequestStatus(String appDeliveryID); + Optional getResponse(String id); } diff --git a/src/main/java/at/gv/egiz/moazs/repository/InMemoryDeliveryRepository.java b/src/main/java/at/gv/egiz/moazs/repository/InMemoryDeliveryRepository.java index 58ec92c..d9abb7b 100644 --- a/src/main/java/at/gv/egiz/moazs/repository/InMemoryDeliveryRepository.java +++ b/src/main/java/at/gv/egiz/moazs/repository/InMemoryDeliveryRepository.java @@ -1,36 +1,27 @@ package at.gv.egiz.moazs.repository; +import at.gv.egiz.moazs.scheme.MsgResponse; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; -import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Repository; import java.util.Optional; import java.util.concurrent.TimeUnit; -import static at.gv.egiz.moazs.util.NullCoalesce.coalesce; import static java.util.Optional.ofNullable; @Repository @Profile("!cluster") public class InMemoryDeliveryRepository implements DeliveryRepository { - private static final Logger logger = LoggerFactory.getLogger(InMemoryDeliveryRepository.class); - - private static final Cache requestRepository = CacheBuilder.newBuilder() + private final Cache requestRepository = CacheBuilder.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .build(); - private static final Cache statusRepository = CacheBuilder.newBuilder() - .expireAfterWrite(30, TimeUnit.MINUTES) - .build(); - - private static final Cache signedStatusRepository = CacheBuilder.newBuilder() + private final Cache responseRepository = CacheBuilder.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .build(); @@ -46,24 +37,14 @@ public class InMemoryDeliveryRepository implements DeliveryRepository { } @Override - public void add(DeliveryRequestStatusType status) { - var key = coalesce(status.getSuccess(), status.getPartialSuccess(), status.getError()) - .get().getAppDeliveryID(); - statusRepository.put(key, status); - } - - @Override - public Optional getDeliveryRequestStatus(String appDeliveryID) { - return ofNullable(statusRepository.getIfPresent(appDeliveryID)); - } - - @Override - public void addSignedDeliveryRequestStatus(byte[] bytes, String appDeliveryId) { - signedStatusRepository.put(appDeliveryId, bytes); + public void add(MsgResponse response) { + String key = response.getResponseID(); + System.out.println("storing with response id " + key); + responseRepository.put(key, response); } @Override - public Optional getSignedDeliveryRequestStatus(String appDeliveryID) { - return ofNullable(signedStatusRepository.getIfPresent(appDeliveryID)); + public Optional getResponse(String id) { + return ofNullable(responseRepository.getIfPresent(id)); } } diff --git a/src/main/java/at/gv/egiz/moazs/repository/RedisDeliveryRepository.java b/src/main/java/at/gv/egiz/moazs/repository/RedisDeliveryRepository.java index 9b7aefd..7ccd236 100644 --- a/src/main/java/at/gv/egiz/moazs/repository/RedisDeliveryRepository.java +++ b/src/main/java/at/gv/egiz/moazs/repository/RedisDeliveryRepository.java @@ -1,7 +1,9 @@ package at.gv.egiz.moazs.repository; import at.gv.egiz.moazs.scheme.Marshaller; +import at.gv.egiz.moazs.scheme.MsgResponse; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; +import at.gv.zustellung.msg.xsd.DeliveryNotificationType; import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; import at.gv.zustellung.app2mzs.xsd.ObjectFactory; import org.apache.tools.ant.filters.StringInputStream; @@ -50,7 +52,7 @@ public class RedisDeliveryRepository implements DeliveryRepository { @Override public Optional getDeliveryRequest(String appDeliveryID) { - var serializedRequest = hashOperations.get(KEY, appDeliveryID); + String serializedRequest = hashOperations.get(KEY, appDeliveryID); if (serializedRequest == null) { return Optional.empty(); @@ -62,22 +64,14 @@ public class RedisDeliveryRepository implements DeliveryRepository { } @Override - public void add(DeliveryRequestStatusType status) { + public void add(MsgResponse notification) { throw new UnsupportedOperationException(NOT_IMPLEMENTED_MESSAGE); - } - @Override - public Optional getDeliveryRequestStatus(String appDeliveryID) { - throw new UnsupportedOperationException(NOT_IMPLEMENTED_MESSAGE); } @Override - public void addSignedDeliveryRequestStatus(byte[] bytes, String appDeliveryId) { + public Optional getResponse(String id) { throw new UnsupportedOperationException(NOT_IMPLEMENTED_MESSAGE); } - @Override - public Optional getSignedDeliveryRequestStatus(String appDeliveryID) { - return Optional.empty(); - } } diff --git a/src/main/java/at/gv/egiz/moazs/scheme/MsgResponse.java b/src/main/java/at/gv/egiz/moazs/scheme/MsgResponse.java new file mode 100644 index 0000000..fe46451 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/scheme/MsgResponse.java @@ -0,0 +1,15 @@ +package at.gv.egiz.moazs.scheme; + +import at.gv.egiz.moazs.MoaZSException; +import at.gv.zustellung.msg.xsd.DeliveryAnswerType; + +public interface MsgResponse { + + String getResponseID(); + T getResponse(); + String getAppDeliveryID(); + String getZSDeliveryID(); + DeliveryAnswerType getAnswer(); + MsgResponse generateError(MoaZSException exception); + +} diff --git a/src/main/java/at/gv/egiz/moazs/scheme/MzsClient.java b/src/main/java/at/gv/egiz/moazs/scheme/MzsClient.java deleted file mode 100644 index 98e0bc8..0000000 --- a/src/main/java/at/gv/egiz/moazs/scheme/MzsClient.java +++ /dev/null @@ -1,13 +0,0 @@ -package at.gv.egiz.moazs.scheme; - -import at.gv.zustellung.app2mzs.xsd.DeliveryResponseType; -import org.springframework.stereotype.Component; - -@Component -public class MzsClient { - - public void sendNotification(DeliveryResponseType responseType) { - throw new UnsupportedOperationException("Not implemented."); - } - -} diff --git a/src/main/java/at/gv/egiz/moazs/scheme/MzsDeliveryRequestValidator.java b/src/main/java/at/gv/egiz/moazs/scheme/MzsDeliveryRequestValidator.java deleted file mode 100644 index 03f2664..0000000 --- a/src/main/java/at/gv/egiz/moazs/scheme/MzsDeliveryRequestValidator.java +++ /dev/null @@ -1,74 +0,0 @@ -package at.gv.egiz.moazs.scheme; - -import at.gv.zustellung.app2mzs.xsd.ClientType; -import at.gv.zustellung.app2mzs.xsd.ConfigType; -import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; -import at.gv.zustellung.app2mzs.xsd.KeyStoreType; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Component; - -@Component -public class MzsDeliveryRequestValidator { - - /** - * Checks if the mandatory fields that are needed to send a tnvz:QueryPersonRequest are present. - * @param request - * @return true if mandatory fields are present. - */ - public boolean isTnvzComplete(DeliveryRequestType request) { - return !request.getConfig().isPerformQueryPersonRequest() || - (request.getTnvzMetaData() != null - && request.getSender().getCorporateBody() != null); - - - } - - /** - * Check if all mandatory fields of configuration are present. - * - * @param profile - * @return true if all mandatory fields are present. - */ - public boolean isConfigProfileComplete(@Nullable ConfigType profile) { - return profile != null - && profile.isPerformQueryPersonRequest() != null - && isTVNZClientConfigured(profile.getTNVZClient(), profile.isPerformQueryPersonRequest()) - && isMSGClientConfigured(profile.getMSGClient()); - } - - private boolean isTVNZClientConfigured(ClientType tnvzClient, Boolean isPerformQueryPersonRequest) { - return !isPerformQueryPersonRequest || (tnvzClient != null - && tnvzClient.getURL() != null - && tnvzClient.getReceiveTimeout() != null - && tnvzClient.getConnectionTimeout() != null - && isSSLConfigured(tnvzClient)); - } - - private boolean isMSGClientConfigured(ClientType msgClientParams) { - return msgClientParams != null - && msgClientParams.getURL() != null - && isSSLConfigured(msgClientParams) - && msgClientParams.getReceiveTimeout() != null - && msgClientParams.getConnectionTimeout() != null; - } - - private boolean isSSLConfigured(ClientType clientParams) { - return !clientParams.getURL().startsWith("https") || (clientParams.getSSL() != null - && clientParams.getSSL().isTrustAll() != null - && clientParams.getSSL().isLaxHostNameVerification() != null - && isKeyStoreConfigured(clientParams.getSSL().getKeyStore()) - && isTrustStoreConfigured(clientParams.getSSL().getTrustStore())); - } - - private boolean isKeyStoreConfigured(KeyStoreType keyStore) { - return keyStore == null || (keyStore.getPassword() != null - && keyStore.getFileType() != null - && keyStore.getFileName() != null); - } - - private boolean isTrustStoreConfigured(KeyStoreType trustStore) { - return trustStore == null || (trustStore.getPassword() != null - && "JKS".equals(trustStore.getFileType()) - && trustStore.getFileName() != null); - } -} diff --git a/src/main/java/at/gv/egiz/moazs/scheme/MzsService.java b/src/main/java/at/gv/egiz/moazs/scheme/MzsService.java deleted file mode 100644 index f245b93..0000000 --- a/src/main/java/at/gv/egiz/moazs/scheme/MzsService.java +++ /dev/null @@ -1,104 +0,0 @@ -package at.gv.egiz.moazs.scheme; - -import at.gv.egiz.moazs.pipeline.DeliveryPipeline; -import at.gv.egiz.moazs.preprocess.DeliveryRequestAugmenter; -import at.gv.egiz.moazs.repository.DeliveryRepository; -import at.gv.zustellung.app2mzs.xsd.App2MzsPortType; -import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; -import at.gv.zustellung.app2mzs.xsd.DeliveryResponseType; -import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; -import org.apache.cxf.annotations.SchemaValidation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import javax.jws.WebParam; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import static at.gv.egiz.moazs.MoaZSException.moaZSException; -import static at.gv.egiz.moazs.MoaZSException.moaZSExceptionBuilder; -import static at.gv.zustellung.app2mzs.xsd.PartialSuccessType.partialSuccessTypeBuilder; -import static java.util.concurrent.CompletableFuture.supplyAsync; - -//todo : validate Schema in both directions. -@Service -@SchemaValidation(type = SchemaValidation.SchemaValidationType.IN) -public class MzsService implements App2MzsPortType { - - private static final Logger logger = LoggerFactory.getLogger(MzsService.class); - - //TODO move timeout and namespaces to config - private static final int TIMEOUT_FOR_ANWSER = 10; - - private final DeliveryRepository repository; - private final DeliveryPipeline pipeline; - private final MzsClient appClient; - private final DeliveryRequestAugmenter augmenter; - private final Msg2MzsConverter converter; - - @Autowired - public MzsService(DeliveryRepository repository, DeliveryPipeline pipeline, MzsClient appClient, - DeliveryRequestAugmenter augmenter, Msg2MzsConverter converter) { - this.repository = repository; - this.pipeline = pipeline; - this.appClient = appClient; - this.augmenter = augmenter; - this.converter = converter; - } - - @Override - public DeliveryResponseType app2Mzs( - @WebParam(partName = "DeliveryRequest", - name = "DeliveryRequest") - DeliveryRequestType deliveryRequest) { - - var appDeliveryID = deliveryRequest.getMetaData().getAppDeliveryID(); - - var future = supplyAsync(() -> augmenter.augment(deliveryRequest)) - .thenApply(this::process) - .thenApply(status -> converter.convert(status, repository.getSignedDeliveryRequestStatus(appDeliveryID))); - - try { - return future.get(TIMEOUT_FOR_ANWSER, TimeUnit.SECONDS); - } catch (TimeoutException e) { - logger.info("Answer Timed Out", e); - - future.thenAccept(appClient::sendNotification); - return generatePartialSuccessResponse(appDeliveryID); - - } catch (Exception e) { - throw moaZSExceptionBuilder("An error occurred while processing DeliveryRequest " + - "with AppDeliveryID=%s.", appDeliveryID) - .withCause(e) - .build(); - } - - } - - private DeliveryRequestStatusType process(DeliveryRequestType deliveryRequest) { - - var appDeliveryID = deliveryRequest.getMetaData().getAppDeliveryID(); - logger.info("Receive request with appDeliveryID = {}.", appDeliveryID); - - repository.add(deliveryRequest); - pipeline.processRequest(appDeliveryID); - - return repository.getDeliveryRequestStatus(appDeliveryID) - .orElseThrow(() -> moaZSException("Could not get a response for AppDeliveryID=%s.", appDeliveryID)); - - } - - private DeliveryResponseType generatePartialSuccessResponse(String appDeliveryId) { - - var partial = partialSuccessTypeBuilder() - .withAppDeliveryID(appDeliveryId) - .build(); - - return DeliveryResponseType.deliveryResponseTypeBuilder() - .withPartialSuccess(partial) - .build(); - } - -} diff --git a/src/main/java/at/gv/egiz/moazs/scheme/NameSpace.java b/src/main/java/at/gv/egiz/moazs/scheme/NameSpace.java index 7c52af1..bb7f621 100644 --- a/src/main/java/at/gv/egiz/moazs/scheme/NameSpace.java +++ b/src/main/java/at/gv/egiz/moazs/scheme/NameSpace.java @@ -4,12 +4,17 @@ public class NameSpace { private NameSpace() {} - public static final String MSG = new at.gv.zustellung.msg.xsd.ObjectFactory().createDeliveryRequest(null).getName().getNamespaceURI(); + private static final at.gv.zustellung.msg.xsd.ObjectFactory MSG_FACTORY = new at.gv.zustellung.msg.xsd.ObjectFactory(); + public static final String MSG_VERSION = "2.2.0"; + public static final String MSG = MSG_FACTORY.createDeliveryRequest(null).getName().getNamespaceURI(); public static final String MSGP = new at.gv.zustellung.msg.xsd.persondata.ObjectFactory().createPerson(null).getName().getNamespaceURI(); - public static final String MZS = new at.gv.zustellung.app2mzs.xsd.ObjectFactory().createDeliveryRequest(null).getName().getNamespaceURI(); + public static final String MZS = new at.gv.zustellung.app2mzs.xsd.ObjectFactory().createDeliveryRequest(null).getName().getNamespaceURI(); public static final String TNVZ = new at.gv.zustellung.tnvz.xsd.ObjectFactory().createAddressabilityQuery(null).getName().getNamespaceURI(); public static final String MZSP = new at.gv.zustellung.app2mzs.xsd.persondata.ObjectFactory().createAbstractPersonData(null).getName().getNamespaceURI(); public static final String DSIG = new org.w3._2000._09.xmldsig_.ObjectFactory().createCanonicalizationMethod(null).getName().getNamespaceURI(); + public static final String MSG_DELIVERY_REQUEST_STATUS = MSG_FACTORY.createDeliveryRequestStatus(null).getName().getLocalPart(); + public static final String MSG_DELIVERY_NOTIFICATION = MSG_FACTORY.createDeliveryNotification(null).getName().getLocalPart(); + } diff --git a/src/main/java/at/gv/egiz/moazs/scheme/NotificationResponse.java b/src/main/java/at/gv/egiz/moazs/scheme/NotificationResponse.java new file mode 100644 index 0000000..f465a28 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/scheme/NotificationResponse.java @@ -0,0 +1,67 @@ +package at.gv.egiz.moazs.scheme; + +import at.gv.egiz.moazs.MoaZSException; +import at.gv.zustellung.msg.xsd.DeliveryAnswerType; +import at.gv.zustellung.msg.xsd.DeliveryNotificationType; + +import static at.gv.zustellung.msg.xsd.DeliveryNotificationType.deliveryNotificationTypeBuilder; + +public class NotificationResponse implements MsgResponse { + + private final DeliveryNotificationType notification; + private final String id; + private static final String ID_SUFFIX = ".NO"; + + public NotificationResponse(DeliveryNotificationType notification) { + this.notification = notification; + this.id = getId(notification.getAppDeliveryID()); + } + + @Override + public String getResponseID() { + return this.id; + } + + public static String getId(String appDeliveryID) { + return appDeliveryID + ID_SUFFIX; + } + + @Override + public DeliveryNotificationType getResponse() { + return notification; + } + + @Override + public String getAppDeliveryID() { + return notification.getAppDeliveryID(); + } + + @Override + public String getZSDeliveryID() { + return notification.getZSDeliveryID(); + } + + @Override + public DeliveryAnswerType getAnswer() { + return notification; + } + + @Override + public MsgResponse generateError(MoaZSException exception) { + + //TODO: test this! + var notification = deliveryNotificationTypeBuilder() + .withAppDeliveryID(exception.getAppDeliveryID()) + .withDeliverySystem(exception.getDeliverySystem()) + .withGZ(exception.getGz()) + .withZSDeliveryID(exception.getZsDeliveryID()) + .build(); + + return new NotificationResponse(notification); + + } + + public static String getIdSuffix() { + return ID_SUFFIX; + } +} diff --git a/src/main/java/at/gv/egiz/moazs/scheme/RequestStatusResponse.java b/src/main/java/at/gv/egiz/moazs/scheme/RequestStatusResponse.java new file mode 100644 index 0000000..89c8be3 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/scheme/RequestStatusResponse.java @@ -0,0 +1,87 @@ +package at.gv.egiz.moazs.scheme; + +import at.gv.egiz.moazs.MoaZSException; +import at.gv.zustellung.msg.xsd.DeliveryAnswerType; +import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; +import at.gv.zustellung.msg.xsd.ErrorInfoType; + +import static at.gv.egiz.moazs.util.NullCoalesce.coalesce; +import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.Error.errorBuilder; +import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.deliveryRequestStatusTypeBuilder; +import static at.gv.zustellung.msg.xsd.ErrorInfoType.errorInfoTypeBuilder; + +public class RequestStatusResponse implements MsgResponse { + + private final DeliveryRequestStatusType status; + private final DeliveryAnswerType answer; + private final String responseID; + private static final String ID_SUFFIX = ".RS"; + + public RequestStatusResponse(DeliveryRequestStatusType status) { + this.status = status; + this.answer = coalesce(status.getSuccess(), status.getPartialSuccess(), status.getError()).get(); + this.responseID = getResponseID(answer.getAppDeliveryID()); + } + + public static String getResponseID(String appDeliveryID) { + return appDeliveryID + ID_SUFFIX; + } + + @Override + public String getResponseID() { + return this.responseID; + } + + @Override + public DeliveryRequestStatusType getResponse() { + return status; + } + + @Override + public String getAppDeliveryID() { + return answer.getAppDeliveryID(); + } + + @Override + public String getZSDeliveryID() { + return answer.getZSDeliveryID(); + } + + @Override + public DeliveryAnswerType getAnswer() { + return this.answer; + } + + @Override + public MsgResponse generateError(MoaZSException exception) { + return generateErrorFromException(exception); + } + + public static MsgResponse generateErrorFromException(MoaZSException exception) { + ErrorInfoType info = errorInfoTypeBuilder() + .withText(exception.getMessage()) + .withCode(exception.getErrorCode()) + .build(); + + DeliveryRequestStatusType.Error error = errorBuilder() + .withErrorInfo(info) + .withAppDeliveryID(exception.getAppDeliveryID()) + .withDeliverySystem(exception.getDeliverySystem()) + .withGZ(exception.getGz()) + .withPreAdviceNoteSent(exception.getPreAdviceNoteSent()) + .withZSDeliveryID(exception.getZsDeliveryID()) + .build(); + + var status = deliveryRequestStatusTypeBuilder() + .withError(error) + .withVersion(NameSpace.MSG_VERSION) + .build(); + + return new RequestStatusResponse(status); + + } + + public static String getIdSuffix() { + return ID_SUFFIX; + } +} diff --git a/src/main/java/at/gv/egiz/moazs/scheme/TnvzHelper.java b/src/main/java/at/gv/egiz/moazs/scheme/TnvzHelper.java deleted file mode 100644 index 70c20bb..0000000 --- a/src/main/java/at/gv/egiz/moazs/scheme/TnvzHelper.java +++ /dev/null @@ -1,232 +0,0 @@ -package at.gv.egiz.moazs.scheme; - -import at.gv.egiz.moazs.MoaZSException; -import at.gv.egiz.moazs.scheme.Mzs2MsgConverter; -import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; -import at.gv.zustellung.app2mzs.xsd.persondata.AbstractAddressType; -import at.gv.zustellung.msg.xsd.persondata.IdentificationType; -import at.gv.zustellung.msg.xsd.persondata.ObjectFactory; -import at.gv.zustellung.msg.xsd.persondata.PostalAddressType; -import at.gv.zustellung.tnvz.xsd.*; -import at.gv.zustellung.tnvz.xsd.QueryPersonRequest.QueryEntryList; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.Nullable; -import javax.xml.bind.JAXBElement; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static at.gv.zustellung.tnvz.xsd.PersonQueryType.MetaData.metaDataBuilder; -import static at.gv.zustellung.tnvz.xsd.PersonQueryType.personQueryTypeBuilder; -import static at.gv.zustellung.tnvz.xsd.QueryPersonRequest.QueryEntryList.queryEntryListBuilder; -import static at.gv.zustellung.tnvz.xsd.QueryPersonRequest.queryPersonRequestBuilder; -import static at.gv.zustellung.tnvz.xsd.Receiver.receiverBuilder; -import static at.gv.zustellung.tnvz.xsd.Sender.senderBuilder; -import static java.lang.String.join; -import static java.util.stream.Collectors.toSet; - -@Component -public class TnvzHelper { - - private final Mzs2MsgConverter converter; - - private static final ObjectFactory FACTORY = new at.gv.zustellung.msg.xsd.persondata.ObjectFactory(); - private static final String ENTRY_ID = "entry-id"; - private static final String RECEIVER_NOT_ADRESSABLE_ERROR_MSG = "Receiver is not addressable. Reason: %s"; - private static final String MIMETYPE_MISSMATCH_ERROR_MSG = "Request contains attachment of type(s) %s, but " + - "receiver only accepts attachments of type(s) %s."; - private static final String MZS_NO_TNVZ_PERSON_QUERY_RESULTS_ERROR_MSG = "tnvz:QueryResultList was empty."; - - - @Autowired - public TnvzHelper(Mzs2MsgConverter converter) { - this.converter = converter; - } - - /** - * Performs all tasks related to making a request to the tnvz service: - * Derives a tnvz:QueryPersonRequest from the {@code mzsRequest}, sends the QueryPersonRequest to - * {@code tvnzPort}, validates the tnvz's response and extracts the {@code Identification} Element. - * @param mzsRequest Data source for the QueryPersonRequest - * @param tvnzPort Client for communicating with the tnvz service - * @param exceptionBuilder Utility to collect information and build a meaningful exception in case of errors. - * @throws MoaZSException in case of an error. - * @return - */ - public IdentificationType performQueryPersonRequest(DeliveryRequestType mzsRequest, - TNVZServicePort tvnzPort, - MoaZSException.Builder exceptionBuilder) { - - var tvnzQuery = buildQuery(mzsRequest); - var tvnzResponse = tvnzPort.queryPerson(tvnzQuery); - verifyResponse(tvnzResponse, exceptionBuilder); - - var tvnzResult = getResult(tvnzResponse); - var typesInRequest = extractListOfMimemtypesIn(mzsRequest); - checkMimetypes(tvnzResult, typesInRequest, exceptionBuilder); - - return tvnzResult.getSuccess().getIdentification(); - } - - private QueryPersonRequest buildQuery(DeliveryRequestType mzsRequest) { - - Sender sender = extractSender(mzsRequest.getSender()); - Receiver receiver = extractReceiver(mzsRequest.getReceiver()); - var metadata = extractMetaData(mzsRequest); - - PersonQueryType personQuery = personQueryTypeBuilder() - .withEntryID(ENTRY_ID) - .withSender(sender) - .withReceiver(receiver) - .withMetaData(metadata) - .build(); - - QueryEntryList entryList = queryEntryListBuilder() - .withQueryEntry(List.of(personQuery)) - .build(); - - return queryPersonRequestBuilder() - .withQueryEntryList(entryList) - .build(); - } - - private PersonQueryType.MetaData extractMetaData(DeliveryRequestType request) { - - var builder = metaDataBuilder(); - - var meta = request.getTnvzMetaData(); - - if (meta.getDeliveryQuality() != null) { - builder.withDeliveryQuality(meta.getDeliveryQuality()); - } else { - builder.withPrivateMessageQuality(meta.getPrivateMessageQuality()); - } - - return builder - .withOrigin(meta.getOrigin()) - .withPreAdviceNote(request.getReceiver().getPreAdviceNote()) - .withIgnorePostRedirectionOrder(meta.getIgnorePostRedirectionOrder()) - .build(); - } - - private Sender extractSender(DeliveryRequestType.Sender sender) { - - var corporateBody = sender.getCorporateBody(); - var mzsIdentification = corporateBody.getIdentification().get(0); - var msgIdentification = converter.convert(mzsIdentification); - - var msgPerson = FACTORY.createPerson(converter.convert(corporateBody)); - - return senderBuilder() - .withIdentification(msgIdentification) - .withPerson(msgPerson) - .build(); - } - - private Receiver extractReceiver(DeliveryRequestType.Receiver receiver) { - - var builder = receiverBuilder(); - - if (receiver.getIdentification() == null) { - builder - .withPerson(converter.convert(receiver.getPerson())) - .withAustrianAddressesOnly(receiver.getAustrianAddressesOnly()); - - var postalAddress = findPostalAddress(receiver.getAddress()); - if (postalAddress != null) - builder.withPostalAddress(postalAddress); - - if (receiver.getPreAdviceNote() != null) { - builder.withNotificationAddressList(receiver.getPreAdviceNote().getNotificationAddressList()); - } - } else { - builder.withIdentification(converter.convert(receiver.getIdentification())); - } - - return builder.build(); - } - - private @Nullable PostalAddressType findPostalAddress(List> addresses) { - - if (addresses == null) return null; - - for (JAXBElement address : addresses) { - if(address.getValue() instanceof at.gv.zustellung.app2mzs.xsd.persondata.PostalAddressType) { - var mzsPostalAddress = (at.gv.zustellung.app2mzs.xsd.persondata.PostalAddressType) address.getValue(); - return converter.convert(mzsPostalAddress); - } - } - - return null; - - } - - private Set extractListOfMimemtypesIn(DeliveryRequestType mzsRequest) { - return mzsRequest.getPayload().stream() - .map(DeliveryRequestType.Payload::getMIMEType) - .collect(toSet()); - } - - private void verifyResponse(QueryPersonResponse tvnzResponse, MoaZSException.Builder mzsBuilder) { - - var error = tvnzResponse.getError(); - if (error != null) { - throw mzsBuilder.withErrorCode(error.getCode()) - .withMessage(error.getText()) - .build(); - } - - var results = tvnzResponse.getQueryResultList().getQueryResult(); - if (results.isEmpty()) { - throw mzsBuilder.withErrorCode(MoaZSException.ERROR_MZS_NO_TNVZ_PERSON_QUERY_RESULTS) - .withMessage(MZS_NO_TNVZ_PERSON_QUERY_RESULTS_ERROR_MSG) - .build(); - } - - var tnvzResult = results.get(0); - mzsBuilder.withTnvzResult(tnvzResult); - if (tnvzResult.getError() != null) { - var info = tnvzResult.getError().getErrorInfo(); - throw mzsBuilder.withErrorCode(info.getCode()) - .withMessage(RECEIVER_NOT_ADRESSABLE_ERROR_MSG, info.getText()) - .build(); - } - } - - private PersonResultType getResult(QueryPersonResponse tvnzResponse) { - return tvnzResponse.getQueryResultList().getQueryResult().get(0); - } - - private void checkMimetypes(PersonResultType tnvzResult, Set typesInRequest, MoaZSException.Builder mzsBuilder) { - var mismatchedTypes = findMimeTypeMismatches(tnvzResult, typesInRequest); - if (!mismatchedTypes.isEmpty()) { - var acceptedTypesString = join(",", getAcceptedTypes(tnvzResult)); - var mismatchedTypesString = join(",", mismatchedTypes); - throw mzsBuilder.withErrorCode(MoaZSException.ERROR_MZS_MIMETYPE_MISSMATCH) - .withMessage(MIMETYPE_MISSMATCH_ERROR_MSG, mismatchedTypesString, acceptedTypesString) - .build(); - } - } - - private Collection findMimeTypeMismatches(PersonResultType result, Set typesInRequest) { - var acceptedTypes = getAcceptedTypes(result); - - if (acceptedTypes.contains("*/*")) { - return List.of(); - } - - var typesInRequestCopy = new HashSet<>(typesInRequest); - typesInRequestCopy.removeAll(acceptedTypes); - - return typesInRequestCopy; - } - - private List getAcceptedTypes(PersonResultType result) { - return result.getSuccess().getMimeTypeList().getMimeType(); - } - - -} diff --git a/src/main/java/at/gv/egiz/moazs/service/MsgService.java b/src/main/java/at/gv/egiz/moazs/service/MsgService.java new file mode 100644 index 0000000..93f1ed5 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/service/MsgService.java @@ -0,0 +1,74 @@ +package at.gv.egiz.moazs.service; +import at.gv.egiz.moazs.process.MsgResponseHandler; +import at.gv.egiz.moazs.repository.DeliveryRepository; +import at.gv.egiz.moazs.scheme.MsgResponse; +import at.gv.egiz.moazs.scheme.NameSpace; +import at.gv.egiz.moazs.scheme.NotificationResponse; +import at.gv.egiz.moazs.scheme.RequestStatusResponse; +import at.gv.zustellung.msg.xsd.*; +import org.apache.cxf.annotations.SchemaValidation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import static at.gv.zustellung.msg.xsd.DeliveryNotificationACKType.deliveryNotificationACKTypeBuilder; +import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusACKType.deliveryRequestStatusACKTypeBuilder; +import static at.gv.zustellung.msg.xsd.GetVersionResponse.getVersionResponseBuilder; +import static java.util.concurrent.CompletableFuture.runAsync; + +@Service +@SchemaValidation(type = SchemaValidation.SchemaValidationType.BOTH) +public class MsgService implements Zuse2AppPort { + + private final DeliveryRepository repository; + private final MsgResponseHandler handler; + + @Autowired + public MsgService(DeliveryRepository repository, MsgResponseHandler handler) { + this.repository = repository; + this.handler = handler; + } + + @Override + public GetVersionResponse getVersion(SimpleRequestType getVersionRequest) { + return getVersionResponseBuilder() + .withVersion(NameSpace.MSG_VERSION) + .build(); + } + + @Override + public DeliveryRequestStatusACKType status(DeliveryRequestStatusType status) { + var response = new RequestStatusResponse(status); + sendToWork(response); + return statusAck(response.getAppDeliveryID(), response.getZSDeliveryID()); + } + + private DeliveryRequestStatusACKType statusAck(String appDeliveryID, String zsDeliveryID) { + return deliveryRequestStatusACKTypeBuilder() + .withAppDeliveryID(appDeliveryID) + .withZSDeliveryID(zsDeliveryID) + .withVersion(NameSpace.MSG_VERSION) + .build(); + } + + @Override + public DeliveryNotificationACKType notification(DeliveryNotificationType notification) { + var response = new NotificationResponse(notification); + sendToWork(response); + return notificationAck(response.getAppDeliveryID(), response.getZSDeliveryID()); + } + + private void sendToWork(MsgResponse response) { + runAsync(() -> repository.add(response)) + .thenRunAsync(() -> handler.handle(response.getResponseID())); + } + + private DeliveryNotificationACKType notificationAck(String appDeliveryID, String zsDeliveryID) { + return deliveryNotificationACKTypeBuilder() + .withAppDeliveryID(appDeliveryID) + .withZSDeliveryID(zsDeliveryID) + .withVersion(NameSpace.MSG_VERSION) + .build(); + } + + +} diff --git a/src/main/java/at/gv/egiz/moazs/service/MzsService.java b/src/main/java/at/gv/egiz/moazs/service/MzsService.java new file mode 100644 index 0000000..c41740f --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/service/MzsService.java @@ -0,0 +1,112 @@ +package at.gv.egiz.moazs.service; + +import at.gv.egiz.moazs.preprocess.DeliveryRequestAugmenter; +import at.gv.egiz.moazs.process.DeliveryPipeline; +import at.gv.egiz.moazs.repository.BinaryRepository; +import at.gv.egiz.moazs.repository.DeliveryRepository; +import at.gv.egiz.moazs.scheme.Msg2MzsConverter; +import at.gv.egiz.moazs.client.MzsClient; +import at.gv.egiz.moazs.scheme.RequestStatusResponse; +import at.gv.zustellung.app2mzs.xsd.App2MzsPortType; +import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; +import at.gv.zustellung.app2mzs.xsd.DeliveryResponseType; +import at.gv.zustellung.msg.xsd.DeliveryRequestStatusType; +import org.apache.cxf.annotations.SchemaValidation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.jws.WebParam; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static at.gv.egiz.moazs.MoaZSException.moaZSException; +import static at.gv.egiz.moazs.MoaZSException.moaZSExceptionBuilder; +import static at.gv.zustellung.app2mzs.xsd.PartialSuccessType.partialSuccessTypeBuilder; +import static java.util.concurrent.CompletableFuture.supplyAsync; + +//todo : validate Schema in both directions. +@Service +@SchemaValidation(type = SchemaValidation.SchemaValidationType.IN) +public class MzsService implements App2MzsPortType { + + private static final Logger logger = LoggerFactory.getLogger(MzsService.class); + + //TODO move timeout and namespaces to config + private static final int TIMEOUT_FOR_ANWSER = 10; + + private final DeliveryRepository repository; + private final DeliveryPipeline pipeline; + private final MzsClient appClient; + private final DeliveryRequestAugmenter augmenter; + private final Msg2MzsConverter converter; + private final BinaryRepository binaryStatusRepository; + + @Autowired + public MzsService(DeliveryRepository repository, DeliveryPipeline pipeline, MzsClient appClient, + DeliveryRequestAugmenter augmenter, Msg2MzsConverter converter, BinaryRepository binaryStatusRepository) { + this.repository = repository; + this.pipeline = pipeline; + this.appClient = appClient; + this.augmenter = augmenter; + this.converter = converter; + this.binaryStatusRepository = binaryStatusRepository; + } + + @Override + public DeliveryResponseType app2Mzs( + @WebParam(partName = "DeliveryRequest", + name = "DeliveryRequest") + DeliveryRequestType deliveryRequest) { + + var appDeliveryID = deliveryRequest.getMetaData().getAppDeliveryID(); + var responseID = RequestStatusResponse.getResponseID(appDeliveryID); + + var future = supplyAsync(() -> augmenter.augment(deliveryRequest)) + .thenApply(this::process) + .thenApply(status -> converter.convert(status, binaryStatusRepository.get(responseID))); + + try { + return future.get(TIMEOUT_FOR_ANWSER, TimeUnit.SECONDS); + } catch (TimeoutException e) { + logger.info("Answer Timed Out", e); + + future.thenAccept(appClient::sendNotification); + return generatePartialSuccessResponse(appDeliveryID); + + } catch (Exception e) { + throw moaZSExceptionBuilder("An error occurred while processing DeliveryRequest " + + "with AppDeliveryID=%s.", appDeliveryID) + .withCause(e) + .build(); + } + + } + + private DeliveryRequestStatusType process(DeliveryRequestType deliveryRequest) { + + var appDeliveryID = deliveryRequest.getMetaData().getAppDeliveryID(); + logger.info("Receive request with appDeliveryID = {}.", appDeliveryID); + + repository.add(deliveryRequest); + pipeline.processRequest(appDeliveryID); + + var statusId = RequestStatusResponse.getResponseID(appDeliveryID); + var response = repository.getResponse(statusId) + .orElseThrow(() -> moaZSException("Could not get a response for AppDeliveryID=%s.", appDeliveryID)); + return (DeliveryRequestStatusType) response.getResponse(); + } + + private DeliveryResponseType generatePartialSuccessResponse(String appDeliveryId) { + + var partial = partialSuccessTypeBuilder() + .withAppDeliveryID(appDeliveryId) + .build(); + + return DeliveryResponseType.deliveryResponseTypeBuilder() + .withPartialSuccess(partial) + .build(); + } + +} diff --git a/src/main/java/at/gv/egiz/moazs/util/ClientFactory.java b/src/main/java/at/gv/egiz/moazs/util/ClientFactory.java index e7761fe..d0a445b 100644 --- a/src/main/java/at/gv/egiz/moazs/util/ClientFactory.java +++ b/src/main/java/at/gv/egiz/moazs/util/ClientFactory.java @@ -1,5 +1,7 @@ -package at.gv.egiz.moazs.util; +package at.gv.egiz.moazs.client; +import at.gv.egiz.moazs.util.FileUtils; +import at.gv.egiz.moazs.util.StoreSOAPBodyBinaryInRepositoryInterceptor; import at.gv.zustellung.app2mzs.xsd.ClientType; import at.gv.zustellung.app2mzs.xsd.KeyStoreType; import at.gv.zustellung.app2mzs.xsd.SSLType; diff --git a/src/main/java/at/gv/egiz/moazs/util/EndpointFactory.java b/src/main/java/at/gv/egiz/moazs/util/EndpointFactory.java new file mode 100644 index 0000000..24321e1 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/util/EndpointFactory.java @@ -0,0 +1,41 @@ +package at.gv.egiz.moazs.util; + +import org.apache.cxf.Bus; +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.jaxws.EndpointImpl; +import org.apache.cxf.message.Message; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import javax.xml.ws.Endpoint; + +import javax.xml.ws.Service; + +@Component +public class EndpointFactory { + + private final Bus bus; + + @Autowired + public EndpointFactory(Bus bus) { + this.bus = bus; + } + + public Endpoint create(Object implementor, Service service) { + return create(implementor, service, null); + } + + public Endpoint create(Object implementor, Service service, Interceptor interceptor) { + EndpointImpl endpoint = new EndpointImpl(bus, implementor); + endpoint.setAddress("/"); + endpoint.setServiceName(service.getServiceName()); + endpoint.setWsdlLocation(service.getWSDLDocumentLocation().toString()); + endpoint.publish(); + + if (interceptor != null) { + endpoint.getInInterceptors().add(interceptor); + } + + return endpoint; + } + +} diff --git a/src/main/java/at/gv/egiz/moazs/util/SSLContextCreator.java b/src/main/java/at/gv/egiz/moazs/util/SSLContextCreator.java index 302bbf0..8fb5d80 100644 --- a/src/main/java/at/gv/egiz/moazs/util/SSLContextCreator.java +++ b/src/main/java/at/gv/egiz/moazs/util/SSLContextCreator.java @@ -1,4 +1,4 @@ -package at.gv.egiz.moazs.util; +package at.gv.egiz.moazs.client; import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; import at.gv.zustellung.app2mzs.xsd.KeyStoreType; diff --git a/src/main/java/at/gv/egiz/moazs/util/StoreSOAPBodyBinaryInRepositoryInterceptor.java b/src/main/java/at/gv/egiz/moazs/util/StoreSOAPBodyBinaryInRepositoryInterceptor.java index 2db81ab..d70c8bd 100644 --- a/src/main/java/at/gv/egiz/moazs/util/StoreSOAPBodyBinaryInRepositoryInterceptor.java +++ b/src/main/java/at/gv/egiz/moazs/util/StoreSOAPBodyBinaryInRepositoryInterceptor.java @@ -1,6 +1,6 @@ package at.gv.egiz.moazs.util; -import at.gv.egiz.moazs.repository.DeliveryRepository; +import at.gv.egiz.moazs.repository.BinaryRepository; import at.gv.egiz.moazs.scheme.SOAPUtils; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; @@ -15,6 +15,7 @@ import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.Map; import static at.gv.egiz.moazs.MoaZSException.moaZSException; @@ -25,14 +26,16 @@ public class StoreSOAPBodyBinaryInRepositoryInterceptor extends AbstractPhaseInt private final CXFMessageUtils messageUtils; private final SOAPUtils soapUtils; - private final DeliveryRepository repository; + private final Map idSuffixes; + private final BinaryRepository repository; @Autowired public StoreSOAPBodyBinaryInRepositoryInterceptor(CXFMessageUtils extractor, SOAPUtils soapUtils, - DeliveryRepository repository) { + Map idSuffixes, BinaryRepository repository) { super(Phase.RECEIVE); this.messageUtils = extractor; this.soapUtils = soapUtils; + this.idSuffixes = idSuffixes; this.repository = repository; } @@ -45,17 +48,28 @@ public class StoreSOAPBodyBinaryInRepositoryInterceptor extends AbstractPhaseInt log.trace("Interceptor received this SOAP message: {}. ", new String(content, StandardCharsets.UTF_8)); } - if(content.length > 0) { - Element document = soapUtils.toDOM(content); - byte[] status = soapUtils.unwrapSoapEnvelope(document); - String appDeliveryID = soapUtils.getAppDeliveryIDFrom(document); - repository.addSignedDeliveryRequestStatus(status, appDeliveryID); + if (content.length <= 0) { + return; + } + + Element document = soapUtils.toDOM(content); + byte[] response = soapUtils.unwrapSoapEnvelope(document); + String appDeliveryID = soapUtils.getAppDeliveryIDFrom(document); + String rootTag = document.getTagName(); - if(log.isTraceEnabled()) { - log.trace("DeliveryRequestStatus with AppDeliveryID={} unwrapped and stored: {}. ", - appDeliveryID, new String(status, StandardCharsets.UTF_8)); - } + if (!idSuffixes.containsKey(rootTag)) { + log.trace("Will not add message of type {}. ", rootTag); + return; } + + var id = appDeliveryID + idSuffixes.get(rootTag); + repository.add(id, response); + + if(log.isTraceEnabled()) { + log.trace("Msg Response with AppDeliveryID={} unwrapped and stored: {}. ", + appDeliveryID, new String(response, StandardCharsets.UTF_8)); + } + } catch (ParserConfigurationException | SAXException | IOException | NullPointerException e) { throw moaZSException("Could not extract signed data from message.", e); } diff --git a/src/main/java/at/gv/egiz/moazs/verify/MsgResponseVerifier.java b/src/main/java/at/gv/egiz/moazs/verify/MsgResponseVerifier.java new file mode 100644 index 0000000..c5e04d9 --- /dev/null +++ b/src/main/java/at/gv/egiz/moazs/verify/MsgResponseVerifier.java @@ -0,0 +1,59 @@ +package at.gv.egiz.moazs.verify; + +import at.gv.egiz.moazs.MoaZSException; +import at.gv.egiz.moazs.repository.BinaryRepository; +import at.gv.egiz.moazs.repository.DeliveryRepository; +import at.gv.egiz.moazs.scheme.MsgResponse; +import at.gv.egiz.moazs.service.MsgService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import static at.gv.egiz.moazs.MoaZSException.moaZSExceptionBuilder; +import static java.lang.String.format; + +@Component +public class MsgResponseVerifier { + + private static final Logger log = LoggerFactory.getLogger(MsgService.class); + public static final String MOASP_SIGNATURE_INVALID_ERROR_MSG = "Signature of Msg Response " + + "with AppDeliveryID=%s is not valid."; + + private final DeliveryRepository repo; + private final BinaryRepository binaryRepo; + private final SignatureVerifier verifier; + + @Autowired + public MsgResponseVerifier(DeliveryRepository repo, + BinaryRepository binaryStatusRepository, + SignatureVerifier verifier) { + this.repo = repo; + this.binaryRepo = binaryStatusRepository; + this.verifier = verifier; + } + + public MsgResponse verify(String id) { + + var response = repo.getResponse(id).get(); + var builder = moaZSExceptionBuilder().withAllParametersInAnswer(response.getAnswer()); + + var binaryResponse = binaryRepo.get(id).get(); + + try { + verifier.verify(binaryResponse); + return response; + } catch (MoaZSException ex) { + log.error(ex.getMessage(), ex); + var wrappingEx = builder + .withMessage(format(MOASP_SIGNATURE_INVALID_ERROR_MSG, response.getAppDeliveryID())) + .withErrorCode(MoaZSException.ERROR_MOASP_SIGNATURE_INVALID) + .withCause(ex) + .build(); + + return response.generateError(wrappingEx); + } + + } + +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 1903067..ca8221c 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -72,3 +72,7 @@ moa.spss: # - relative path (otherwise, relative to application's class path) configuration: moa-spss/MOASPSSConfiguration.xml default-trustprofile: test-trustprofile + +repository: + # duration in minutes before repository records are evicted. + expiresAfterWrite: 30 \ No newline at end of file diff --git a/src/main/resources/zusemsg/zuse2app_p2.wsdl b/src/main/resources/zusemsg/zuse2app_p2.wsdl new file mode 100644 index 0000000..d50c3cc --- /dev/null +++ b/src/main/resources/zusemsg/zuse2app_p2.wsdl @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/java/at/gv/egiz/moazs/ConfigProfileGeneratorTest.java b/src/test/java/at/gv/egiz/moazs/ConfigProfileGeneratorTest.java index ff981a9..f408c3b 100644 --- a/src/test/java/at/gv/egiz/moazs/ConfigProfileGeneratorTest.java +++ b/src/test/java/at/gv/egiz/moazs/ConfigProfileGeneratorTest.java @@ -1,6 +1,6 @@ package at.gv.egiz.moazs; -import at.gv.egiz.moazs.scheme.MzsDeliveryRequestValidator; +import at.gv.egiz.moazs.preprocess.MzsDeliveryRequestValidator; import at.gv.egiz.moazs.preprocess.*; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/src/test/java/at/gv/egiz/moazs/DeliveryRequestAugmenterTest.java b/src/test/java/at/gv/egiz/moazs/DeliveryRequestAugmenterTest.java index 3bc0d3b..12f1dea 100644 --- a/src/test/java/at/gv/egiz/moazs/DeliveryRequestAugmenterTest.java +++ b/src/test/java/at/gv/egiz/moazs/DeliveryRequestAugmenterTest.java @@ -1,6 +1,6 @@ package at.gv.egiz.moazs; -import at.gv.egiz.moazs.scheme.MzsDeliveryRequestValidator; +import at.gv.egiz.moazs.preprocess.MzsDeliveryRequestValidator; import at.gv.egiz.moazs.preprocess.ConfigUtil; import at.gv.egiz.moazs.preprocess.DeliveryRequestAugmenter; import at.gv.zustellung.app2mzs.xsd.ConfigType; diff --git a/src/test/java/at/gv/egiz/moazs/ITMsgClientTest.java b/src/test/java/at/gv/egiz/moazs/ITMsgClientTest.java index 70e300c..0f87dd6 100644 --- a/src/test/java/at/gv/egiz/moazs/ITMsgClientTest.java +++ b/src/test/java/at/gv/egiz/moazs/ITMsgClientTest.java @@ -1,6 +1,6 @@ package at.gv.egiz.moazs; -import at.gv.egiz.moazs.util.ClientFactory; +import at.gv.egiz.moazs.client.ClientFactory; import at.gv.egiz.moazs.scheme.Marshaller; import at.gv.zustellung.app2mzs.xsd.ClientType; import at.gv.zustellung.app2mzs.xsd.KeyStoreType; diff --git a/src/test/java/at/gv/egiz/moazs/ITMzsServiceTest.java b/src/test/java/at/gv/egiz/moazs/ITMzsServiceTest.java index 4f24518..22aa03f 100644 --- a/src/test/java/at/gv/egiz/moazs/ITMzsServiceTest.java +++ b/src/test/java/at/gv/egiz/moazs/ITMzsServiceTest.java @@ -1,7 +1,8 @@ package at.gv.egiz.moazs; -import at.gv.egiz.moazs.pipeline.DeliveryPipeline; +import at.gv.egiz.moazs.process.DeliveryPipeline; import at.gv.egiz.moazs.repository.DeliveryRepository; +import at.gv.egiz.moazs.scheme.RequestStatusResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; @@ -63,7 +64,7 @@ public class ITMzsServiceTest { .withSuccess(success) .build(); - repository.add(status); + repository.add(new RequestStatusResponse(status)); }; } diff --git a/src/test/java/at/gv/egiz/moazs/SafeResponseToFileSinkTest.java b/src/test/java/at/gv/egiz/moazs/SafeResponseToFileSinkTest.java new file mode 100644 index 0000000..9092dfb --- /dev/null +++ b/src/test/java/at/gv/egiz/moazs/SafeResponseToFileSinkTest.java @@ -0,0 +1,113 @@ +package at.gv.egiz.moazs; + +import at.gv.egiz.moazs.process.SafeResponseToFileSink; +import at.gv.egiz.moazs.repository.BinaryRepository; +import at.gv.egiz.moazs.scheme.Marshaller; +import at.gv.egiz.moazs.scheme.RequestStatusResponse; +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collection; + +import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.Success.successBuilder; +import static at.gv.zustellung.msg.xsd.DeliveryRequestStatusType.deliveryRequestStatusTypeBuilder; +import static java.util.Optional.of; +import static org.apache.commons.io.FileUtils.readFileToString; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SafeResponseToFileSinkTest { + + private static final Logger log = LoggerFactory.getLogger(SafeResponseToFileSinkTest.class); + + private SafeResponseToFileSink sink; + + private final String root = "./target/tmp/SafeResponseToFileSinkTestOut"; + + @Mock + private BinaryRepository repository; + + @Mock + private Marshaller marshaller; + + + @Before + public void setup() { + sink = new SafeResponseToFileSink(marshaller, repository, root); + deleteRoot(); + + } + + private void deleteRoot() { + try { + FileUtils.deleteDirectory(new File(root)); + } catch (IOException e) { + log.warn("Could not delete {}", root); + } + } + + @Test + public void safeRequestToFiles() { + + var fileContent = "some content"; + var status = setupMocks(fileContent); + + sink.handle(status) + .thenRun(() -> assertFilesCreatedAndContentMatches(fileContent)); + } + + private void assertFilesCreatedAndContentMatches(String fileContent) { + var rootFolder = new File(root); + Collection files = FileUtils.listFiles(rootFolder, null, true); + + assertThat(rootFolder.exists()).isTrue(); + assertThat(rootFolder.isDirectory()).isTrue(); + assertThat(files).isNotEmpty(); + + files.stream() + .map(file -> readFile(file)) + .forEach(content -> assertThat(content).isEqualTo(fileContent)); + } + + private String readFile(File file) { + try { + return readFileToString(file, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private RequestStatusResponse setupMocks(String fileContent) { + + var appDeliveryId = "app-delivery-id"; + var responseId = RequestStatusResponse.getResponseID(appDeliveryId); + + when(repository.get(responseId)) + .thenReturn(of(fileContent.getBytes(StandardCharsets.UTF_8))); + when(marshaller.marshallXml(any())).thenReturn(fileContent); + + var success = successBuilder() + .withAppDeliveryID(appDeliveryId) + .build(); + + var status = deliveryRequestStatusTypeBuilder() + .withSuccess(success) + .build(); + + return new RequestStatusResponse(status); + + + } + +} diff --git a/src/test/java/at/gv/egiz/moazs/SingleThreadedDeliveryPipelineTest.java b/src/test/java/at/gv/egiz/moazs/SingleThreadedDeliveryPipelineTest.java index c08d567..e145cd9 100644 --- a/src/test/java/at/gv/egiz/moazs/SingleThreadedDeliveryPipelineTest.java +++ b/src/test/java/at/gv/egiz/moazs/SingleThreadedDeliveryPipelineTest.java @@ -1,12 +1,14 @@ package at.gv.egiz.moazs; -import at.gv.egiz.moazs.util.ClientFactory; -import at.gv.egiz.moazs.pipeline.DeliveryPipeline; -import at.gv.egiz.moazs.pipeline.SingleThreadedDeliveryPipeline; +import at.gv.egiz.moazs.process.DeliveryPipeline; +import at.gv.egiz.moazs.process.SingleThreadedDeliveryPipeline; +import at.gv.egiz.moazs.client.TnvzHelper; +import at.gv.egiz.moazs.repository.BinaryRepository; +import at.gv.egiz.moazs.repository.InMemoryBinaryRepository; +import at.gv.egiz.moazs.scheme.*; +import at.gv.egiz.moazs.client.ClientFactory; import at.gv.egiz.moazs.repository.DeliveryRepository; import at.gv.egiz.moazs.repository.InMemoryDeliveryRepository; -import at.gv.egiz.moazs.scheme.Mzs2MsgConverter; -import at.gv.egiz.moazs.scheme.TnvzHelper; import at.gv.egiz.moazs.verify.MoaSPSSSignatureVerifier; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; import at.gv.zustellung.msg.xsd.App2ZusePort; @@ -22,6 +24,7 @@ import org.mockito.junit.MockitoJUnitRunner; import static at.gv.egiz.moazs.MoaZSException.moaZSException; import static at.gv.egiz.moazs.MoaZSException.moaZSExceptionBuilder; +import static at.gv.egiz.moazs.scheme.RequestStatusResponse.getResponseID; import static at.gv.zustellung.app2mzs.xsd.ClientType.clientTypeBuilder; import static at.gv.zustellung.app2mzs.xsd.ConfigType.configTypeBuilder; import static at.gv.zustellung.app2mzs.xsd.DeliveryRequestType.deliveryRequestTypeBuilder; @@ -37,6 +40,7 @@ import static org.mockito.Mockito.*; public class SingleThreadedDeliveryPipelineTest { private DeliveryRepository repository = new InMemoryDeliveryRepository(); + private BinaryRepository binaryRepository = new InMemoryBinaryRepository(30); @Mock private TnvzHelper tnvzHelper; @@ -61,57 +65,70 @@ public class SingleThreadedDeliveryPipelineTest { @Before public void setup() { - pipeline = new SingleThreadedDeliveryPipeline(repository, tnvzHelper, converter, clientFactory, verifier); + pipeline = new SingleThreadedDeliveryPipeline( + repository, + binaryRepository, + tnvzHelper, + converter, + clientFactory, + verifier); } @Test public void executePipelineWithoutTnvzRequest() { - var appDeliveryId = "no-tnvz-request"; - var expectedStatus = setupMocks(appDeliveryId, false); + var appDeliveryID = "no-tnvz-request"; + var expectedStatus = setupMocks(appDeliveryID, false); - pipeline.processRequest(appDeliveryId); + pipeline.processRequest(appDeliveryID); verifyZeroInteractions(tnvzHelper); - var actualStatus = repository.getDeliveryRequestStatus(appDeliveryId).get(); + var response = repository.getResponse(getResponseID(appDeliveryID)).get(); + var actualStatus = (DeliveryRequestStatusType) response.getResponse(); assertThat(actualStatus).isEqualTo(expectedStatus); } @Test public void rejectDeliveryWhenReceiverIsNotAddressable() { - var appDeliveryId = "not-addressable"; - setupMocks(appDeliveryId, true); + var appDeliveryID = "not-addressable"; + setupMocks(appDeliveryID, true); when(tnvzHelper.performQueryPersonRequest(any(), any(), any())) - .thenThrow(buildMzsException("400")); + .thenThrow(buildMzsException("400", appDeliveryID)); - pipeline.processRequest(appDeliveryId); - var actualCode = repository.getDeliveryRequestStatus(appDeliveryId).get() - .getError().getErrorInfo().getCode(); + pipeline.processRequest(appDeliveryID); + + var responseId = getResponseID(appDeliveryID); + var response = repository.getResponse(responseId).get(); + var status = (DeliveryRequestStatusType) response.getResponse(); + var actualCode = status.getError().getErrorInfo().getCode(); - verify(tnvzHelper).performQueryPersonRequest(any(), any(), any()); assertThat(actualCode).isEqualTo("400"); + verifyZeroInteractions(converter); + verify(tnvzHelper).performQueryPersonRequest(any(), any(), any()); } @Test public void executePipelineWithTnvzRequest() { - var appDeliveryId = "tnvz-request"; - var expectedStatus = setupMocks(appDeliveryId, true); + var appDeliveryID = "tnvz-request"; + var expectedStatus = setupMocks(appDeliveryID, true); - pipeline.processRequest(appDeliveryId); - var actualStatus = repository.getDeliveryRequestStatus(appDeliveryId).get(); + pipeline.processRequest(appDeliveryID); + var response = repository.getResponse(getResponseID(appDeliveryID)).get(); + var actualStatus = (DeliveryRequestStatusType) response.getResponse(); assertThat(actualStatus).isEqualTo(expectedStatus); } @Test public void rejectInvalidSignature() { - var appDeliveryId = "invalid-signature"; - setupMocks(appDeliveryId, true); + var appDeliveryID = "invalid-signature"; + setupMocks(appDeliveryID, true); doThrow(moaZSException("Signature Invalid!")).when(verifier).verify(any()); - pipeline.processRequest(appDeliveryId); - var actualCode = repository.getDeliveryRequestStatus(appDeliveryId).get() - .getError().getErrorInfo().getCode(); + pipeline.processRequest(appDeliveryID); + var response = repository.getResponse(getResponseID(appDeliveryID)).get(); + var status = (DeliveryRequestStatusType) response.getResponse(); + var actualCode = status.getError().getErrorInfo().getCode(); assertThat(actualCode).isEqualTo(MoaZSException.ERROR_MOASP_SIGNATURE_INVALID); @@ -125,7 +142,7 @@ public class SingleThreadedDeliveryPipelineTest { var signedStatus = new byte[0]; var identification = IdentificationType.identificationTypeBuilder().build(); repository.add(mzsRequest); - repository.addSignedDeliveryRequestStatus(signedStatus, appDeliveryId); + binaryRepository.add(getResponseID(appDeliveryId), signedStatus); when(converter.convert(eq(mzsRequest) )).thenReturn(msgRequest); when(converter.convert(eq(mzsRequest), any())).thenReturn(msgRequest); @@ -140,8 +157,11 @@ public class SingleThreadedDeliveryPipelineTest { } - private MoaZSException buildMzsException(String code) { - return moaZSExceptionBuilder("").withErrorCode(code).build(); + private MoaZSException buildMzsException(String code, String appDeliveryID) { + return moaZSExceptionBuilder("") + .withErrorCode(code) + .withAppDeliveryID(appDeliveryID) + .build(); } private DeliveryRequestStatusType setupStatus(String appDeliveryId) { diff --git a/src/test/java/at/gv/egiz/moazs/TnvzHelperTest.java b/src/test/java/at/gv/egiz/moazs/TnvzHelperTest.java index 66873d4..b58002b 100644 --- a/src/test/java/at/gv/egiz/moazs/TnvzHelperTest.java +++ b/src/test/java/at/gv/egiz/moazs/TnvzHelperTest.java @@ -2,7 +2,7 @@ package at.gv.egiz.moazs; import at.gv.egiz.moazs.scheme.Mzs2MsgConverter; -import at.gv.egiz.moazs.scheme.TnvzHelper; +import at.gv.egiz.moazs.client.TnvzHelper; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; import at.gv.zustellung.app2mzs.xsd.persondata.IdentificationType; import at.gv.zustellung.tnvz.xsd.MimeTypeList; -- cgit v1.2.3