input
stringlengths
994
101k
output
stringlengths
1.87k
81.8k
instruction
stringclasses
1 value
package com.intrasoft.ermis.transit.officeofdeparture.service; import static com.intrasoft.ermis.transit.common.util.TransitReflectionUtil.getCurrentMethod; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC013CType; import com.intrasoft.ermis.ddntav5152.messages.CC014CType; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CD050CType; import com.intrasoft.ermis.ddntav5152.messages.CD115CType; import com.intrasoft.ermis.ddntav5152.messages.CD118CType; import com.intrasoft.ermis.ddntav5152.messages.CD165CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.transit.bpmnshared.BpmnManagementService; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.enums.MessageOfficeTypeExpectedStatusesEnum; import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.exceptions.MessageOutOfOrderException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.contracts.core.enums.MessageXPathsEnum; import com.intrasoft.ermis.transit.contracts.core.enums.YesNoEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.Declaration; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.domain.ValidationResult; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnTimersEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.ProcessDefinitionEnum; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureFallbackDeclarationFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleAmendmentRequestFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleDestinationControlResultsFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleDiversionFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleIncidentNotificationFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleOfArrivalAdviceFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleRecoveryFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureInitializationFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureInvalidationFacade; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.xml.sax.InputSource; @Service @RequiredArgsConstructor public class HandleDDNTAMessageServiceImpl implements HandleDDNTAMessageService { public static final String STATE_VALIDATION_FAILED = "State validation failed"; public static final String IS_SEND_COPY_OF_CD006C_ENABLED_RS = "isSendCopyOfIE006EnabledRS"; public static final String SEND_COPY_OF_CD006C_ENABLED = "sendCopyOfIE006Enabled"; private final ErmisLogger log; private final MovementService movementService; private final DossierDataService dossierDataService; private final OoDepartureInitializationFacade ooDepartureInitializationFacade; private final OoDepartureInvalidationFacade ooDepartureInvalidationFacade; private final OoDepartureHandleOfArrivalAdviceFacade ooDepartureHandleOfArrivalAdviceFacade; private final OoDepartureHandleDestinationControlResultsFacade ooDepartureHandleDestinationControlResultsFacade; private final OoDepartureHandleAmendmentRequestFacade ooDepartureHandleAmendmentRequestFacade; private final OoDepartureHandleDiversionFacade ooDepartureHandleDiversionFacade; private final OoDepartureHandleIncidentNotificationFacade ooDepartureHandleIncidentNotificationFacade; private final OoDepartureHandleRecoveryFacade ooDepartureHandleRecoveryFacade; private final OoDepartureFallbackDeclarationFacade ooDepartureFallbackDeclarationFacade; private final GuaranteeService guaranteeService; private final InvalidationService invalidationService; private final BpmnManagementService bpmnManagementService; private final GenerateMessageService generateMessageService; private final InitializationService initializationService; private final EnquiryService enquiryService; private final FallbackDeclarationService fallbackDeclarationService; private final ProcessingStatusService processingStatusService; private final AmendmentRequestService amendmentRequestService; private final BpmnEngine bpmnEngine; private final ErmisConfigurationService ermisConfigurationService; public void handleDDNTAMessage(Movement movement, String movementId, String messageId, String messageType) throws MessageOutOfOrderException, JAXBException { MessageTypes messageTypeEnum = MessageTypes.fromValue(messageType); switch (messageTypeEnum) { case CD_006_C: movementService.checkForNullMovement(movement); processCD006C(movement, messageId); break; case CD_018_C: movementService.checkForNullMovement(movement); processCD018C(movement, messageId); break; case CD_027_C: movementService.checkForNullMovement(movement); processCD027C(movement, messageId); break; case CD_095_C: processCD095C(movementId, messageId); break; case CD_118_C: movementService.checkForNullMovement(movement); processCD118C(movement, messageId); break; case CD_143_C: movementService.checkForNullMovement(movement); processCD143C(movement, messageId); break; case CD_145_C: enquiryService.handleIE145Message(movementId, messageId); break; case CD_150_C: movementService.checkForNullMovement(movement); processCD150C(movement, messageId); break; case CD_151_C: movementService.checkForNullMovement(movement); processCD151C(movement, messageId); break; case CD_152_C: movementService.checkForNullMovement(movement); processCD152C(movement, messageId); break; case CD_168_C: movementService.checkForNullMovement(movement); processCD168C(movement, messageId); break; case CD_180_C: processCD180C(movementId, messageId); break; case CD_205_C: guaranteeService.onGuaranteeUseRegistrationCompleted(movementId, messageId); break; case CD_002_C: case CD_114_C: case CD_164_C: ooDepartureHandleDiversionFacade.initProcessInstance(movementId, messageId, messageType); break; case CC_013_C: movementService.checkForNullMovement(movement); processCC013C(movement, messageId); break; case CC_014_C: movementService.checkForNullMovement(movement); processCC014(movement, messageId); break; case CC_015_C: movementService.checkForNullMovement(movement); processCC015(movement, messageId); break; case CC_141_C: movementService.checkForNullMovement(movement); processCC141C(movement, messageId); break; case CC_170_C: ooDepartureInitializationFacade.handleIE170Message(movementId, messageId); break; case CC_191_C: initializationService.handleIE191Message(movementId, messageId); break; case CD_974_C: movementService.checkForNullMovement(movement); processCD974(movementId,messageId); break; default: log.warn("Received unhandled message type: {}. Message ignored.", messageType); break; } } // CD Message method: private void processCD006C(Movement movement, String messageId) { // TODO the states Enquiry Recommended and Under Enquiry Procedure // for the Office of Departure are not yet assignable in the current flow ProcessingStatusTypeEnum movementCurrentState = movementService.checkLatestState(movement.getId()); boolean isInStateMovementReleased = ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED == movementCurrentState; boolean recoveryRecommendedTimerIsActive = isRecoveryRecommendedTimerActive(movement); // ("Enquiry Recommended" OR "Under Enquiry Procedure OR Recovery Recommended") // AND NO IE006 has been received (only one (1) IE006 associated with Movement): boolean conditionalStatesValidWithNo006 = (ProcessingStatusTypeEnum.OODEP_ENQUIRY_RECOMMENDED == movementCurrentState || ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE == movementCurrentState || ProcessingStatusTypeEnum.OODEP_RECOVERY_RECOMMENDED == movementCurrentState ) && (dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_006_C.value()).size() == 1); if (isInStateMovementReleased || conditionalStatesValidWithNo006) { if (recoveryRecommendedTimerIsActive) { updateCountryAndOfficeOfDestinationOfMovement(movement, messageId); invalidationService.cancelInvalidationRequestIfExists(movement.getId()); ooDepartureHandleOfArrivalAdviceFacade.initProcessInstance(movement, messageId); } else { throw new MessageOutOfOrderException(getCurrentMethod(), "T_Recovery_Recommended timer is not Active"); } } else { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + " -> NOT (isInStateMovementReleased || conditionalStatesValidWithNo006)"); } boolean sendCopyOfCD006CMessage = false; try { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(IS_SEND_COPY_OF_CD006C_ENABLED_RS); sendCopyOfCD006CMessage = Boolean.parseBoolean(configuration.getEvaluationParams().get(SEND_COPY_OF_CD006C_ENABLED)); } catch (NotFoundException e) { log.warn(e.getMessage().concat(". Defaulting to false.")); } if (sendCopyOfCD006CMessage) { log.info("Going to send a copy of CD006C message."); generateMessageService.generateCopyOfIE006(movement.getId(), messageId); } else { log.info("Configuration value is false. Won't send a copy of CD006C message."); } } private void processCD018C(Movement movement, String messageId) throws MessageOutOfOrderException { // TODO The states Enquiry Recommended and Under Enquiry Procedure // for the Office of Departure are not yet assignable in the current flow Message message = dossierDataService.getMessageById(messageId); ProcessingStatusTypeEnum movementCurrentState = movementService.checkLatestState(movement.getId()); boolean isInStateMovementReleased = ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED == movementCurrentState; boolean isInStateArrived = ProcessingStatusTypeEnum.OODEP_ARRIVED == movementCurrentState; boolean ie006HasBeenReceived = dossierDataService.messageTypeExistsForMovement(movement.getId(), MessageTypes.CD_006_C); boolean recoveryRecommendedTimerIsActive = isRecoveryRecommendedTimerActive(movement); // ("Enquiry Recommended" OR "Under Enquiry Procedure" OR "Recovery Recommended") AND IE006 has been received: boolean conditionalStatesValidWithExisting006 = (ProcessingStatusTypeEnum.OODEP_ENQUIRY_RECOMMENDED == movementCurrentState || ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE == movementCurrentState || ProcessingStatusTypeEnum.OODEP_RECOVERY_RECOMMENDED == movementCurrentState ) && ie006HasBeenReceived; // ("Enquiry Recommended" OR "Under Enquiry Procedure") AND IE006 !!HAS NOT!! been received: boolean conditionalStatesValidWithout006 = (ProcessingStatusTypeEnum.OODEP_ENQUIRY_RECOMMENDED == movementCurrentState || ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE == movementCurrentState ) && !ie006HasBeenReceived; if (((isInStateArrived || conditionalStatesValidWithExisting006) && !message.isManualInserted()) || (message.isManualInserted() && (isInStateMovementReleased || conditionalStatesValidWithout006))) { if (recoveryRecommendedTimerIsActive) { // Check if process is already running for Movement's IE018: // (NOTE that for the given process, MRN is set as the processBusinessKey.) boolean isProcessInstanceAlreadyRunning = bpmnEngine.isProcessInstanceAlreadyRunning( ProcessDefinitionEnum.OODEPARTURE_HANDLE_DESTINATION_CONTROL_RESULTS.getProcessDefinitionKey(), movement.getMrn(), null); if (isProcessInstanceAlreadyRunning) { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED); } else { updateCountryAndOfficeOfDestinationOfMovement(movement, messageId); // If not already running, start it: ooDepartureHandleDestinationControlResultsFacade.initProcessInstance(movement, messageId); } } else { throw new MessageOutOfOrderException(getCurrentMethod(), "T_Recovery_Recommended timer is not Active"); } } else { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED); } } /** * Handles CD027 for known movement * * @param movement * @param messageId * @throws JAXBException */ private void processCD027C(Movement movement, String messageId) throws JAXBException { log.info("processCD027C() start..."); generateMessageService.generateIE038(movement.getId(), messageId); log.info("processCD027C() end : Generated IE038"); } private void processCD095C(String movementId, String messageId) { // Simple logger to verify arrival at office of Departure: log.info("IE095 with Movement ID: {} and Message ID: {} received!", movementId, messageId); } private void processCD118C(Movement movement, String messageId) { CD118CType cd118cMessage = dossierDataService.getDDNTAMessageById(messageId, CD118CType.class); // "Movement Released" OR... boolean movementReleased = movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED); // ("Enquiry Recommended" OR "Under Enquiry Procedure") AND NO IE006 has been received: boolean enquiryStateValid = (movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_ENQUIRY_RECOMMENDED) || movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE)) && dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_006_C.value()).isEmpty(); if (movementReleased || enquiryStateValid) { List<String> ie050IdList = dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_050_C.value()) .stream() .map(MessageOverview::getId) .collect(Collectors.toList()); List<String> ie115IdList = dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_115_C.value()) .stream() .map(MessageOverview::getId) .collect(Collectors.toList()); List<String> ie118IdList = dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_118_C.value()) .stream() .map(MessageOverview::getId) .collect(Collectors.toList()); // IE050 OR... boolean ie050Sent = checkIE050SentToCountry(ie050IdList, cd118cMessage.getCustomsOfficeOfTransitActual().getReferenceNumber()); // IE115 have been sent AND... boolean ie115Sent = checkIE115SentToCountry(ie115IdList, cd118cMessage.getCustomsOfficeOfTransitActual().getReferenceNumber()); // NO other IE118 has been received from that Office - list must have ONE item per Transit Office due to association: boolean noOtherIE118ReceivedFromTransitActual = checkNoOtherIE118ReceivedFromTransitActual(ie118IdList, cd118cMessage.getCustomsOfficeOfTransitActual().getReferenceNumber()); if ((ie050Sent || ie115Sent) && noOtherIE118ReceivedFromTransitActual) { log.info("Received IE118 by Office of Transit: {}", cd118cMessage.getCustomsOfficeOfTransitActual().getReferenceNumber()); invalidationService.cancelInvalidationRequestIfExists(movement.getId()); } else { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + " : NOT (ie050Sent && ie115Sent && noOtherIE118ReceivedFromTransitActual)"); } } else { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + " : NOT (movementReleased || enquiryStateValid)"); } } private void processCD143C(Movement movement, String messageId) { enquiryService.handleIE143Message(movement, messageId); } private void processCD150C(Movement movement, String messageId) { // State validation as in Management Microservice Set<String> allowedProcessingStatusItemCodes = MessageOfficeTypeExpectedStatusesEnum.getProcessingStatusItemCodesByMessageTypeAndRoleType(MessageTypes.CD_150_C, OfficeRoleTypesEnum.DEPARTURE); ProcessingStatusTypeEnum currentProcessingStatus = movementService.checkLatestState(movement.getId()); if (allowedProcessingStatusItemCodes.contains(currentProcessingStatus.getItemCode())) { invalidationService.cancelInvalidationRequestIfExists(movement.getId()); ooDepartureHandleRecoveryFacade.onCD150CMessageReceived(movement, messageId); } else { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + ": Movement state should be " + allowedProcessingStatusItemCodes + " but is " + movement.getProcessingStatus()); } } private void processCD151C(Movement movement, String messageId) { boolean isMovementInOoDepRecoveryRecommendedState = movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_RECOVERY_RECOMMENDED); if (isMovementInOoDepRecoveryRecommendedState) { ooDepartureHandleRecoveryFacade.onCD151CMessageReceived(movement, messageId); } else { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + ": Movement state should be " + ProcessingStatusTypeEnum.OODEP_RECOVERY_RECOMMENDED + " but is " + movement.getProcessingStatus()); } } private void processCD152C(Movement movement, String messageId) { if (movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_UNDER_RECOVERY_PROCEDURE)) { ooDepartureHandleRecoveryFacade.onCD152CCReceived(movement.getId(), messageId); } else { throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + " : NOT in -> " + ProcessingStatusTypeEnum.OODEP_UNDER_RECOVERY_PROCEDURE + " state"); } } private void processCD168C(Movement movement, String messageId) throws MessageOutOfOrderException { // Retrieve IE168 Message: Message ie168Message = dossierDataService.getMessageById(messageId); // Collect distinct NAs where IE160 and/or IE165 (positive) has been sent to. // IE160 countries: Set<String> countriesSent = dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_160_C.value()) .stream() .map(overview -> overview.getDestination().substring(overview.getDestination().length() - 2)) .collect(Collectors.toSet()); // IE165 (positive) countries: List<MessageOverview> ie165OverviewList = dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_165_C.value()); ie165OverviewList.forEach(overview -> { CD165CType cd165cType = dossierDataService.getDDNTAMessageById(overview.getId(), CD165CType.class); // IE165 is positive if it does not contain a RequestRejectionReasonCode: if (StringUtils.isEmpty(cd165cType.getTransitOperation().getRequestRejectionReasonCode())) { countriesSent.add(overview.getDestination().substring(overview.getDestination().length() - 2)); } }); // Send MessageOutOfOrder (IE906) if no IE160 or IE165 (positive) was sent to the NA of the IE168 sender: if (!countriesSent.contains(ie168Message.getSource().substring(ie168Message.getSource().length() - 2))) { dossierDataService.updateMessageStatus(ie168Message.getId(), MessageStatusEnum.REJECTED.name()); throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + ": National Authority of IE168 sender is invalid"); } // "Movement Released" OR... boolean movementReleasedState = movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED); // ("Enquiry Recommended" OR "Under Enquiry Procedure") AND NO IE006 has been received: boolean conditionalStatesValidWithout006 = (movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_ENQUIRY_RECOMMENDED) || movementService.checkIfInGivenState(movement.getId(), ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE)) && dossierDataService.getMessagesOverview(movement.getId(), MessageTypes.CD_006_C.value()).isEmpty(); if (movementReleasedState || conditionalStatesValidWithout006) { invalidationService.cancelInvalidationRequestIfExists(movement.getId()); } else { dossierDataService.updateMessageStatus(ie168Message.getId(), MessageStatusEnum.REJECTED.name()); throw new MessageOutOfOrderException(getCurrentMethod(), STATE_VALIDATION_FAILED + ": NOT (movementReleasedState || conditionalStatesValidWithout006)"); } } private void processCD180C(String movementId, String messageId) { invalidationService.cancelInvalidationRequestIfExists(movementId); ooDepartureHandleIncidentNotificationFacade.initProcessInstance(movementId, messageId); } // CC Message methods: private void processCC013C(Movement movement, String messageId) throws JAXBException { Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movement.getId()); boolean isFallbackDeclaration = false; if (declaration != null) { CC015CType cc015cTypeMessage = XmlConverter.buildMessageFromXML(declaration.getPayload(), CC015CType.class); isFallbackDeclaration = fallbackDeclarationService.isFallBackDeclaration(cc015cTypeMessage); } if (isThereAnAmendmentActiveForCurrentMovement(movement.getMrn(), ProcessDefinitionEnum.OODEPARTURE_HANDLE_AMENDMENT_REQUEST_PROCESS.getProcessDefinitionKey())) { createValidationResults(messageId, "An active amendment exists for given movement", "N/A", "N/A"); generateMessageService.generateIE056(movement.getId(), messageId, false, CC013CType.class); } else if (isFallbackDeclaration) { amendmentRequestService.amendDeclarationAndCreateNewVersion(movement.getId(), messageId, MessageTypes.CC_013_C.value(), true); } else { ooDepartureHandleAmendmentRequestFacade.initProcessInstance(movement, messageId); } } private void processCC014(Movement movement, String messageId) throws JAXBException { CC014CType cc014CType = dossierDataService.getDDNTAMessageById(messageId, CC014CType.class); Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movement.getId()); boolean isFallbackDeclaration = false; if (declaration != null) { CC015CType cc015cTypeMessage = XmlConverter.buildMessageFromXML(declaration.getPayload(), CC015CType.class); isFallbackDeclaration = fallbackDeclarationService.isFallBackDeclaration(cc015cTypeMessage); } if (invalidationService.isMovementBeforeRelease(movement)) { if (invalidationService.isInvalidationOnDemand(cc014CType)) { ooDepartureInvalidationFacade.initInvalidationProcess(movement, messageId, BpmnFlowMessagesEnum.IE014_FROM_CUSTOMS_OFFICER); } else { ooDepartureInvalidationFacade.initInvalidationProcess(movement, messageId, BpmnFlowMessagesEnum.IE014_FROM_TRADER); } } else if (invalidationService.isMovementAfterRelease(movement)) { ooDepartureInvalidationFacade.initOnDemandAfterReleaseProcessInstance(movement, messageId); } else if (isFallbackDeclaration) { processingStatusService.saveProcessingStatus(movement.getId(), ProcessingStatusTypeEnum.OODEP_PAPER_BASED_CANCELLED.getItemCode()); } else { throw new BaseException(String.format("Received manually IE014 in a status(%s) that cannot be processed", movement.getProcessingStatus())); } } private void processCC015(Movement movement, String messageId) throws JAXBException { // Ideally this should be done from within bpmn activity Message message = dossierDataService.getMessageById(messageId); CC015CType cc015CType = XmlConverter.buildMessageFromXML(message.getPayload(), CC015CType.class); Declaration declaration = Declaration.builder() .movementId(movement.getId()) .payloadType(message.getMessageType()) .payload(message.getPayload()) .build(); dossierDataService.createDeclaration(declaration); updateMovementWithDeclarationData(movement, message); if (fallbackDeclarationService.isFallBackDeclaration(cc015CType)) { ooDepartureFallbackDeclarationFacade.initProcessInstance(movement, messageId); } else { ooDepartureInitializationFacade.initProcessInstance(movement, messageId); } } private void processCC141C(Movement movement, String messageId) { enquiryService.handleIE141Message(movement, messageId); } private void processCD974(String movementId, String messageId) throws JAXBException { log.info("processCD974() start..."); generateMessageService.generateIE975(movementId,messageId); } private void updateMovementWithDeclarationData(Movement movement, Message message) { try { CC015CType cc015c = XmlConverter.buildMessageFromXML(message.getPayload(), CC015CType.class); YesNoEnum simplifiedProcedure = cc015c.getAuthorisation().stream() .filter(authorisation -> "C521".equals(authorisation.getType())) .findAny() .map(authorisationType02 -> YesNoEnum.YES) .orElse(YesNoEnum.NO); movement.setProcedureType(simplifiedProcedure.getValue()); movement.setDeclarationType(cc015c.getTransitOperation().getDeclarationType()); movement.setSubmitterIdentification(cc015c.getHolderOfTheTransitProcedure().getIdentificationNumber()); movement.setSecurity(cc015c.getTransitOperation().getSecurity()); movement.setOfficeOfDeparture(cc015c.getCustomsOfficeOfDeparture().getReferenceNumber()); movement.setOfficeOfDestination(cc015c.getCustomsOfficeOfDestinationDeclared().getReferenceNumber()); movement.setCountryOfDestination(cc015c.getConsignment().getCountryOfDestination()); movement.setCountryOfDispatch(cc015c.getConsignment().getCountryOfDispatch()); dossierDataService.updateMovement(movement); log.info(String.format("Updated details for movement %s", movement.getId())); } catch (JAXBException e) { log.error("Could not unmarshall message", e); } } private boolean checkIE050SentToCountry(List<String> ie050IdList, String ie118OfficeOfTransitActualReferenceNumber) { // Two (2) first alphanumerics of an Office represent the Country it belongs to: String country = MessageUtil.extractOfficeCountryCode(ie118OfficeOfTransitActualReferenceNumber); return ie050IdList.stream().anyMatch(id -> { try { Message message = dossierDataService.getMessageById(id); CD050CType cd050cMessage = XmlConverter.buildMessageFromXML(message.getPayload(), CD050CType.class); return cd050cMessage.getCustomsOfficeOfTransitDeclared().stream().anyMatch(office -> country.equals(MessageUtil.extractOfficeCountryCode(office.getReferenceNumber()))); } catch (Exception e) { log.error("checkIE050Sent() ERROR for messageId: {}", id); return false; } }); } private boolean checkIE115SentToCountry(List<String> ie115IdList, String ie118OfficeOfTransitActualReferenceNumber) { // Two (2) first alphanumerics of an Office represent the Country it belongs to: String country = MessageUtil.extractOfficeCountryCode(ie118OfficeOfTransitActualReferenceNumber); return ie115IdList.stream().anyMatch(id -> { try { Message message = dossierDataService.getMessageById(id); CD115CType cd115cMessage = XmlConverter.buildMessageFromXML(message.getPayload(), CD115CType.class); return country.equals(MessageUtil.extractOfficeCountryCode(cd115cMessage.getCustomsOfficeOfTransitActual().getReferenceNumber())); } catch (Exception e) { log.error("checkIE115Sent() ERROR for messageId: {}", id); return false; } }); } private boolean checkNoOtherIE118ReceivedFromTransitActual(List<String> ie118IdList, String ie118OfficeOfTransitActualReferenceNumber) { // Due to association by Management, list of size ONE means it's the first IE118 from this Office of Transit: return ie118IdList.stream().filter(id -> { try { Message message = dossierDataService.getMessageById(id); CD118CType cd118cMessage = XmlConverter.buildMessageFromXML(message.getPayload(), CD118CType.class); return ie118OfficeOfTransitActualReferenceNumber.equals(cd118cMessage.getCustomsOfficeOfTransitActual().getReferenceNumber()); } catch (Exception e) { log.error("checkNoOtherIE118ReceivedFromTransitActual() ERROR for messageId: {}", id); return false; } }).count() == 1; } private boolean isThereAnAmendmentActiveForCurrentMovement(String businessKey, String processDefinition) { return !bpmnManagementService.findProcessInstanceByBusinessKeyAndProcessDefinition(businessKey, processDefinition).isEmpty(); } private void createValidationResults(String messageId, String ruleId, String pointer, String errorCode) { List<ValidationResult> validationResults = new ArrayList<>(); ValidationResult validationResult = new ValidationResult(); validationResult.setMessageId(messageId); validationResult.setRuleId(ruleId); validationResult.setPointer(pointer); validationResult.setErrorCode(errorCode); validationResult.setRejecting(true); validationResults.add(validationResult); dossierDataService.saveValidationResults(validationResults); } private boolean isRecoveryRecommendedTimerActive(Movement movement) { return bpmnManagementService.isTimerActive( movement.getMrn(), ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(), BpmnTimersEnum.RECOVERY_RECOMMENDED_TIMER.getActivityId()); } @SuppressWarnings("findsecbugs:XPATH_INJECTION") private void updateCountryAndOfficeOfDestinationOfMovement(Movement movement, String messageId) { Message message = dossierDataService.getMessageById(messageId); try (StringReader sr = new StringReader(message.getPayload())) { InputSource xml = new InputSource(sr); XPath xPath = XPathFactory.newInstance().newXPath(); String actualCustomsOfficeOfDestination = (String) xPath.evaluate(MessageXPathsEnum.DESTINATION_ACTUAL_OFFICE_ID.getValue(), xml, XPathConstants.STRING); String actualCountryOfDestination = MessageUtil.extractOfficeCountryCode(actualCustomsOfficeOfDestination); movement.setOfficeOfDestination(actualCustomsOfficeOfDestination); movement.setCountryOfDestination(actualCountryOfDestination); dossierDataService.updateMovement(movement); } catch (XPathExpressionException exception) { log.error("Error getting xpath for expression: " + MessageXPathsEnum.DESTINATION_ACTUAL_OFFICE_ID.getValue() + " from message: " + message.getMessageType()); } } }
package com.intrasoft.ermis.trs.officeofdeparture.service; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.ddntav5152.messages.CD165CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.ddntav5152.messages.TransitOperationType41; import com.intrasoft.ermis.transit.bpmnshared.BpmnManagementService; import com.intrasoft.ermis.transit.common.exceptions.MessageOutOfOrderException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureFallbackDeclarationFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleAmendmentRequestFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleDestinationControlResultsFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleDiversionFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleEnquiryProcessFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleIncidentNotificationFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleOfArrivalAdviceFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureHandleRecoveryFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureInitializationFacade; import com.intrasoft.ermis.transit.officeofdeparture.process.OoDepartureInvalidationFacade; import com.intrasoft.ermis.transit.officeofdeparture.service.AmendmentRequestService; import com.intrasoft.ermis.transit.officeofdeparture.service.CustomsOfficerActionService; import com.intrasoft.ermis.transit.officeofdeparture.service.DossierDataService; import com.intrasoft.ermis.transit.officeofdeparture.service.EnquiryService; import com.intrasoft.ermis.transit.officeofdeparture.service.FallbackDeclarationService; import com.intrasoft.ermis.transit.officeofdeparture.service.GenerateMessageService; import com.intrasoft.ermis.transit.officeofdeparture.service.GuaranteeService; import com.intrasoft.ermis.transit.officeofdeparture.service.HandleDDNTAMessageServiceImpl; import com.intrasoft.ermis.transit.officeofdeparture.service.InitializationService; import com.intrasoft.ermis.transit.officeofdeparture.service.InvalidationService; import com.intrasoft.ermis.transit.officeofdeparture.service.MovementService; import com.intrasoft.ermis.transit.officeofdeparture.service.ProcessingStatusService; import com.intrasoft.ermis.transit.officeofdeparture.service.RiskControlAssessmentService; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.JAXBException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class HandleDDNTAMessageServiceUT { private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID"; private static final String IE168_MESSAGE_ID = "TEST_IE168_MESSAGE_ID"; private static final String TEST_NA = "NTA.GB"; @Mock private ErmisLogger log; @Mock private MovementService movementService; @Mock private DossierDataService dossierDataService; @Mock private OoDepartureInitializationFacade ooDepartureInitializationFacade; @Mock private OoDepartureInvalidationFacade ooDepartureInvalidationFacade; @Mock private OoDepartureHandleOfArrivalAdviceFacade ooDepartureHandleOfArrivalAdviceFacade; @Mock private OoDepartureHandleDestinationControlResultsFacade ooDepartureHandleDestinationControlResultsFacade; @Mock private OoDepartureHandleAmendmentRequestFacade ooDepartureHandleAmendmentRequestFacade; @Mock private OoDepartureHandleDiversionFacade ooDepartureHandleDiversionFacade; @Mock private OoDepartureHandleIncidentNotificationFacade ooDepartureHandleIncidentNotificationFacade; @Mock private OoDepartureHandleRecoveryFacade ooDepartureHandleRecoveryFacade; @Mock private OoDepartureFallbackDeclarationFacade ooDepartureFallbackDeclarationFacade; @Mock private GuaranteeService guaranteeService; @Mock private InvalidationService invalidationService; @Mock private BpmnManagementService bpmnManagementService; @Mock private GenerateMessageService generateMessageService; @Mock private InitializationService initializationService; @Mock private EnquiryService enquiryService; @Mock private FallbackDeclarationService fallbackDeclarationService; @Mock private ProcessingStatusService processingStatusService; @Mock private AmendmentRequestService amendmentRequestService; @InjectMocks private HandleDDNTAMessageServiceImpl handleDDNTAMessageService; @ParameterizedTest @DisplayName("Test - Process IE168 - National Authority Checks") @CsvSource({"true,true", "true,false", "false,true", "false,false",}) void testProcessIE168NationalAuthorityChecks(boolean sentIE160, boolean sentIE165Positive) { // Test data: Movement testMovement = Movement.builder().id(MOVEMENT_ID).build(); // Stubs: // General: if (!sentIE160 && !sentIE165Positive) { when(dossierDataService.updateMessageStatus(any(), any())).thenReturn(new Message()); } // Unrelated to IE168 case tested: if (sentIE160 || sentIE165Positive) { when(movementService.checkIfInGivenState(eq(MOVEMENT_ID), any())).thenReturn(true); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CD_006_C.value())).thenReturn(Collections.emptyList()); } // Related to test case: when(dossierDataService.getMessageById(IE168_MESSAGE_ID)).thenReturn(createIE168Message()); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CD_160_C.value())).thenReturn(createIE160MessageOverviewList(sentIE160)); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CD_165_C.value())).thenReturn(createIE165MessageOverviewList(sentIE165Positive)); when(dossierDataService.getDDNTAMessageById("IE165_DK", CD165CType.class)).thenReturn(createCD165CType(false)); if (sentIE165Positive) { when(dossierDataService.getDDNTAMessageById("IE165_GB", CD165CType.class)).thenReturn(createCD165CType(true)); } // Call tested method: try { // Verifications: if (!sentIE160 && !sentIE165Positive) { assertThrows(MessageOutOfOrderException.class, () -> handleDDNTAMessageService.handleDDNTAMessage(testMovement, MOVEMENT_ID, IE168_MESSAGE_ID, MessageTypes.CD_168_C.value())); } else { handleDDNTAMessageService.handleDDNTAMessage(testMovement, MOVEMENT_ID, IE168_MESSAGE_ID, MessageTypes.CD_168_C.value()); } } catch (JAXBException ex) { fail("Method execution failed."); } } private Message createIE168Message() { Message ie168Message = new Message(); ie168Message.setSource(TEST_NA); return ie168Message; } private List<MessageOverview> createIE160MessageOverviewList(boolean sentIE160) { List<MessageOverview> messageOverviewList = new ArrayList<>(); messageOverviewList.add(MessageOverview.builder().destination("NTA.GR").build()); if (sentIE160) { messageOverviewList.add(MessageOverview.builder().destination(TEST_NA).build()); } return messageOverviewList; } private List<MessageOverview> createIE165MessageOverviewList(boolean sentIE165Positive) { List<MessageOverview> messageOverviewList = new ArrayList<>(); messageOverviewList.add(MessageOverview.builder().id("IE165_DK").destination("NTA.DK").build()); if (sentIE165Positive) { messageOverviewList.add(MessageOverview.builder().id("IE165_GB").destination(TEST_NA).build()); } return messageOverviewList; } private CD165CType createCD165CType(boolean ie165Positive) { CD165CType cd165cType = new CD165CType(); cd165cType.setTransitOperation(new TransitOperationType41()); if (!ie165Positive) { cd165cType.getTransitOperation().setRequestRejectionReasonCode("REJECT"); } return cd165cType; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.cargov1.messages.CC056CType; import com.intrasoft.ermis.cargov1.messages.CC057CType; import com.intrasoft.ermis.cargov1.messages.FunctionalErrorType04; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.cargov1.messages.TB007CType; import com.intrasoft.ermis.cargov1.messages.TB014CType; import com.intrasoft.ermis.cargov1.messages.TB015CType; import com.intrasoft.ermis.cargov1.messages.TB028CType; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.outbound.MessageProducer; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.common.mappers.CargoMessageTypeMapper; import com.intrasoft.ermis.transit.common.util.MessageUtil; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; import java.util.Objects; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Document; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class GenerateMessageServiceImpl implements GenerateMessageService { private static final String ARRIVAL_PRESENTATION_TIMER_RULE_ID = "CARGO_ARRIVAL_PRESENTATION_TIMER_EXPIRATION"; private static final String NOT_AVAILABLE = "N/A"; private final ErmisLogger logger; private final DossierDataService dossierDataService; private final MessageProducer messageProducer; private final GetCountryCodeService getCountryCodeService; private final CargoMessageTypeMapper cargoMessageTypeMapper; @Override public <T> void generateIE056(String movementId, String messageId, Class<T> messageClass) throws NotFoundException, JAXBException { Message correlatedMessage; List<ValidationResult> validationResultList; try { correlatedMessage = dossierDataService.getMessageById(messageId); } catch (NotFoundException exception) { throw new NotFoundException("generateIE056() : Failed to find Message with ID: " + messageId + " for Movement with ID: " + movementId); } // Find validation results: validationResultList = dossierDataService.findValidationResultListByMessageId(messageId); // Create CC056C: CC056CType cc056cTypeMessage = createCC056CMessage(movementId, validationResultList, correlatedMessage.getPayload(), messageClass); // Transform to XML message: String cc056cTypeMessageXML = XmlConverter.marshal(cc056cTypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CC_056_C.value()); Message message = Message.builder() .messageIdentification(cc056cTypeMessage.getMessageIdentification()) .messageType(cc056cTypeMessage.getMessageType().value()) .source(sanitizeInput(cc056cTypeMessage.getMessageSender())) .destination(sanitizeInput(cc056cTypeMessage.getMessageRecipient())) .domain(MessageDomainTypeEnum.EXTERNAL.name()) .payload(cc056cTypeMessageXML) .direction(DirectionEnum.SENT.getDirection()) .build(); saveAndPublishMessage(message, movementId); } @Override public <T> void generateIE057(String movementId, String messageId, Class<T> messageClass) throws NotFoundException, JAXBException { Message correlatedMessage; List<ValidationResult> validationResultList; try { correlatedMessage = dossierDataService.getMessageById(messageId); } catch (NotFoundException exception) { throw new NotFoundException("generateIE057() : Failed to find Message with ID: " + messageId + " for Movement with ID: " + movementId); } // Find validation results: validationResultList = dossierDataService.findValidationResultListByMessageId(messageId); // Create CC057C: CC057CType cc057cTypeMessage = createCC057CMessage(validationResultList, correlatedMessage.getPayload(), messageClass); // Transform to XML message: String cc057cTypeMessageXML = XmlConverter.marshal(cc057cTypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CC_057_C.value()); Message message = Message.builder() .messageIdentification(cc057cTypeMessage.getMessageIdentification()) .messageType(cc057cTypeMessage.getMessageType().value()) .source(sanitizeInput(cc057cTypeMessage.getMessageSender())) .destination(sanitizeInput(cc057cTypeMessage.getMessageRecipient())) .domain(MessageDomainTypeEnum.EXTERNAL.name()) .payload(cc057cTypeMessageXML) .direction(DirectionEnum.SENT.getDirection()) .build(); saveAndPublishMessage(message, movementId); } @Override public void generateTB028(String movementId, String mrn) throws JAXBException { Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movementId); TB015CType tb015cTypeMessage = XmlConverter.buildMessageFromXML(declaration.getPayload(), TB015CType.class); // Create TB028C: TB028CType tb028cTypeMessage = createTB028CMessage(tb015cTypeMessage, mrn); // Transform to XML message: String tb028cTypeMessageXML = XmlConverter.marshal(tb028cTypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.TB_028_C.value()); Message message = Message.builder() .messageIdentification(tb028cTypeMessage.getMessageIdentification()) .messageType(tb028cTypeMessage.getMessageType().value()) .source(tb028cTypeMessage.getMessageSender()) .destination(tb028cTypeMessage.getMessageRecipient()) .domain(MessageDomainTypeEnum.EXTERNAL.name()) .payload(tb028cTypeMessageXML) .direction(DirectionEnum.SENT.getDirection()) .build(); saveAndPublishMessage(message, movementId); } private <T> CC056CType createCC056CMessage(String movementId, List<ValidationResult> validationResults, String messagePayload, Class<T> messageClass) throws JAXBException { Document document = XmlConverter.convertStringToXMLDocument(messagePayload); T messageIn = XmlConverter.buildMessageFromXML(messagePayload, messageClass); CC056CType messageOut = new CC056CType(); if (messageIn instanceof TB015CType) { messageOut = cargoMessageTypeMapper.fromTB015CtoCC056C((TB015CType) messageIn); } else if (messageIn instanceof TB014CType) { Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movementId); TB015CType cc015cTypeMessage = XmlConverter.buildMessageFromXML(declaration.getPayload(), TB015CType.class); messageOut = cargoMessageTypeMapper.fromTB014CtoCC056C((TB014CType) messageIn); messageOut.setMessageRecipient(cc015cTypeMessage.getMessageSender()); } setCoreDataToMessage(messageOut, messageIn); CC056CType finalMessageOut = messageOut; if (validationResults.stream().anyMatch(validationResult -> validationResult.isRejecting() && ARRIVAL_PRESENTATION_TIMER_RULE_ID.equals(validationResult.getRuleId()))) { finalMessageOut.getTransitOperation().setRejectionCode("4"); finalMessageOut.getTransitOperation().setRejectionReason("Arrival Presentation Timer Expiration"); } else { finalMessageOut.getTransitOperation().setRejectionCode("12"); finalMessageOut.getTransitOperation().setRejectionReason(null); validationResults.stream().filter(ValidationResult::isRejecting).forEach(validationResult -> { String originalValue = null; try { int valuesArraySize = XmlConverter.evaluateXPath(document, validationResult.getPointer()).size(); if (valuesArraySize > 0) { originalValue = XmlConverter.evaluateXPath(document, validationResult.getPointer()).get(0); } } catch (Exception e) { logger.error("createCC056Message error: ", e); } finalMessageOut.getFunctionalError().add(createFunctionalError(validationResult, originalValue)); }); } return finalMessageOut; } private <T> CC057CType createCC057CMessage(List<ValidationResult> validationResults, String messagePayload, Class<T> messageClass) throws JAXBException { Document document = XmlConverter.convertStringToXMLDocument(messagePayload); T messageIn = XmlConverter.buildMessageFromXML(messagePayload, messageClass); CC057CType messageOut = new CC057CType(); if (messageIn instanceof TB007CType) { messageOut = cargoMessageTypeMapper.fromTB007CtoCC057C((TB007CType) messageIn); } setCoreDataToMessage(messageOut, messageIn); CC057CType finalMessageOut = messageOut; finalMessageOut.getTransitOperation().setRejectionCode("12"); finalMessageOut.getTransitOperation().setRejectionReason(null); validationResults.stream().filter(ValidationResult::isRejecting).forEach(validationResult -> { String originalValue = null; try { int valuesArraySize = XmlConverter.evaluateXPath(document, validationResult.getPointer()).size(); if (valuesArraySize > 0) { originalValue = XmlConverter.evaluateXPath(document, validationResult.getPointer()).get(0); } } catch (Exception e) { logger.error("createCC057Message error: ", e); } finalMessageOut.getFunctionalError().add(createFunctionalError(validationResult, originalValue)); }); return finalMessageOut; } private TB028CType createTB028CMessage(TB015CType messageIn, String mrn) { TB028CType messageOut = cargoMessageTypeMapper.fromTB015CtoTB028C(messageIn); messageOut.setMessageType(MessageTypes.TB_028_C); messageOut.setMessageSender(generateMessageSender()); messageOut.setPreparationDateAndTime(nowUTC()); messageOut.setMessageIdentification(MessageUtil.generateMessageIdentification()); messageOut.getTransitOperation().setLRN(messageIn.getTransitOperation().getLRN()); messageOut.getTransitOperation().setDeclarationAcceptanceDate(nowUTC().toLocalDate()); messageOut.getTransitOperation().setMRN(mrn); return messageOut; } private void saveAndPublishMessage(Message message, String movementId) { Message savedMessage = dossierDataService.saveMessage(message); if (!StringUtils.isBlank(movementId)) { dossierDataService.associateMessageWithMovement(savedMessage.getId(), movementId); } messageProducer.publish(message.getPayload(), movementId, message.getMessageType()); } private String generateMessageSender() { return CargoMessageTypeMapper.NTA + getCountryCodeService.getCountryCode(); } private LocalDateTime nowUTC() { return LocalDateTime.now(ZoneOffset.UTC); } private FunctionalErrorType04 createFunctionalError(ValidationResult validationResult, String originalValue) { FunctionalErrorType04 functionalError = new FunctionalErrorType04(); functionalError.setErrorPointer(validationResult.getPointer()); functionalError.setErrorCode(validationResult.getErrorCode()); functionalError.setErrorReason(validationResult.getRuleId()); functionalError.setOriginalAttributeValue(originalValue); return functionalError; } private <T> void setCoreDataToMessage(T messageOut, T messageIn) { if (messageOut instanceof CC056CType) { ((CC056CType) messageOut).setMessageSender(generateMessageSender()); ((CC056CType) messageOut).setMessageType(MessageTypes.CC_056_C); ((CC056CType) messageOut).setPreparationDateAndTime(nowUTC()); ((CC056CType) messageOut).setMessageIdentification(MessageUtil.generateMessageIdentification()); ((CC056CType) messageOut).getTransitOperation().setBusinessRejectionType(messageIn.getClass().getSimpleName().substring(2, 5)); ((CC056CType) messageOut).getTransitOperation().setRejectionDateAndTime(nowUTC()); } else if (messageOut instanceof CC057CType) { ((CC057CType) messageOut).setMessageSender(generateMessageSender()); ((CC057CType) messageOut).setMessageType(MessageTypes.CC_057_C); ((CC057CType) messageOut).setPreparationDateAndTime(nowUTC()); ((CC057CType) messageOut).setMessageIdentification(MessageUtil.generateMessageIdentification()); ((CC057CType) messageOut).getTransitOperation().setBusinessRejectionType(messageIn.getClass().getSimpleName().substring(2, 5)); ((CC057CType) messageOut).getTransitOperation().setRejectionDateAndTime(nowUTC()); } else { logger.warn("setCoreDataToMessage(): Invalid Message of class: " + messageOut.getClass().getSimpleName()); } } private String sanitizeInput(String input) { return Objects.nonNull(input) ? input : NOT_AVAILABLE; } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.cargov1.messages.CC056CType; import com.intrasoft.ermis.cargov1.messages.CC057CType; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.cargov1.messages.TB007CType; import com.intrasoft.ermis.cargov1.messages.TB015CType; import com.intrasoft.ermis.cargov1.messages.TB028CType; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.outbound.MessageProducer; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.GenerateMessageServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult; import com.intrasoft.ermis.transit.cargoofficeofdestination.test.util.TestDataUtilities; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.mappers.CargoMessageTypeMapper; import com.intrasoft.ermis.transit.common.mappers.CargoMessageTypeMapperImpl; import com.intrasoft.ermis.transit.common.util.MessageUtil; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import javax.xml.bind.JAXBException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class GenerateMessageServiceUT { private static final String MOVEMENT_ID_PREFIX = "MOVEMENT_ID_"; private static final String MESSAGE_ID_PREFIX = "MESSAGE_ID_"; private static final String MESSAGE_IDENTIFICATION_PREFIX = "MESSAGE_IDENTIFICATION_"; private static final String MOCKED_COUNTRY_CODE = "DK"; private static final String ARRIVAL_PRESENTATION_TIMER_RULE_ID = "CARGO_ARRIVAL_PRESENTATION_TIMER_EXPIRATION"; private static final String ARRIVAL_PRESENTATION_TIMER_ERROR_CODE = "N/A"; private static final String ARRIVAL_PRESENTATION_TIMER_ERROR_POINTER = "/TB015C/preparationDateAndTime"; private static final String GENERIC_RULE_ID = "GENERIC_RULE_ID"; private static final String GENERIC_ERROR_POINTER = "/TB015C/preparationDateAndTime"; private static final String GENERIC_ERROR_CODE = "GENERIC_CODE"; private static final String MRN = "TEST_MRN"; private static final String TEST_DEPARTURE_OFFICE = "DK000000"; private static final String TEST_DESTINATION_OFFICE = "DK111111"; @Mock private ErmisLogger logger; @Mock private DossierDataService dossierDataService; @Mock private MessageProducer messageProducer; @Mock private GetCountryCodeService getCountryCodeService; @Spy private CargoMessageTypeMapper cargoMessageTypeMapper = new CargoMessageTypeMapperImpl(); @InjectMocks private GenerateMessageServiceImpl generateMessageService; @Captor private ArgumentCaptor<String> messagePayloadCaptor; @ParameterizedTest @DisplayName("Test - Generate IE056 - Generic cases") @MethodSource("provideTestArguments") <T> void testGenerateIE056GenericCases(Class<T> messageClass) throws JAXBException { String movementId = MOVEMENT_ID_PREFIX + messageClass.getSimpleName(); String messageId = MESSAGE_ID_PREFIX + messageClass.getSimpleName(); Message message = createMessage(messageId, messageClass); // Stubs/mocks: when(dossierDataService.getMessageById(messageId)) .thenReturn(message); when(dossierDataService.findValidationResultListByMessageId(messageId)) .thenReturn(createValidationResultList(messageId, false)); when(dossierDataService.saveMessage(any(Message.class))) .thenReturn(new Message()); when(getCountryCodeService.getCountryCode()).thenReturn(MOCKED_COUNTRY_CODE); // Call GenerateMessageService method: generateMessageService.generateIE056(movementId, messageId, messageClass); // Verifications & Assertions: verify(dossierDataService).associateMessageWithMovement(any(), eq(movementId)); verify(messageProducer).publish(messagePayloadCaptor.capture(), eq(movementId), eq(MessageTypes.CC_056_C.value())); ie056MessageAssertions(messageClass, messagePayloadCaptor.getValue(), false); } @Test @DisplayName("Test - Generate IE057") void testGenerateIE057() throws JAXBException { String movementId = MOVEMENT_ID_PREFIX + TB007CType.class.getSimpleName(); String messageId = MESSAGE_ID_PREFIX + TB007CType.class.getSimpleName(); Message message = createMessage(messageId, TB007CType.class); // Stubs/mocks: when(dossierDataService.getMessageById(messageId)) .thenReturn(message); when(dossierDataService.findValidationResultListByMessageId(messageId)) .thenReturn(createValidationResultList(messageId, false)); when(dossierDataService.saveMessage(any(Message.class))) .thenReturn(new Message()); when(getCountryCodeService.getCountryCode()).thenReturn(MOCKED_COUNTRY_CODE); // Call GenerateMessageService method: generateMessageService.generateIE057(movementId, messageId, TB007CType.class); // Verifications & Assertions: verify(dossierDataService).associateMessageWithMovement(any(), eq(movementId)); verify(messageProducer).publish(messagePayloadCaptor.capture(), eq(movementId), eq(MessageTypes.CC_057_C.value())); CC057CType cc057cTypeMessage = XmlConverter.buildMessageFromXML(messagePayloadCaptor.getValue(), CC057CType.class); assertEquals(MessageTypes.CC_057_C, cc057cTypeMessage.getMessageType()); assertEquals(TB007CType.class.getSimpleName().substring(2, 5), cc057cTypeMessage.getTransitOperation().getBusinessRejectionType()); assertEquals(CargoMessageTypeMapper.NTA + MOCKED_COUNTRY_CODE, cc057cTypeMessage.getMessageSender()); assertEquals("12", cc057cTypeMessage.getTransitOperation().getRejectionCode()); assertNull(cc057cTypeMessage.getTransitOperation().getRejectionReason()); assertEquals(GENERIC_RULE_ID, cc057cTypeMessage.getFunctionalError().get(0).getErrorReason()); assertEquals(GENERIC_ERROR_CODE, cc057cTypeMessage.getFunctionalError().get(0).getErrorCode()); assertEquals(GENERIC_ERROR_POINTER, cc057cTypeMessage.getFunctionalError().get(0).getErrorPointer()); } @Test @DisplayName("Test - Generate IE056 - TB015 Arrival Presentation Timer Expiration case") void testGenerateIE056TB015ArrivalPresentationTimerExpirationCase() throws JAXBException { Class<TB015CType> messageClass = TB015CType.class; String movementId = MOVEMENT_ID_PREFIX + messageClass.getSimpleName(); String messageId = MESSAGE_ID_PREFIX + messageClass.getSimpleName(); Message message = createMessage(messageId, messageClass); // Stubs/mocks: when(dossierDataService.getMessageById(messageId)) .thenReturn(message); when(dossierDataService.findValidationResultListByMessageId(messageId)) .thenReturn(createValidationResultList(messageId, true)); when(dossierDataService.saveMessage(any(Message.class))) .thenReturn(new Message()); when(getCountryCodeService.getCountryCode()).thenReturn(MOCKED_COUNTRY_CODE); // Call GenerateMessageService method: generateMessageService.generateIE056(movementId, messageId, messageClass); // Verifications & Assertions: verify(dossierDataService).associateMessageWithMovement(any(), eq(movementId)); verify(messageProducer).publish(messagePayloadCaptor.capture(), eq(movementId), eq(MessageTypes.CC_056_C.value())); ie056MessageAssertions(messageClass, messagePayloadCaptor.getValue(), true); } @Test @DisplayName("Test - Generate TB028") void testGenerateTB028() throws JAXBException { String testCaseSuffix = "TB028C"; String movementId = MOVEMENT_ID_PREFIX + testCaseSuffix; TB015CType testTB015CType = TestDataUtilities.createTB015C(TEST_DEPARTURE_OFFICE, TEST_DESTINATION_OFFICE); Declaration testDeclaration = TestDataUtilities.createDeclaration(movementId, XmlConverter.marshal(testTB015CType, NamespacesEnum.NTA.getValue(), MessageTypes.TB_015_C.value()), MessageTypes.TB_015_C.value()); // Stubs/mocks: when(dossierDataService.getLatestDeclarationByMovementId(movementId)) .thenReturn(testDeclaration); when(dossierDataService.saveMessage(any(Message.class))) .thenReturn(new Message()); when(getCountryCodeService.getCountryCode()).thenReturn(MOCKED_COUNTRY_CODE); // Call GenerateMessageService method: generateMessageService.generateTB028(movementId, MRN); // Verifications & Assertions: verify(dossierDataService).associateMessageWithMovement(any(), eq(movementId)); verify(messageProducer).publish(messagePayloadCaptor.capture(), eq(movementId), eq(MessageTypes.TB_028_C.value())); TB028CType actualTB028C = XmlConverter.buildMessageFromXML(messagePayloadCaptor.getValue(), TB028CType.class); assertEquals(testTB015CType.getTransitOperation().getLRN(), actualTB028C.getTransitOperation().getLRN()); assertEquals(MRN, actualTB028C.getTransitOperation().getMRN()); assertEquals(MessageTypes.TB_028_C, actualTB028C.getMessageType()); assertEquals(TEST_DEPARTURE_OFFICE, actualTB028C.getCustomsOfficeOfDeparture().getReferenceNumber()); assertEquals(testTB015CType.getMessageSender(), actualTB028C.getMessageRecipient()); assertEquals(CargoMessageTypeMapper.NTA + MOCKED_COUNTRY_CODE, actualTB028C.getMessageSender()); } private <T> Message createMessage(String messageId, Class<T> messageClass) { Message message = new Message(); message.setId(messageId); message.setMessageType(MessageUtil.extractMessageTypeFromMessageClass(messageClass)); message.setPayload(createMessagePayload(messageClass)); return message; } private <T> String createMessagePayload(Class<T> messageClass) { if (TB015CType.class.equals(messageClass)) { TB015CType messagePayload = TestDataUtilities.createTB015C(TEST_DEPARTURE_OFFICE, TEST_DESTINATION_OFFICE); messagePayload.setMessageIdentification(MESSAGE_IDENTIFICATION_PREFIX + messageClass); return XmlConverter.marshal(messagePayload, NamespacesEnum.NTA.getValue(), MessageTypes.TB_015_C.value()); } else if (TB007CType.class.equals(messageClass)) { TB007CType messagePayload = TestDataUtilities.createTB007C(TEST_DESTINATION_OFFICE); messagePayload.setMessageIdentification(MESSAGE_IDENTIFICATION_PREFIX + messageClass); return XmlConverter.marshal(messagePayload, NamespacesEnum.NTA.getValue(), MessageTypes.TB_007_C.value()); } else { return null; } } private List<ValidationResult> createValidationResultList(String messageId, boolean timerExpirationCase) { List<ValidationResult> validationResultList = new ArrayList<>(); ValidationResult validationResult = new ValidationResult(); if (timerExpirationCase) { validationResult.setRuleId(ARRIVAL_PRESENTATION_TIMER_RULE_ID); validationResult.setErrorCode(ARRIVAL_PRESENTATION_TIMER_ERROR_CODE); validationResult.setPointer(ARRIVAL_PRESENTATION_TIMER_ERROR_POINTER); } else { validationResult.setRuleId(GENERIC_RULE_ID); validationResult.setErrorCode(GENERIC_ERROR_CODE); validationResult.setPointer(GENERIC_ERROR_POINTER); } validationResult.setRejecting(true); validationResult.setMessageId(messageId); validationResultList.add(validationResult); return validationResultList; } private <T> void ie056MessageAssertions(Class<T> messageClass, String ie056MessagePayload, boolean timerExpirationCase) throws JAXBException { CC056CType cc056cTypeMessage = XmlConverter.buildMessageFromXML(ie056MessagePayload, CC056CType.class); assertEquals(MessageTypes.CC_056_C, cc056cTypeMessage.getMessageType()); assertEquals(messageClass.getSimpleName().substring(2, 5), cc056cTypeMessage.getTransitOperation().getBusinessRejectionType()); assertEquals(CargoMessageTypeMapper.NTA + MOCKED_COUNTRY_CODE, cc056cTypeMessage.getMessageSender()); if (TB015CType.class.equals(messageClass) && timerExpirationCase) { assertEquals("4", cc056cTypeMessage.getTransitOperation().getRejectionCode()); assertEquals("Arrival Presentation Timer Expiration", cc056cTypeMessage.getTransitOperation().getRejectionReason()); } else { assertEquals("12", cc056cTypeMessage.getTransitOperation().getRejectionCode()); assertNull(cc056cTypeMessage.getTransitOperation().getRejectionReason()); assertEquals(GENERIC_RULE_ID, cc056cTypeMessage.getFunctionalError().get(0).getErrorReason()); assertEquals(GENERIC_ERROR_CODE, cc056cTypeMessage.getFunctionalError().get(0).getErrorCode()); assertEquals(GENERIC_ERROR_POINTER, cc056cTypeMessage.getFunctionalError().get(0).getErrorPointer()); } } private static Stream<Arguments> provideTestArguments() { return Stream.of( Arguments.of(TB015CType.class) ); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofdeparture.service; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.AcceptGuaranteeEvent; import com.intrasoft.ermis.ddntav5152.messages.CC013CType; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CC170CType; import com.intrasoft.ermis.ddntav5152.messages.GuaranteeType01; import com.intrasoft.ermis.ddntav5152.messages.GuaranteeType02; import com.intrasoft.ermis.ddntav5152.messages.HouseConsignmentType06; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.enums.GuaranteeTypesEnum; import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.officeofdeparture.domain.Declaration; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.domain.WorkTask; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowFallbackEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.ProcessDefinitionEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.events.ProcessInstanceCancellationResponseDomainEvent; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class AmendmentRequestServiceImpl implements AmendmentRequestService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String FALLBACK_CANCELLATION = "Cancelled by Main flow fallback"; private final ErmisLogger log; private final DossierDataService dossierDataService; private final WorkTaskManagerDataService workTaskManagerDataService; private final GenerateMessageService generateMessageService; public static final String COMMON = "COMMON"; private final MessageTypeMapper messageTypeMapper; private final MovementService movementService; private final BpmnFlowService bpmnFlowService; private static final List<String> guaranteeTypeList = Arrays.asList(GuaranteeTypesEnum.TYPE_0.getCode(), GuaranteeTypesEnum.TYPE_1.getCode(), GuaranteeTypesEnum.TYPE_2.getCode(), GuaranteeTypesEnum.TYPE_4.getCode(), GuaranteeTypesEnum.TYPE_9.getCode()); @Override public boolean checkIE204ConveyanceEligibility(String movementId) { // Guarantee types that provide IE204 conveyance eligibility: List<String> guaranteeTypesForIE204 = new ArrayList<>(guaranteeTypeList); // Retrieve CC015C message based on movementID: CC015CType cc015cMessage = getCC015CMessage(movementId); if (cc015cMessage != null) { // Check if Guarantee list from CC015C message contains at least one (1) guarantee of type // that deems IE204 eligibility as true, else false: return cc015cMessage.getGuarantee().stream().anyMatch(guarantee -> guaranteeTypesForIE204.contains(guarantee.getGuaranteeType())); } else { // Throw BaseException if CC015C with provided movementID was not found: throw new BaseException("ERROR in checkIE204ConveyanceEligibility(): CC015C Message was NULL!"); } } @Override public ProcessingStatusTypeEnum checkPreviousState(String movementId) { return movementService.checkLatestState(movementId); } @Override public boolean checkCurrentState(String movementId, ProcessingStatusTypeEnum state) { return movementService.checkIfInGivenState(movementId, state); } @Override public boolean checkGMSGuarantees(String movementId) { return checkAmendedGuaranteeTypes(movementId); } @Override public boolean isAutomaticReleaseTimerActive(String movementId) { // TODO Implementation pending... return true; } @Override public void rejectMessage(String movementId, String messageId, boolean isIE015Rejected) throws JAXBException { generateMessageService.generateIE056(movementId, messageId, isIE015Rejected, CC013CType.class); dossierDataService.updateMessageStatus(messageId, MessageStatusEnum.REJECTED.name()); } @Override public Declaration amendDeclarationAndCreateNewVersion(String movementId, String messageId, String messageType, boolean isFallbackDeclaration) throws JAXBException { Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movementId); CC015CType cc015CTypeOfLatestDeclaration = XmlConverter.buildMessageFromXML(declaration.getPayload(), CC015CType.class); CC015CType updatedCc015CTypeMessage = null; if (AcceptGuaranteeEvent.class.getSimpleName().equals(messageType) && !isFallbackDeclaration) { updatedCc015CTypeMessage = updateCc015CTypeWithAcceptGuaranteeEvent(movementId, cc015CTypeOfLatestDeclaration); } else if (MessageTypes.CC_013_C.value().equals(messageType)) { updatedCc015CTypeMessage = updateCc015CTypeWithCc013C(movementId, isFallbackDeclaration, cc015CTypeOfLatestDeclaration); updateMovementWithAmendment(movementId, messageId); } else if (MessageTypes.CC_170_C.value().equals(messageType) && !isFallbackDeclaration) { updatedCc015CTypeMessage = updateCc015CTypeWithCc170C(messageId, cc015CTypeOfLatestDeclaration); } if (updatedCc015CTypeMessage != null) { log.info("amendDeclarationAndCreateNewVersion(): Will create new Declaration on Movement: [{}] with received messageType: [{}]", movementId, messageType); String updatedCC015cXml = XmlConverter.marshal(updatedCc015CTypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CC_015_C.value()); Message updatedCC015CMessage = Message.builder() .messageIdentification(cc015CTypeOfLatestDeclaration.getMessageIdentification()) .messageType(cc015CTypeOfLatestDeclaration.getMessageType().value()) .source(cc015CTypeOfLatestDeclaration.getMessageSender()) .destination(cc015CTypeOfLatestDeclaration.getMessageRecipient()) .domain(COMMON) .payload(updatedCC015cXml) .build(); Declaration updatedDeclaration = Declaration.builder() .movementId(movementId) .payloadType(MessageTypes.CC_015_C.value()) .payload(updatedCC015CMessage.getPayload()) .version(declaration.getVersion() + 1) .build(); dossierDataService.createDeclaration(updatedDeclaration); return updatedDeclaration; } return null; } private CC015CType updateCc015CType(String movementId, boolean isFallbackDeclaration, CC015CType cc015CTypeOfLatestDeclaration, List<MessageOverview> cc013cMessageOverviewList) throws JAXBException { CC015CType updatedCc015CTypeMessage = null; if (!cc013cMessageOverviewList.isEmpty()) { Message cc013Message = dossierDataService.getMessageById(cc013cMessageOverviewList.get(0).getId()); CC013CType cc013CTypeMessage = XmlConverter.buildMessageFromXML(cc013Message.getPayload(), CC013CType.class); updatedCc015CTypeMessage = createNewDeclarationBasedOnCC013(cc013CTypeMessage, cc015CTypeOfLatestDeclaration); if(isFallbackDeclaration) { updatedCc015CTypeMessage.getExtensions().addAll(cc015CTypeOfLatestDeclaration.getExtensions()); } } else { log.error("No message with type CC013C found for movementId: {}", movementId); } return updatedCc015CTypeMessage; } @Override public void fallBackToPrelodgedRiskStep(String movementId) { // Find any OPEN work tasks in database and change their status before process modification. cancelAllOpenWorkTasks(movementId); // Since the action happens in the initialization flow, movementId == processBusinessKey. modifyProcessInstance( movementId, ProcessDefinitionEnum.OODEPARTURE_INITIALIZATION_PROCESS.getProcessDefinitionKey(), BpmnFlowFallbackEnum.INITIALIZATION_PROCESS_GATEWAY_PRELODGED_RISK.getActivityId(), List.of(BpmnFlowFallbackEnum.EVENT_GATEWAY_GPR.getActivityId()) ); } @Override public void initiateFallbackToMainFlow(String movementId) { // Find any OPEN work tasks in database and change their status before process modification. cancelAllOpenWorkTasks(movementId); // Cancel Control process, if started - initiated via Kafka, before modifying the Main flow. // Since the action happens in the control flow, movement.getMRN == processBusinessKey. cancelProcessInstanceIfExists( getMRN(movementId), com.intrasoft.ermis.transit.contracts.control.enums.ProcessDefinitionEnum.CTL_MAIN_FLOW.getProcessDefinitionKey(), FALLBACK_CANCELLATION ); } @Override public void continueFallbackToMainFlow(ProcessInstanceCancellationResponseDomainEvent responseDomainEvent) { // Called by ProcessInstanceCancellationResponseHandler when the fallback initiation is completed. // (Since the action happens in the main flow, movement.getMRN == processBusinessKey.) if (responseDomainEvent.isCompleted()) { modifyProcessInstance( responseDomainEvent.getProcessBusinessKey(), ProcessDefinitionEnum.OODEPARTURE_MAIN_PROCESS.getProcessDefinitionKey(), BpmnFlowFallbackEnum.MAIN_PROCESS_RISK_CONTROL.getActivityId(), List.of() ); } else { log.warn("Process Instance cancellation was not completed for Business Key: {}!", responseDomainEvent.getProcessBusinessKey()); } } @Override public void fallBackToStartOfGuaranteeProcess(String movementId) { // Since the action happens in the 'Register Guarantee Use' flow, movement.getMRN == processBusinessKey. modifyProcessInstance( getMRN(movementId), ProcessDefinitionEnum.OODEPARTURE_REGISTER_GUARANTEE_USE_PROCESS.getProcessDefinitionKey(), BpmnFlowFallbackEnum.REGISTER_GUARANTEE_PROCESS_INITIALIZE_REGISTER_GUARANTEE_USE.getActivityId(), List.of() ); } @Override public void triggerGuaranteeFlowContinuation(String movementId) { // Since the action happens in the 'Register Guarantee Use' flow, movement.getMRN == processBusinessKey. String processBusinessKey = getMRN(movementId); bpmnFlowService.correlateMessage(processBusinessKey, BpmnFlowMessagesEnum.GUARANTEE_AMENDMENT_RECEIVED_MESSAGE.getTypeValue()); } @Override public void updateLimitDate(String movementId, LocalDate expectedArrivalDate) throws JAXBException { Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movementId); CC015CType cc015CType = XmlConverter.buildMessageFromXML(declaration.getPayload(), CC015CType.class); cc015CType.getTransitOperation().setLimitDate(expectedArrivalDate); String updatedCC015cXml = XmlConverter.marshal(cc015CType, NamespacesEnum.NTA.getValue(), MessageTypes.CC_015_C.value()); Declaration updatedDeclaration = Declaration.builder() .movementId(movementId) .payloadType(MessageTypes.CC_015_C.value()) .payload(updatedCC015cXml) .version(declaration.getVersion() + 1) .build(); dossierDataService.createDeclaration(updatedDeclaration); } private CC015CType getCC015CMessage(String movementId) { CC015CType cc015cTypeMessage; try { // Fetch Declaration: Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movementId); // Retrieve CC015C message: cc015cTypeMessage = XmlConverter.buildMessageFromXML(declaration.getPayload(), CC015CType.class); return cc015cTypeMessage; } catch (Exception e) { throw new BaseException("ERROR in getCC015CMessage()", e); } } private CC015CType getPreviousVersionCC015CMessage(String movementId) { CC015CType cc015cTypeMessage; try { // Fetch latest (current) Declaration: Declaration currentDeclaration = dossierDataService.getLatestDeclarationByMovementId(movementId); // Retrieve its version: Integer currentVersion = currentDeclaration.getVersion(); // Fetch previous Declaration: Declaration previousDeclaration = dossierDataService.getDeclarationByMovementIdAndVersion(movementId, currentVersion - 1); // Retrieve CC015C message: cc015cTypeMessage = XmlConverter.buildMessageFromXML(previousDeclaration.getPayload(), CC015CType.class); return cc015cTypeMessage; } catch (Exception e) { throw new BaseException("ERROR in getPreviousVersionCC015CMessage()", e); } } private CC013CType getCC013CMessage(String movementId) { CC013CType cc013cTypeMessage; try { List<MessageOverview> cc013cMessageOverviewList = dossierDataService.getMessagesOverview(movementId, MessageTypes.CC_013_C.value()); // Retrieve CC013C message: Message cc013cMessage; if (!cc013cMessageOverviewList.isEmpty()) { cc013cMessage = dossierDataService.getMessageById(cc013cMessageOverviewList.get(0).getId()); } else { throw new NotFoundException("getCC013CMessage() : Returned EMPTY MessageOverview List for movementId: " + movementId); } cc013cTypeMessage = XmlConverter.buildMessageFromXML(cc013cMessage.getPayload(), CC013CType.class); return cc013cTypeMessage; } catch (Exception e) { throw new BaseException(String.format("ERROR in getCC013CMessage() for movementId: %s", movementId), e); } } private String getMRN(String movementId) { Movement movement; try { // Retrieve movement: movement = dossierDataService.getMovementById(movementId); return movement.getMrn(); } catch (Exception e) { throw new BaseException("ERROR in getMRN()", e); } } private boolean checkAmendedGuaranteeTypes(String movementId) { // Retrieve previous IE015 & current IE013 messages based on movementID: CC015CType cc015cMessage = getPreviousVersionCC015CMessage(movementId); CC013CType cc013cMessage = getCC013CMessage(movementId); if (cc013cMessage != null) { // Check if there were amendments on them: return amendmentOnSpecificGuaranteeTypes(cc015cMessage, cc013cMessage); } else { // Throw BaseException if CC013C with provided movementID was not found: throw new BaseException("ERROR in checkGuaranteeEligibility(): for movementId: [" + movementId + "]. CC013C Message was NULL!"); } } private boolean amendmentOnSpecificGuaranteeTypes(CC015CType cc015cMessage, CC013CType cc013cMessage) { List<GuaranteeType01> cc013cSpecificGuarantees = cc013cMessage.getGuarantee() .stream() .filter(guaranteeType01 -> guaranteeTypeList.contains(guaranteeType01.getGuaranteeType())) .toList(); List<GuaranteeType01> cc015cSpecificGuarantees = guaranteeType02ListToType01List(cc015cMessage.getGuarantee() .stream() .filter(guaranteeType02 -> guaranteeTypeList.contains(guaranteeType02.getGuaranteeType())) .toList()); // If NOT identical, then there was an amendment on guarantee of specific type. // Covers cases of added, removed or changed guarantees (013 > 015 | 015 > 013 | 013 != 015). return !(cc013cSpecificGuarantees.containsAll(cc015cSpecificGuarantees) && cc015cSpecificGuarantees.containsAll(cc013cSpecificGuarantees)); } private List<GuaranteeType01> guaranteeType02ListToType01List(List<GuaranteeType02> guaranteeType02List) { List<GuaranteeType01> guaranteeType01List = new ArrayList<>(); guaranteeType02List.forEach(guaranteeType02 -> { GuaranteeType01 guaranteeType01 = new GuaranteeType01(); guaranteeType01.setSequenceNumber(guaranteeType02.getSequenceNumber()); guaranteeType01.setGuaranteeType(guaranteeType02.getGuaranteeType()); guaranteeType01.setOtherGuaranteeReference(guaranteeType02.getOtherGuaranteeReference()); guaranteeType01.getGuaranteeReference().addAll(guaranteeType02.getGuaranteeReference()); guaranteeType01List.add(guaranteeType01); }); return guaranteeType01List; } private void modifyProcessInstance(String processBusinessKey, String processDefinitionKey, String activityId, List<String> nonCancelableActivityIds) { bpmnFlowService.modifyProcessInstance(processBusinessKey, processDefinitionKey, activityId, nonCancelableActivityIds); } private void cancelProcessInstanceIfExists(String processBusinessKey, String processDefinitionKey, String cancellationReason) { bpmnFlowService.cancelProcessInstanceIfExists(processBusinessKey, processDefinitionKey, cancellationReason); } private void cancelAllOpenWorkTasks(String movementId) { // Find any OPEN work tasks in database and change their status to 'CANCELLED'. List<WorkTask> openWorkTaskList = new ArrayList<>(workTaskManagerDataService.findOpenWorkTasksByMovementId(movementId)); openWorkTaskList.forEach(workTask -> workTaskManagerDataService.autoUpdateWorkTask(workTask.getWorkTaskId())); } private CC015CType createNewDeclarationBasedOnCC013(CC013CType cc013CTypeMessage, CC015CType cc015CTypeOfLatestDeclaration) { CC015CType updatedCC015C; if (cc013CTypeMessage.getTransitOperation().getAmendmentTypeFlag().equals("1")) { CC015CType cc015cUpdatedGuarantee = messageTypeMapper.fromCC013toCC015CTypeGuranteeAmend(cc013CTypeMessage); updatedCC015C = cc015CTypeOfLatestDeclaration; updatedCC015C.getGuarantee().clear(); updatedCC015C.getGuarantee().addAll(cc015cUpdatedGuarantee.getGuarantee()); } else { updatedCC015C = messageTypeMapper.fromCC013toCC015CType(cc013CTypeMessage); updatedFieldsOfCC015CMessage(cc015CTypeOfLatestDeclaration, updatedCC015C); } updatedCC015C.setPreparationDateAndTime(LocalDateTime.now()); return updatedCC015C; } @SneakyThrows private CC015CType createNewDeclarationBasedOnCC170(CC170CType cc170cTypeMessage, CC015CType cc015CTypeOfLatestDeclaration) { //Representative amendment cc015CTypeOfLatestDeclaration.setRepresentative(cc170cTypeMessage.getRepresentative()); //Consignment level amendments cc015CTypeOfLatestDeclaration.getConsignment().setInlandModeOfTransport(cc170cTypeMessage.getConsignment().getInlandModeOfTransport()); cc015CTypeOfLatestDeclaration.getConsignment().setContainerIndicator(cc170cTypeMessage.getConsignment().getContainerIndicator()); cc015CTypeOfLatestDeclaration.getConsignment().setModeOfTransportAtTheBorder(cc170cTypeMessage.getConsignment().getModeOfTransportAtTheBorder()); cc015CTypeOfLatestDeclaration.getConsignment().setPlaceOfLoading(cc170cTypeMessage.getConsignment().getPlaceOfLoading()); cc015CTypeOfLatestDeclaration.getConsignment().setLocationOfGoods( messageTypeMapper.fromLocationOfGoodsType03ToType05(cc170cTypeMessage.getConsignment().getLocationOfGoods())); cc015CTypeOfLatestDeclaration.getConsignment().getDepartureTransportMeans().clear(); cc015CTypeOfLatestDeclaration.getConsignment() .getDepartureTransportMeans() .addAll(messageTypeMapper.fromDepartureTransportMeansType05ToType03List( cc170cTypeMessage.getConsignment().getDepartureTransportMeans())); cc015CTypeOfLatestDeclaration.getConsignment().getActiveBorderTransportMeans().clear(); cc015CTypeOfLatestDeclaration.getConsignment() .getActiveBorderTransportMeans() .addAll(messageTypeMapper.fromActiveBorderTransportMeansType03ToType02List( cc170cTypeMessage.getConsignment().getActiveBorderTransportMeans())); cc015CTypeOfLatestDeclaration.getConsignment().getTransportEquipment().clear(); cc015CTypeOfLatestDeclaration.getConsignment().getTransportEquipment().addAll(cc170cTypeMessage.getConsignment().getTransportEquipment()); //HouseConsignment level amendments cc015CTypeOfLatestDeclaration.getConsignment().getHouseConsignment().forEach(cc015cHouseConsignment -> { HouseConsignmentType06 matchedHouseConsignment = cc170cTypeMessage.getConsignment().getHouseConsignment().stream().filter(cc170cHouseConsignment -> cc015cHouseConsignment.getSequenceNumber().equals(cc170cHouseConsignment.getSequenceNumber())) .findFirst() .orElse(null); if (matchedHouseConsignment != null) { cc015cHouseConsignment.getDepartureTransportMeans().clear(); cc015cHouseConsignment.getDepartureTransportMeans().addAll(matchedHouseConsignment.getDepartureTransportMeans()); } }); return cc015CTypeOfLatestDeclaration; } private CC015CType amendDeclarationWithAcceptGuaranteeEvent(AcceptGuaranteeEvent acceptGuaranteeEvent, CC015CType cc015CTypeMessageOfLastDeclaration) { cc015CTypeMessageOfLastDeclaration.getGuarantee().clear(); cc015CTypeMessageOfLastDeclaration.getGuarantee().addAll(acceptGuaranteeEvent.getGuarantee()); return cc015CTypeMessageOfLastDeclaration; } private void updatedFieldsOfCC015CMessage(CC015CType cc015CTypeOfLatestDeclaration, CC015CType updatedCC015C) { updatedCC015C.setMessageRecipient(cc015CTypeOfLatestDeclaration.getMessageRecipient()); updatedCC015C.setMessageSender(cc015CTypeOfLatestDeclaration.getMessageSender()); updatedCC015C.setPreparationDateAndTime(cc015CTypeOfLatestDeclaration.getPreparationDateAndTime()); updatedCC015C.setMessageIdentification(cc015CTypeOfLatestDeclaration.getMessageIdentification()); updatedCC015C.setMessageType(cc015CTypeOfLatestDeclaration.getMessageType()); updatedCC015C.setCorrelationIdentifier(cc015CTypeOfLatestDeclaration.getCorrelationIdentifier()); // PSD-3285. If the CC013C does not have an <LRN> element, then copy the LRN from the latest Declaration that should ALWAYS have a value if(StringUtils.isBlank(updatedCC015C.getTransitOperation().getLRN())) { log.info("updatedFieldsOfCC015CMessage()-1 : Will set the LRN of the newly created Declaration as the LRN of the latest one: [{}]", cc015CTypeOfLatestDeclaration.getTransitOperation().getLRN()); updatedCC015C.getTransitOperation().setLRN(cc015CTypeOfLatestDeclaration.getTransitOperation().getLRN()); } else { log.info("updatedFieldsOfCC015CMessage()-2 : Will update the LRN of the newly created Declaration from the one of the new Message: [{}]", updatedCC015C.getTransitOperation().getLRN()); } } private CC015CType updateCc015CTypeWithAcceptGuaranteeEvent(String movementId, CC015CType cc015CTypeOfLatestDeclaration) { List<MessageOverview> acceptGuaranteeMessageOverviewList = dossierDataService.getMessagesOverview(movementId, AcceptGuaranteeEvent.class.getSimpleName()); if (acceptGuaranteeMessageOverviewList.isEmpty()) { log.error("No message with type AcceptGuaranteeEvent found for movementId: {}", movementId); return null; } Message acceptGuaranteeMessage = dossierDataService.getMessageById(acceptGuaranteeMessageOverviewList.get(0).getId()); AcceptGuaranteeEvent acceptGuaranteeEvent = JSON_CONVERTER.convertStringToObject(acceptGuaranteeMessage.getPayload(), AcceptGuaranteeEvent.class); return amendDeclarationWithAcceptGuaranteeEvent(acceptGuaranteeEvent, cc015CTypeOfLatestDeclaration); } private CC015CType updateCc015CTypeWithCc013C(String movementId, boolean isFallbackDeclaration, CC015CType cc015CTypeOfLatestDeclaration) throws JAXBException { List<MessageOverview> cc013cMessageOverviewList = dossierDataService.getMessagesOverview(movementId, MessageTypes.CC_013_C.value()); return updateCc015CType(movementId, isFallbackDeclaration, cc015CTypeOfLatestDeclaration, cc013cMessageOverviewList); } private CC015CType updateCc015CTypeWithCc170C(String ie170MessageId, CC015CType cc015CTypeOfLatestDeclaration) throws JAXBException { Message cc170Message = dossierDataService.getMessageById(ie170MessageId); CC170CType cc170CTypeMessage = XmlConverter.buildMessageFromXML(cc170Message.getPayload(), CC170CType.class); return createNewDeclarationBasedOnCC170(cc170CTypeMessage, cc015CTypeOfLatestDeclaration); } private void updateMovementWithAmendment(String movementId, String messageId) throws JAXBException { Message cc013Message = dossierDataService.getMessageById(messageId); CC013CType cc013Payload = XmlConverter.buildMessageFromXML(cc013Message.getPayload(), CC013CType.class); String customsOfficeOfDestinationDeclared = cc013Payload.getCustomsOfficeOfDestinationDeclared().getReferenceNumber(); String countryOfDestination = MessageUtil.extractOfficeCountryCode(customsOfficeOfDestinationDeclared); Movement movement = dossierDataService.getMovementById(movementId); movement.setCountryOfDestination(countryOfDestination); movement.setOfficeOfDestination(customsOfficeOfDestinationDeclared); dossierDataService.updateMovement(movement); } }
package com.intrasoft.ermis.trs.officeofdeparture.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC013CType; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.officeofdeparture.domain.Declaration; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.service.AmendmentRequestServiceImpl; import com.intrasoft.ermis.trs.officeofdeparture.util.GeneratorHelper; import java.util.List; import javax.xml.bind.JAXBException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class AmendmentRequestServiceUT extends GeneratorHelper { @InjectMocks private AmendmentRequestServiceImpl amendmentRequestService; private static Movement createMovement(String countryOfDestination, String customsOfficeOfDestinationDeclared) { Movement expectedMovement = new Movement(); expectedMovement.setCountryOfDestination(countryOfDestination); expectedMovement.setOfficeOfDestination(customsOfficeOfDestinationDeclared); return expectedMovement; } @Test void test_amendment_with_ie013_having_NotNull_LRN() { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); CC013CType cc013Type = XmlConverter.buildMessageFromXML(loadTextFile("CC013C"), CC013CType.class); Message cc013cMessage = createCC013CMessage(cc013Type); Declaration existingDeclaration = createDeclaration(cc015CType); when(dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID)).thenReturn(existingDeclaration); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CC_013_C.value())).thenReturn(List.of(cc013cMessage)); when(dossierDataService.getMessageById(anyString())).thenReturn(cc013cMessage); when(dossierDataService.getMovementById(anyString())).thenReturn(new Movement()); Declaration newDeclaration = amendmentRequestService.amendDeclarationAndCreateNewVersion(MOVEMENT_ID, MESSAGE_ID, MessageTypes.CC_013_C.value(), false); CC015CType cc015CTypeOfDeclarationCreated = XmlConverter.buildMessageFromXML(newDeclaration.getPayload(), CC015CType.class); assertEquals(cc015CTypeOfDeclarationCreated.getTransitOperation().getLRN(), cc013Type.getTransitOperation().getLRN()); assertEquals(newDeclaration.getVersion(), existingDeclaration.getVersion() + 1); verify(dossierDataService).updateMovement(createMovement(cc013Type.getConsignment().getCountryOfDestination(), cc013Type.getCustomsOfficeOfDestinationDeclared().getReferenceNumber())); } catch (JAXBException e) { fail(); } } @Test void test_amendment_with_ie013_having_Null_LRN() { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); CC013CType cc013Type = XmlConverter.buildMessageFromXML(loadTextFile("CC013C"), CC013CType.class); cc013Type.getTransitOperation().setLRN(null); Message cc013cMessage = createCC013CMessage(cc013Type); Declaration existingDeclaration = createDeclaration(cc015CType); when(dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID)).thenReturn(existingDeclaration); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CC_013_C.value())).thenReturn(List.of(cc013cMessage)); when(dossierDataService.getMessageById(anyString())).thenReturn(cc013cMessage); when(dossierDataService.getMovementById(anyString())).thenReturn(new Movement()); Declaration newDeclaration = amendmentRequestService.amendDeclarationAndCreateNewVersion(MOVEMENT_ID, MESSAGE_ID, MessageTypes.CC_013_C.value(), false); CC015CType cc015CTypeOfDeclarationCreated = XmlConverter.buildMessageFromXML(newDeclaration.getPayload(), CC015CType.class); assertEquals(cc015CTypeOfDeclarationCreated.getTransitOperation().getLRN(), cc015CType.getTransitOperation().getLRN()); assertEquals(newDeclaration.getVersion(), existingDeclaration.getVersion() + 1); verify(dossierDataService).updateMovement(createMovement(cc013Type.getConsignment().getCountryOfDestination(), cc013Type.getCustomsOfficeOfDestinationDeclared().getReferenceNumber())); } catch (JAXBException e) { fail(); } } private Message createCC013CMessage(CC013CType cc013CType) { return Message.builder() .id(MESSAGE_ID) .messageType(MessageTypes.CC_013_C.value()) .payload(XmlConverter.marshal(cc013CType)) .build(); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.validation.service; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.common.drools.core.RuleService; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.contracts.core.dto.declaration.common.CustomsData; import com.intrasoft.ermis.contracts.core.dto.declaration.common.CustomsDataPayloadContentTypeEnum; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.ValidationResultDTO; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.events.ExternalValidationRequestEvent; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.events.ExternalValidationResponseEvent; import com.intrasoft.ermis.platform.contracts.dossier.dtos.MessageDTO; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.platform.shared.client.reference.data.core.ReferenceDataAdapter; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListDomain; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.enums.ValidationStrategyEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import com.intrasoft.ermis.transit.contracts.core.enums.RegimeEnum; import com.intrasoft.ermis.transit.validation.Declaration; import com.intrasoft.ermis.transit.validation.Movement; import com.intrasoft.ermis.transit.validation.Request; import com.intrasoft.ermis.transit.validation.Response; import com.intrasoft.ermis.transit.validation.ValidationResult; import com.intrasoft.ermis.transit.validation.builders.ValidationMessageWrapperBuilder; import com.intrasoft.ermis.transit.validation.configuration.ValidationDDNTASpecificationConfigurationProperties; import com.intrasoft.ermis.transit.validation.drools.domain.ExternalSystemValidationInstruction; import com.intrasoft.ermis.transit.validation.drools.rules.ValidationMessageWrapper; import com.intrasoft.ermis.transit.validation.enums.BRSessionEnum; import com.intrasoft.ermis.transit.validation.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.validation.enums.BpmnMessageNamesEnum; import com.intrasoft.ermis.transit.validation.enums.ExternalValidationRequestStatusEnum; import com.intrasoft.ermis.transit.validation.port.outbound.ExternalSystemValidationRequestProducer; import com.intrasoft.ermis.transit.validation.port.outbound.mapper.SharedKernelValidationResultMapper; import com.intrasoft.ermis.transit.validation.port.outbound.mapper.ValidationResultDTOMapper; import com.intrasoft.proddev.referencedata.shared.enums.CodelistKeyEnum; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class ExternalSystemValidationServiceImpl implements ExternalSystemValidationService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); // Configuration Rules: private static final String TRANSIT_EXTERNAL_SYSTEM_VALIDATION_SWITCH_RS = "getTransitExternalSystemValidationSwitchRS"; private static final String TRANSIT_EXTERNAL_SYSTEM_VALIDATION_RESPONSE_TIMER_RS = "getTransitExternalSystemValidationResponseDelayTimerRS"; private static final String BUNDLE_DECLARATION_IN_EXTERNAL_SYSTEM_VALIDATION_RS = "getBundleDeclarationInExternalSystemValidationRS"; private static final String APPLICABLE_MESSAGE_TYPES_FOR_DECLARATION_BUNDLING_RS = "getApplicableMessageTypesForDeclarationBundlingRS"; // Evaluation parameter literals: private static final String SWITCH_VALUE_LITERAL = "switchValue"; private static final String ENABLED_LITERAL = "enabled"; private static final String APPLICABLE_MESSAGE_TYPES_LITERAL = "applicableMessageTypes"; // Autowired beans: private final ErmisLogger log; private final ValidationDDNTASpecificationConfigurationProperties validationDDNTASpecificationConfigurationProperties; private final TimerDelayExecutor timerDelayExecutor; private final ErmisConfigurationService ermisConfigurationService; private final ReferenceDataAdapter referenceDataAdapter; private final TransitionPeriodService transitionPeriodService; private final DossierDataService dossierDataService; private final GetCountryCodeService getCountryCodeService; private final RuleService ruleService; private final ValidationResultDTOMapper validationResultDTOMapper; private final SharedKernelValidationResultMapper sharedKernelValidationResultMapper; private final BpmnEngine bpmnEngine; private final ExternalSystemValidationRequestProducer externalSystemValidationRequestProducer; private final ValidationMessageWrapperBuilder validationMessageWrapperBuilder; @Override public boolean isExternalSystemValidationEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(TRANSIT_EXTERNAL_SYSTEM_VALIDATION_SWITCH_RS); boolean isEnabled = "enabled".equals(configuration.getEvaluationParams().get(SWITCH_VALUE_LITERAL).toLowerCase(Locale.ROOT)); // Log message to correct invalid value detected in Configuration, while method defaults to false: if (!("enabled".equals(configuration.getEvaluationParams().get(SWITCH_VALUE_LITERAL).toLowerCase(Locale.ROOT))) && !("disabled".equals(configuration.getEvaluationParams().get(SWITCH_VALUE_LITERAL).toLowerCase(Locale.ROOT)))) { log.warn("Switch parameter in BR20026 contains invalid value: {}. " + "Please correct with \"enabled\" or \"disabled\". " + "Defaulting to \"disabled\".", configuration.getEvaluationParams().get(SWITCH_VALUE_LITERAL)); } return isEnabled; } @Override public void initiateExternalSystemValidationProcess(String processBusinessKey, Map<String, Object> values) { log.info("ENTER initiateExternalSystemValidationProcess() with processBusinessKey: {}", processBusinessKey); CorrelateBpmnMessageCommand correlateBpmnMessageCommand = CorrelateBpmnMessageCommand .builder() .messageName(BpmnMessageNamesEnum.REQUEST_EXTERNAL_SYSTEM_VALIDATION_MESSAGE.getValue()) .businessKey(processBusinessKey) .values(values) .build(); bpmnEngine.correlateMessage(correlateBpmnMessageCommand); log.info("EXIT initiateExternalSystemValidationProcess() with processBusinessKey: {}", processBusinessKey); } @Override public List<ExternalSystemValidationInstruction> determineExternalSystems(String messageId) { MessageDTO messageDTO = dossierDataService.getMessageByMessageId(messageId); ValidationMessageWrapper messageWrapper = validationMessageWrapperBuilder.buildValidationMessageWrapper(messageDTO, transitionPeriodService.getNCTSTPAndL3EndDates()); List<Object> facts = new ArrayList<>(); facts.add(messageWrapper); Map<String, Object> globals = new HashMap<>(); globals.put("externalSystemInstructionList", new ArrayList<ExternalSystemValidationInstruction>()); ruleService.executeStateless(BRSessionEnum.EXTERNAL_SYSTEM_INSTRUCTION_IDENTIFICATION_RS.getSessionName(), globals, facts); @SuppressWarnings("unchecked") List<ExternalSystemValidationInstruction> externalSystemList = (List<ExternalSystemValidationInstruction>) globals.get("externalSystemInstructionList"); return externalSystemList; } @Override public boolean externalSystemValidationInstructionsExist(List<ExternalSystemValidationInstruction> externalSystemValidationInstructionList) { if (externalSystemValidationInstructionList != null) { return !externalSystemValidationInstructionList.isEmpty(); } else { throw new BaseException("externalSystemValidationInstructionsExist(): ERROR - externalSystemValidationInstructionList was NULL!"); } } @Override public TimerInfo getExternalSystemResponseTimerDelayConfiguration() { return timerDelayExecutor.getTimerDelayConfig(LocalDateTime.now(ZoneOffset.UTC), LocalDateTime.now(ZoneOffset.UTC), TRANSIT_EXTERNAL_SYSTEM_VALIDATION_RESPONSE_TIMER_RS, false) .orElseThrow(() -> new BaseException("Failed to setup External System Response timer!")); } @Override public void sendExternalValidationRequest(String requestId, String externalSystem, String messageId) { ExternalValidationRequestEvent externalValidationRequestEvent = buildExternalValidationRequestEvent(requestId, externalSystem, messageId); String requestMessageId = persistExternalValidationRequestEvent(externalValidationRequestEvent); persistRequest(requestId, requestMessageId, messageId); externalSystemValidationRequestProducer.publishExternalSystemValidationRequest(externalValidationRequestEvent); } @Override public void handleExternalSystemValidationResponse(String messageId, String externalSystem, String requestId, boolean isRejecting) { try { Map<String, Object> values = new HashMap<>(); values.put(BpmnFlowVariablesEnum.EXTERNAL_SYSTEM_VALIDATION_REJECTION_VALUE_CHILD_LOCAL.getValue(), isRejecting); CorrelateBpmnMessageCommand correlateBpmnMessageCommand = CorrelateBpmnMessageCommand.builder() .messageName( BpmnMessageNamesEnum.EXTERNAL_VALIDATION_RESPONSE_RECEIVED_MESSAGE.getValue()) .processInstanceId(requestId) .values(values) .build(); bpmnEngine.correlateMessage(correlateBpmnMessageCommand); log.info("Successfully correlated {} External System Validation Results for Message with ID: {}", externalSystem, messageId); } catch (Exception e) { throw new BaseException("ERROR: Could not correlate BPMN Command for Message with ID: " + messageId, e); } } @Override public List<ValidationResult> persistExternalSystemValidationResults(List<ValidationResult> validationResultList) { if (validationResultList != null) { return validationResultDTOMapper.toDomain(dossierDataService.saveValidationResults(validationResultDTOMapper.toDTO(validationResultList))); } else { return new ArrayList<>(); } } @Override public void handleRequestTimeout(String messageId) { // Find all Requests for the Message undergoing validation that are still PENDING: List<Request> requestList = dossierDataService.getRequestsByCriteria(null, messageId, ExternalValidationRequestStatusEnum.PENDING.name()); // For each Request found, retrieve the ExternalValidationRequestEvent Messages and save their Destination (External System): List<String> externalSystemList = new ArrayList<>(); requestList.forEach(request -> externalSystemList.add(dossierDataService.getMessageByMessageId(request.getRequestMessageId()).getDestination())); // Place External Systems as a JSON Array in ValidationResult's pointer field: String jsonArrayPointer = JSON_CONVERTER.convertToJsonString(externalSystemList); // Update each Request's status to 'EXPIRED': requestList.forEach(request -> dossierDataService.updateRequestStatus(request.getId(), ExternalValidationRequestStatusEnum.EXPIRED.name())); // Persist informative Validation Result that holds the External Systems for which the timer expired: List<ValidationResult> validationResultList = new ArrayList<>(); ValidationResult informativeValidationResult = ValidationResult.builder() .messageId(messageId) .createdDateTime(LocalDateTime.now(ZoneOffset.UTC)) .rejecting(false) .ruleId("SLA_TIMER_EXPIRATION") .errorCode("INTERNAL") .pointer(jsonArrayPointer) .build(); validationResultList.add(informativeValidationResult); dossierDataService.saveValidationResults(validationResultDTOMapper.toDTO(validationResultList)); } @Override public void propagateExternalSystemValidationResults(String messageId, List<Boolean> validationRejectionList) { boolean isRejecting = validationRejectionList.stream().anyMatch(Boolean.TRUE::equals); CorrelateBpmnMessageCommand messageCommand = CorrelateBpmnMessageCommand.builder() .businessKey(messageId) .messageName(convertStrategyToMessageName( ValidationStrategyEnum.EXTERNAL_SYSTEM_VALIDATION_STRATEGY.getStrategy())) .value(BpmnFlowVariablesEnum.IS_REJECTING.getValue(), isRejecting) .build(); bpmnEngine.correlateMessage(messageCommand); } @Override public List<ValidationResult> mapToTransitValidationResultList(List<ValidationResultDTO> externalValidationResultList, String businessKey) { List<ValidationResult> validationResultList = new ArrayList<>(); externalValidationResultList.forEach(validationResultDTO -> { boolean isRejecting = referenceDataAdapter.verifyCodeListItem(CodelistKeyEnum.VALIDATION_RESULT_TYPES.getKey(), validationResultDTO.getValidationResultType(), LocalDate.now(ZoneOffset.UTC), null, CodeListDomain.ERMIS) && referenceDataAdapter.verifyCodeListItem(CodelistKeyEnum.REJECTING_VALIDATION_RESULTS.getKey(), validationResultDTO.getValidationResultType(), LocalDate.now(ZoneOffset.UTC), null, CodeListDomain.ERMIS); ValidationResult validationResult = sharedKernelValidationResultMapper.toDomain(validationResultDTO); validationResult.setRejecting(isRejecting); validationResult.setMessageId(businessKey); validationResultList.add(validationResult); }); return validationResultList; } @Override public boolean isResponseExpected(String requestId) { try { return ExternalValidationRequestStatusEnum.PENDING.name().equals(dossierDataService.getRequestById(requestId).getStatus()); } catch (Exception e) { return false; } } @Override public String persistExternalSystemValidationResponse(ExternalValidationResponseEvent externalValidationResponseEvent) { return persistExternalValidationResponseEvent(externalValidationResponseEvent); } @Override public void persistResponse(String responseId, String requestId, String responseMessageId, boolean finalResponse) { Response response = Response.builder() .id(responseId) .responseMessageId(responseMessageId) .requestId(requestId) .finalResponse(finalResponse) .createdDateTime(LocalDateTime.now(ZoneOffset.UTC)) .build(); dossierDataService.saveResponse(response); } @Override public void updateRequestStatus(String id, String status) { dossierDataService.updateRequestStatus(id, status); } private ExternalValidationRequestEvent buildExternalValidationRequestEvent(String requestId, String externalSystem, String messageId) { try { MessageDTO messageDTO = dossierDataService.getMessageByMessageId(messageId); ExternalValidationRequestEvent externalValidationRequestEvent = new ExternalValidationRequestEvent(); externalValidationRequestEvent.setRequestId(requestId); externalValidationRequestEvent.setExternalSystem(externalSystem); // In Validation, businessKey == messageId: externalValidationRequestEvent.setBusinessKey(messageId); externalValidationRequestEvent.setRegime(RegimeEnum.TRANSIT.getValue()); externalValidationRequestEvent.setReferenceDate(messageDTO.getCreatedDateTime()); // Populate Validation Data (Customs Data): externalValidationRequestEvent.setValidationData(buildCustomsDataSet(messageDTO)); return externalValidationRequestEvent; } catch (Exception e) { throw new BaseException("ERROR building ExternalValidationRequestEvent for Message with ID: " + messageId, e); } } private Set<CustomsData> buildCustomsDataSet(MessageDTO messageDTO) { Set<CustomsData> customsDataSet = new HashSet<>(); // Default customsData: CustomsData customsData = new CustomsData(); customsData.setSequenceNumber(BigInteger.ONE); customsData.setPayloadSpec(validationDDNTASpecificationConfigurationProperties.getDDNTASpecification()); customsData.setType(messageDTO.getMessageType()); customsData.setPayloadType(CustomsDataPayloadContentTypeEnum.XML.toString()); customsData.setPayload(messageDTO.getPayload()); customsDataSet.add(customsData); // Configurable customsData - extension to add Declaration: boolean includeDeclaration = shouldIncludeDeclaration(); // Check applicability and take proper actions: if (includeDeclaration) { List<String> applicableMessageTypes = getApplicableMessageTypes(); if (applicableMessageTypes.contains(messageDTO.getMessageType())) { // Fetch associated Movement via messageId: Movement movement = dossierDataService.findAssociatedMovementViaMessageId(messageDTO.getId()); // Retrieve Declaration via movementId: Declaration declaration = dossierDataService.findLatestDeclarationViaMovementId(movement.getId()); // Set appropriate data: CustomsData declarationCustomsData = new CustomsData(); declarationCustomsData.setSequenceNumber(BigInteger.TWO); declarationCustomsData.setPayloadSpec(validationDDNTASpecificationConfigurationProperties.getDDNTASpecification()); declarationCustomsData.setType(declaration.getPayloadType()); declarationCustomsData.setPayloadType(CustomsDataPayloadContentTypeEnum.XML.toString()); declarationCustomsData.setPayload(declaration.getPayload()); customsDataSet.add(declarationCustomsData); } } return customsDataSet; } private boolean shouldIncludeDeclaration() { // Retrieve configuration: Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(BUNDLE_DECLARATION_IN_EXTERNAL_SYSTEM_VALIDATION_RS); return Boolean.parseBoolean(configuration.getEvaluationParams().get(ENABLED_LITERAL)); } private List<String> getApplicableMessageTypes() { // Retrieve configuration: Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(APPLICABLE_MESSAGE_TYPES_FOR_DECLARATION_BUNDLING_RS); // Parse the CSV String parameter, upper case it, strip it from whitespaces, split it and return as list: return Arrays.stream(configuration.getEvaluationParams().get(APPLICABLE_MESSAGE_TYPES_LITERAL) .toUpperCase(Locale.ROOT) .replaceAll("\\s", "") .split(",")) .toList(); } private String persistExternalValidationRequestEvent(ExternalValidationRequestEvent externalValidationRequestEvent) { MessageDTO externalValidationRequestEventMessage = new MessageDTO(); externalValidationRequestEventMessage.setMessageType(ExternalValidationRequestEvent.class.getSimpleName()); externalValidationRequestEventMessage.setPayload(JSON_CONVERTER.convertToJsonString(externalValidationRequestEvent)); externalValidationRequestEventMessage.setSource(MessageTypeMapper.NTA + getCountryCodeService.getCountryCode()); externalValidationRequestEventMessage.setDestination(externalValidationRequestEvent.getExternalSystem()); externalValidationRequestEventMessage.setDomain(MessageDomainTypeEnum.ERMIS.name()); // ID of Message undergoing validation: externalValidationRequestEventMessage.setMessageIdentification(externalValidationRequestEvent.getBusinessKey()); externalValidationRequestEventMessage.setDirection(DirectionEnum.SENT.getDirection()); return dossierDataService.saveMessage(externalValidationRequestEventMessage).getId(); } private void persistRequest(String requestId, String requestMessageId, String referencedMessageId) { Request request = Request.builder() .id(requestId) .requestMessageId(requestMessageId) .referencedMessageId(referencedMessageId) .status(ExternalValidationRequestStatusEnum.PENDING.name()) .createdDateTime(LocalDateTime.now(ZoneOffset.UTC)) .build(); dossierDataService.saveRequest(request); } private String persistExternalValidationResponseEvent(ExternalValidationResponseEvent externalValidationResponseEvent) { MessageDTO externalValidationResponseEventMessage = new MessageDTO(); externalValidationResponseEventMessage.setMessageType(ExternalValidationResponseEvent.class.getSimpleName()); externalValidationResponseEventMessage.setPayload(JSON_CONVERTER.convertToJsonString(externalValidationResponseEvent)); externalValidationResponseEventMessage.setSource(externalValidationResponseEvent.getExternalSystem()); externalValidationResponseEventMessage.setDestination(MessageTypeMapper.NTA + getCountryCodeService.getCountryCode()); externalValidationResponseEventMessage.setDomain(MessageDomainTypeEnum.ERMIS.name()); // ID of Message undergoing validation: externalValidationResponseEventMessage.setMessageIdentification(externalValidationResponseEvent.getBusinessKey()); externalValidationResponseEventMessage.setDirection(DirectionEnum.RECEIVED.getDirection()); return dossierDataService.saveMessage(externalValidationResponseEventMessage).getId(); } private String convertStrategyToMessageName(String strategy) { strategy = StringUtils.uncapitalize(strategy); return strategy.replace("ValidationStrategy", "ValidationCompletedMessage"); } }
package com.intrasoft.ermis.transit.validation.service; import static com.intrasoft.ermis.transit.validation.util.DataGenerators.createIE015Message; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.common.drools.core.RuleService; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.contracts.core.dto.declaration.common.CustomsData; import com.intrasoft.ermis.contracts.core.dto.declaration.common.CustomsDataPayloadContentTypeEnum; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.RuleDTO; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.ValidationInformationDTO; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.ValidationResultDTO; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.events.ExternalValidationRequestEvent; import com.intrasoft.ermis.contracts.core.dto.declaration.validation.v2.events.ExternalValidationResponseEvent; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.platform.shared.client.reference.data.core.ReferenceDataAdapter; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.Attribute; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListDomain; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListItem; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.common.util.Pair; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import com.intrasoft.ermis.transit.contracts.core.enums.RegimeEnum; import com.intrasoft.ermis.transit.contracts.core.enums.TimeUnitEnum; import com.intrasoft.ermis.platform.contracts.dossier.dtos.MessageDTO; import com.intrasoft.ermis.transit.validation.Request; import com.intrasoft.ermis.transit.validation.Response; import com.intrasoft.ermis.transit.validation.ValidationResult; import com.intrasoft.ermis.transit.validation.builders.ValidationMessageWrapperBuilder; import com.intrasoft.ermis.transit.validation.configuration.ValidationDDNTASpecificationConfigurationProperties; import com.intrasoft.ermis.transit.validation.drools.domain.ExternalSystemValidationInstruction; import com.intrasoft.ermis.transit.validation.enums.BRSessionEnum; import com.intrasoft.ermis.transit.validation.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.validation.enums.BpmnMessageNamesEnum; import com.intrasoft.ermis.transit.validation.enums.ExternalValidationRequestStatusEnum; import com.intrasoft.ermis.transit.validation.message.MessageHelper; import com.intrasoft.ermis.transit.validation.port.outbound.ExternalSystemValidationRequestProducer; import com.intrasoft.ermis.transit.validation.port.outbound.mapper.SharedKernelValidationResultMapper; import com.intrasoft.ermis.transit.validation.port.outbound.mapper.SharedKernelValidationResultMapperImpl; import com.intrasoft.ermis.transit.validation.port.outbound.mapper.ValidationResultDTOMapper; import com.intrasoft.ermis.transit.validation.port.outbound.mapper.ValidationResultDTOMapperImpl; import com.intrasoft.proddev.referencedata.shared.enums.CodelistKeyEnum; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ExternalSystemValidationServiceUT { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String TRANSIT_EXTERNAL_SYSTEM_VALIDATION_SWITCH_RS = "getTransitExternalSystemValidationSwitchRS"; private final static String PROCESS_BUSINESS_KEY = UUID.randomUUID().toString(); private final static String MESSAGE_ID = "messageId"; private final static String EXTERNAL_SYSTEM = "externalSystem"; private final static String VALIDATION_RESULT_TYPE = "testValidationResultType"; private ExternalValidationRequestEvent externalValidationRequestEventActual; @Mock private ErmisLogger ermisLogger; @Mock private ValidationDDNTASpecificationConfigurationProperties validationDDNTASpecificationConfigurationProperties; @Mock private TimerDelayExecutor timerDelayExecutor; @Mock private ErmisConfigurationService ermisConfigurationService; @Mock private ReferenceDataAdapter referenceDataAdapter; @Mock private BpmnEngine bpmnEngine; @Mock private DossierDataService dossierDataService; @Mock private TransitionPeriodService transitionPeriodService; @Mock private GetCountryCodeService getCountryCodeService; @Mock private RuleService ruleService; @Spy private ValidationResultDTOMapper validationResultDTOMapper = new ValidationResultDTOMapperImpl(); @Spy private final SharedKernelValidationResultMapper sharedKernelValidationResultMapper = new SharedKernelValidationResultMapperImpl(); @Mock private ValidationMessageWrapperBuilder validationMessageWrapperBuilder = new ValidationMessageWrapperBuilder(new MessageHelper(new ArrayList<>())); @Spy private ExternalSystemValidationRequestProducer externalSystemValidationRequestProducer = new ExternalSystemValidationRequestProducer() { @Override public void publishExternalSystemValidationRequest(ExternalValidationRequestEvent externalValidationRequestEvent) { externalValidationRequestEventActual = externalValidationRequestEvent; } }; @InjectMocks private ExternalSystemValidationServiceImpl externalSystemValidationService; @Captor private ArgumentCaptor<CorrelateBpmnMessageCommand> correlateBpmnMessageCommandArgumentCaptor; @Captor private ArgumentCaptor<MessageDTO> externalValidationResponseEventMessageArgumentCaptor; @Captor private ArgumentCaptor<Response> responseArgumentCaptor; @Captor private ArgumentCaptor<String> statusArgumentCaptor; @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - Is External System Validation Enabled") void testIsExternalSystemValidationEnabled(boolean isExternalSystemValidationEnabled) { Configuration configuration = buildConfigurationDTO(isExternalSystemValidationEnabled); // Mocks: when(ermisConfigurationService.getConfigurationByTemplateName(TRANSIT_EXTERNAL_SYSTEM_VALIDATION_SWITCH_RS)) .thenReturn(configuration); try { // Call tested method of service: boolean returnedValue = externalSystemValidationService.isExternalSystemValidationEnabled(); // Assertion: assertEquals(isExternalSystemValidationEnabled, returnedValue); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Initiate External System Validation Process") void testInitiateExternalSystemValidationProcess() { CorrelateBpmnMessageCommand correlateBpmnMessageCommandExpected = buildBpmnMessageCommand(BpmnMessageNamesEnum.REQUEST_EXTERNAL_SYSTEM_VALIDATION_MESSAGE.getValue(), PROCESS_BUSINESS_KEY, new HashMap<>()); try { // Call tested method of service: externalSystemValidationService.initiateExternalSystemValidationProcess(PROCESS_BUSINESS_KEY, new HashMap<>()); // Verification & Assertions: verify(bpmnEngine, times(1)).correlateMessage(correlateBpmnMessageCommandArgumentCaptor.capture()); assertEquals(correlateBpmnMessageCommandExpected.getBusinessKey(), correlateBpmnMessageCommandArgumentCaptor.getValue().getBusinessKey()); assertEquals(correlateBpmnMessageCommandExpected.getMessageName(), correlateBpmnMessageCommandArgumentCaptor.getValue().getMessageName()); assertEquals(correlateBpmnMessageCommandExpected.getValues(), correlateBpmnMessageCommandArgumentCaptor.getValue().getValues()); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Determine External Systems") void testDetermineExternalSystems() { MessageDTO messageDTO = buildMessageDTO(null, MessageTypes.CC_015_C.value(), null, createIE015Message()); // Mocks: when(dossierDataService.getMessageByMessageId(MESSAGE_ID)) .thenReturn(messageDTO); when(transitionPeriodService.getNCTSTPAndL3EndDates()) .thenReturn(new Pair<>(LocalDate.now(), LocalDate.now())); try { // Call tested method of service: List<ExternalSystemValidationInstruction> returnedExternalSystemValidationInstructionList = externalSystemValidationService.determineExternalSystems(MESSAGE_ID); // Verification & Assertion: verify(ruleService, times(1)) .executeStateless(eq(BRSessionEnum.EXTERNAL_SYSTEM_INSTRUCTION_IDENTIFICATION_RS.getSessionName()), any(), any()); assertEquals(0, returnedExternalSystemValidationInstructionList.size()); } catch (Exception e) { fail(); } } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - External System Validation Instructions Exist") void testExternalSystemValidationInstructionsExist(boolean externalSystemValidationInstructionsExist) { List<ExternalSystemValidationInstruction> externalSystemValidationInstructionList = buildExternalSystemValidationInstructionList(externalSystemValidationInstructionsExist); try { // Call tested method of service: boolean returnedValue = externalSystemValidationService.externalSystemValidationInstructionsExist(externalSystemValidationInstructionList); // Assertion: assertEquals(externalSystemValidationInstructionsExist, returnedValue); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Get External System Response Timer Delay Configuration") void testGetExternalSystemResponseTimerDelayConfiguration() { TimerInfo expectedTimerInfo = buildTimerInfo(); // Mocks: when(timerDelayExecutor.getTimerDelayConfig(any(), any(), any(), anyBoolean())) .thenReturn(Optional.of(expectedTimerInfo)); try { // Call tested method of service: TimerInfo timerInfo = externalSystemValidationService.getExternalSystemResponseTimerDelayConfiguration(); // Assertions: assertEquals(expectedTimerInfo.getDelay(), timerInfo.getDelay()); assertEquals(expectedTimerInfo.getUnit(), timerInfo.getUnit()); assertEquals(expectedTimerInfo.getRuleInstance(), timerInfo.getRuleInstance()); assertEquals(expectedTimerInfo.getErrorCode(), timerInfo.getErrorCode()); assertEquals(expectedTimerInfo.getTimerSetupString(), timerInfo.getTimerSetupString()); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Send External Validation Request") void testSendExternalValidationRequest() { String requestId = UUID.randomUUID().toString(); String requestMessageId = UUID.randomUUID().toString(); MessageDTO cc015cMessageDTO = buildMessageDTO(null, MessageTypes.CC_015_C.value(), null, createIE015Message()); MessageDTO requestMessageDTO = buildMessageDTO(requestMessageId, ExternalValidationRequestEvent.class.getSimpleName(), null, null); CustomsData expectedCustomsData = buildCustomsData(cc015cMessageDTO); Configuration configuration = buildConfiguration(); // Mocks: when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(dossierDataService.getMessageByMessageId(MESSAGE_ID)).thenReturn(cc015cMessageDTO); when(dossierDataService.saveMessage(any())).thenReturn(requestMessageDTO); when(validationDDNTASpecificationConfigurationProperties.getDDNTASpecification()).thenReturn("DDNTA/5.15"); when(ermisConfigurationService.getConfigurationByTemplateName("getBundleDeclarationInExternalSystemValidationRS")).thenReturn(configuration); try { // Call tested method of service: externalSystemValidationService.sendExternalValidationRequest(requestId, EXTERNAL_SYSTEM, MESSAGE_ID); // Grab produced Customs Data: List<CustomsData> customsDataArrayList = new ArrayList<>(externalValidationRequestEventActual.getValidationData()); CustomsData producedCustomsData = customsDataArrayList.get(0); CC015CType expectedPayload = XmlConverter.buildMessageFromXML(cc015cMessageDTO.getPayload(), CC015CType.class); CC015CType producedCustomsDataPayload = XmlConverter.buildMessageFromXML(producedCustomsData.getPayload(), CC015CType.class); // Verification & Assertions: verify(dossierDataService, times(1)).saveMessage(any()); verify(dossierDataService, times(1)).saveRequest(any()); verify(externalSystemValidationRequestProducer, times(1)).publishExternalSystemValidationRequest(any()); // ExternalValidationRequestEvent assertions: assertEquals(EXTERNAL_SYSTEM, externalValidationRequestEventActual.getExternalSystem()); assertEquals(RegimeEnum.TRANSIT.getValue(), externalValidationRequestEventActual.getRegime()); assertNull(externalValidationRequestEventActual.getBusinessVersion()); // CustomsData assertions: assertEquals(expectedCustomsData.getPayloadSpec(), producedCustomsData.getPayloadSpec()); assertEquals(expectedCustomsData.getPayloadType(), producedCustomsData.getPayloadType()); assertEquals(expectedCustomsData.getType(), producedCustomsData.getType()); assertEquals(expectedCustomsData.getSequenceNumber(), producedCustomsData.getSequenceNumber()); // CustomsData payload assertions: assertEquals(expectedPayload.getMessageSender(), producedCustomsDataPayload.getMessageSender()); assertEquals(expectedPayload.getMessageRecipient(), producedCustomsDataPayload.getMessageRecipient()); assertEquals(expectedPayload.getMessageIdentification(), producedCustomsDataPayload.getMessageIdentification()); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Handle External System Validation Response") void testHandleExternalSystemValidationResponse() { String requestId = UUID.randomUUID().toString(); CorrelateBpmnMessageCommand correlateBpmnMessageCommandExpected = buildBpmnMessageCommand(BpmnMessageNamesEnum.EXTERNAL_VALIDATION_RESPONSE_RECEIVED_MESSAGE.getValue(), PROCESS_BUSINESS_KEY, new HashMap<>()); correlateBpmnMessageCommandExpected.setProcessInstanceId(requestId); try { // Call tested method of service: externalSystemValidationService.handleExternalSystemValidationResponse(PROCESS_BUSINESS_KEY, EXTERNAL_SYSTEM, requestId, false); // Verification & Assertions: verify(bpmnEngine, times(1)).correlateMessage(correlateBpmnMessageCommandArgumentCaptor.capture()); assertEquals(correlateBpmnMessageCommandExpected.getMessageName(), correlateBpmnMessageCommandArgumentCaptor.getValue().getMessageName()); assertEquals(correlateBpmnMessageCommandExpected.getProcessInstanceId(), correlateBpmnMessageCommandArgumentCaptor.getValue().getProcessInstanceId()); assertTrue(correlateBpmnMessageCommandArgumentCaptor.getValue() .getValues() .containsKey( BpmnFlowVariablesEnum.EXTERNAL_SYSTEM_VALIDATION_REJECTION_VALUE_CHILD_LOCAL.getValue())); assertEquals(Boolean.FALSE, correlateBpmnMessageCommandArgumentCaptor.getValue() .getValues() .get(BpmnFlowVariablesEnum.EXTERNAL_SYSTEM_VALIDATION_REJECTION_VALUE_CHILD_LOCAL.getValue())); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Persist External System Validation Results") void testPersistExternalSystemValidationResults() { List<ValidationResult> validationResultList = buildValidationResultList(); try { // Call tested method of service: externalSystemValidationService.persistExternalSystemValidationResults(validationResultList); // Verification: verify(dossierDataService, times(1)).saveValidationResults(validationResultDTOMapper.toDTO(validationResultList)); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Handle Request Timeout") void testHandleRequestTimeout() { String requestMessageId01 = "requestMessageId01"; String requestMessageId02 = "requestMessageId02"; String externalSystem01 = "externalSystem01"; String externalSystem02 = "externalSystem02"; List<Request> requestList = new ArrayList<>(); requestList.add(buildRequest(requestMessageId01)); requestList.add(buildRequest(requestMessageId02)); MessageDTO requestMessage01 = buildMessageDTO(requestMessageId01, ExternalValidationRequestEvent.class.getSimpleName(), externalSystem01, null); MessageDTO requestMessage02 = buildMessageDTO(requestMessageId02, ExternalValidationRequestEvent.class.getSimpleName(), externalSystem02, null); // Mocks: when(dossierDataService.getRequestsByCriteria(ArgumentMatchers.isNull(), eq(MESSAGE_ID), eq(ExternalValidationRequestStatusEnum.PENDING.name()))) .thenReturn(requestList); when(dossierDataService.getMessageByMessageId(eq(requestMessageId01))).thenReturn(requestMessage01); when(dossierDataService.getMessageByMessageId(eq(requestMessageId02))).thenReturn(requestMessage02); try { // Call tested method of service: externalSystemValidationService.handleRequestTimeout(MESSAGE_ID); // Verification: verify(dossierDataService, times(1)) .getRequestsByCriteria(ArgumentMatchers.isNull(), eq(MESSAGE_ID), eq(ExternalValidationRequestStatusEnum.PENDING.name())); verify(dossierDataService, times(1)) .getMessageByMessageId(eq(requestMessageId01)); verify(dossierDataService, times(1)) .getMessageByMessageId(eq(requestMessageId02)); verify(dossierDataService, times(2)) .updateRequestStatus(anyString(), eq(ExternalValidationRequestStatusEnum.EXPIRED.name())); verify(dossierDataService, times(1)) .saveValidationResults(any()); } catch (Exception e) { fail(); } } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - Propagate External System Validation Results") void testPropagateExternalSystemValidationResults(boolean containsRejection) { List<Boolean> validationRejectionList = buildValidationRejectionMap(containsRejection); try { // Call tested method of service: externalSystemValidationService.propagateExternalSystemValidationResults(MESSAGE_ID, validationRejectionList); // Verification: verify(bpmnEngine, times(1)).correlateMessage(correlateBpmnMessageCommandArgumentCaptor.capture()); // Assertions: assertEquals(MESSAGE_ID, correlateBpmnMessageCommandArgumentCaptor.getValue().getBusinessKey()); assertEquals("externalSystemValidationCompletedMessage", correlateBpmnMessageCommandArgumentCaptor.getValue().getMessageName()); assertTrue(correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().containsKey(BpmnFlowVariablesEnum.IS_REJECTING.getValue())); assertEquals(containsRejection, correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().get(BpmnFlowVariablesEnum.IS_REJECTING.getValue())); } catch (Exception e) { fail(); } } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - Map To Transit Validation Result List") void testMapToTransitValidationResultList(boolean isRejecting) { // Mocks: when(referenceDataAdapter.verifyCodeListItem(eq(CodelistKeyEnum.VALIDATION_RESULT_TYPES.getKey()), eq(VALIDATION_RESULT_TYPE), (LocalDate) any(), any(), (CodeListDomain) any())).thenReturn(true); when(referenceDataAdapter.verifyCodeListItem(eq(CodelistKeyEnum.REJECTING_VALIDATION_RESULTS.getKey()), eq(VALIDATION_RESULT_TYPE), (LocalDate) any(), any(), (CodeListDomain) any())).thenReturn(isRejecting); List<ValidationResultDTO> externalValidationResultList = buildExternalValidationResultList(false); try { // Call tested method of service: List<ValidationResult> mappedExternalValidationResults = externalSystemValidationService.mapToTransitValidationResultList(externalValidationResultList, MESSAGE_ID); // Assertions: assertEquals(MESSAGE_ID, mappedExternalValidationResults.get(0).getMessageId()); assertEquals(externalValidationResultList.get(0).getViolatedRule().getRuleID(), mappedExternalValidationResults.get(0).getRuleId()); assertEquals(isRejecting, mappedExternalValidationResults.get(0).isRejecting()); assertEquals(externalValidationResultList.get(0).getPointers().get(0), mappedExternalValidationResults.get(0).getPointer()); assertEquals(externalValidationResultList.get(0).getInformation().get(0).getCode(), mappedExternalValidationResults.get(0).getErrorCode()); } catch (Exception e) { fail(); } } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - Map To Transit Validation Result List with Missing Data") void testMapToTransitValidationResultListWithMissingData(boolean isRejecting) { // Mocks: when(referenceDataAdapter.verifyCodeListItem(eq(CodelistKeyEnum.VALIDATION_RESULT_TYPES.getKey()), eq(VALIDATION_RESULT_TYPE), (LocalDate) any(), any(), (CodeListDomain) any())).thenReturn(true); when(referenceDataAdapter.verifyCodeListItem(eq(CodelistKeyEnum.REJECTING_VALIDATION_RESULTS.getKey()), eq(VALIDATION_RESULT_TYPE), (LocalDate) any(), any(), (CodeListDomain) any())).thenReturn(isRejecting); List<ValidationResultDTO> externalValidationResultList = buildExternalValidationResultList(true); try { // Call tested method of service: List<ValidationResult> mappedExternalValidationResults = externalSystemValidationService.mapToTransitValidationResultList(externalValidationResultList, MESSAGE_ID); // Assertions: assertEquals(MESSAGE_ID, mappedExternalValidationResults.get(0).getMessageId()); assertEquals(externalValidationResultList.get(0).getViolatedRule().getRuleID(), mappedExternalValidationResults.get(0).getRuleId()); assertEquals(isRejecting, mappedExternalValidationResults.get(0).isRejecting()); assertEquals("", mappedExternalValidationResults.get(0).getPointer()); assertEquals("", mappedExternalValidationResults.get(0).getErrorCode()); } catch (Exception e) { fail(); } } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - Is Response Expected") void testIsResponseExpected(boolean responseExpected) { String requestId = UUID.randomUUID().toString(); Request request = buildRequest(UUID.randomUUID().toString()); if (!responseExpected) { request.setStatus(ExternalValidationRequestStatusEnum.CANCELLED.name()); } // Mock: when(dossierDataService.getRequestById(eq(requestId))).thenReturn(request); try { // Call tested method of service: boolean returnedValue = externalSystemValidationService.isResponseExpected(requestId); // Verification: verify(dossierDataService, times(1)).getRequestById(eq(requestId)); // Assertion: assertEquals(responseExpected, returnedValue); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Persist External System Validation Response") void testPersistExternalSystemValidationResponse() { String responseMessageId = UUID.randomUUID().toString(); String externalSystem = "EXTERNAL_SYSTEM"; ExternalValidationResponseEvent externalValidationResponseEvent = buildExternalValidationResponseEvent(MESSAGE_ID, externalSystem); MessageDTO expectedResponseMessageDTO = buildMessageDTO(responseMessageId, ExternalValidationResponseEvent.class.getSimpleName(), externalSystem, externalValidationResponseEvent); // Mock: when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(dossierDataService.saveMessage(any())).thenReturn(expectedResponseMessageDTO); try { // Call tested method of service: externalSystemValidationService.persistExternalSystemValidationResponse(externalValidationResponseEvent); // Verification: verify(dossierDataService, times(1)).saveMessage(externalValidationResponseEventMessageArgumentCaptor.capture()); // Assertions: assertEquals(expectedResponseMessageDTO.getMessageType(), externalValidationResponseEventMessageArgumentCaptor.getValue().getMessageType()); assertEquals(expectedResponseMessageDTO.getPayload(), externalValidationResponseEventMessageArgumentCaptor.getValue().getPayload()); assertEquals(expectedResponseMessageDTO.getSource(), externalValidationResponseEventMessageArgumentCaptor.getValue().getSource()); assertEquals(expectedResponseMessageDTO.getDestination(), externalValidationResponseEventMessageArgumentCaptor.getValue().getDestination()); assertEquals(expectedResponseMessageDTO.getDomain(), externalValidationResponseEventMessageArgumentCaptor.getValue().getDomain()); assertEquals(expectedResponseMessageDTO.getMessageIdentification(), externalValidationResponseEventMessageArgumentCaptor.getValue().getMessageIdentification()); assertEquals(expectedResponseMessageDTO.getDirection(), externalValidationResponseEventMessageArgumentCaptor.getValue().getDirection()); } catch (Exception e) { fail(); } } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - Persist Response") void testPersistResponse(boolean finalResponse) { String responseId = UUID.randomUUID().toString(); String requestId = UUID.randomUUID().toString(); String responseMessageId = UUID.randomUUID().toString(); try { // Call tested method of service: externalSystemValidationService.persistResponse(responseId, requestId, responseMessageId, finalResponse); // Verification: verify(dossierDataService, times(1)).saveResponse(responseArgumentCaptor.capture()); // Assertions: assertEquals(responseId, responseArgumentCaptor.getValue().getId()); assertEquals(requestId, responseArgumentCaptor.getValue().getRequestId()); assertEquals(responseMessageId, responseArgumentCaptor.getValue().getResponseMessageId()); assertEquals(finalResponse, responseArgumentCaptor.getValue().isFinalResponse()); } catch (Exception e) { fail(); } } @ParameterizedTest @MethodSource("provideStatusArguments") @DisplayName("Test - Update Request Status") void testUpdateRequestStatus(String status) { String requestId = UUID.randomUUID().toString(); try { // Call tested method of service: externalSystemValidationService.updateRequestStatus(requestId, status); // Verification: verify(dossierDataService, times(1)).updateRequestStatus(eq(requestId), statusArgumentCaptor.capture()); // Assertion: assertEquals(status, statusArgumentCaptor.getValue()); } catch (Exception e) { fail(); } } private Request buildRequest(String requestMessageId) { return Request.builder() .id(UUID.randomUUID().toString()) .requestMessageId(requestMessageId) .referencedMessageId(MESSAGE_ID) .status(ExternalValidationRequestStatusEnum.PENDING.name()) .build(); } private <T> MessageDTO buildMessageDTO(String id, String messageType, String externalSystem, T payload) { if (ExternalValidationRequestEvent.class.getSimpleName().equals(messageType)) { return MessageDTO.builder() .id(id) .messageIdentification(MESSAGE_ID) .messageType(messageType) .direction(DirectionEnum.SENT.getDirection()) .destination(externalSystem) .build(); } else if (ExternalValidationResponseEvent.class.getSimpleName().equals(messageType)) { return MessageDTO.builder() .id(id) .messageIdentification(MESSAGE_ID) .messageType(messageType) .source(externalSystem) .payload(JSON_CONVERTER.convertToJsonString(payload)) .destination(MessageTypeMapper.NTA + "DK") .domain(MessageDomainTypeEnum.ERMIS.name()) .direction(DirectionEnum.RECEIVED.getDirection()) .build(); } else { return MessageDTO.builder() .id(id == null ? UUID.randomUUID().toString() : id) .messageIdentification(MESSAGE_ID) .messageType(messageType) .payload(XmlConverter.marshal(payload, NamespacesEnum.NTA.getValue(), MessageTypes.CC_015_C.value())) .build(); } } private CodeListItem buildCodeListItem() { List<Attribute> attributeList = new ArrayList<>(); Attribute TPEndDateAttribute = Attribute.builder().key("TPendDate").value("2025-12-25 12:00:00").build(); Attribute L3EndDateAttribute = Attribute.builder().key("L3endDate").value("2025-12-25 12:00:00").build(); attributeList.add(TPEndDateAttribute); attributeList.add(L3EndDateAttribute); return CodeListItem.builder().code("TEST_CODE").attributes(attributeList).build(); } private Configuration buildConfigurationDTO(boolean isEnabled) { Map<String, String> evaluationParams = new HashMap<>(); if (isEnabled) { evaluationParams.put("switchValue", "enabled"); } else { evaluationParams.put("switchValue", "disabled"); } return new Configuration( null, null, null, evaluationParams, null, LocalDateTime.now(ZoneOffset.UTC).minusDays(60), LocalDateTime.now(ZoneOffset.UTC).minusDays(60), LocalDateTime.now(ZoneOffset.UTC).plusDays(60)); } private CorrelateBpmnMessageCommand buildBpmnMessageCommand(String messageName, String processBusinessKey, Map<String, Object> values) { return CorrelateBpmnMessageCommand .builder() .messageName(messageName) .businessKey(processBusinessKey) .values(values) .build(); } private List<ExternalSystemValidationInstruction> buildExternalSystemValidationInstructionList(boolean isPopulated) { List<ExternalSystemValidationInstruction> externalSystemValidationInstructionList = new ArrayList<>(); if (isPopulated) { ExternalSystemValidationInstruction externalSystemValidationInstruction = new ExternalSystemValidationInstruction(); externalSystemValidationInstruction.setExternalSystem("TEST_SYSTEM"); externalSystemValidationInstructionList.add(externalSystemValidationInstruction); } return externalSystemValidationInstructionList; } private TimerInfo buildTimerInfo() { TimerInfo timerInfo = new TimerInfo(); timerInfo.setDelay(60); timerInfo.setUnit(TimeUnitEnum.MINUTES); timerInfo.setErrorCode("TEST_ERROR_CODE"); timerInfo.setRuleInstance("TEST_RULE_INSTANCE"); return timerInfo; } private List<ValidationResult> buildValidationResultList() { List<ValidationResult> validationResultList = new ArrayList<>(); ValidationResult validationResult = ValidationResult.builder().messageId(MESSAGE_ID).build(); validationResultList.add(validationResult); return validationResultList; } private List<Boolean> buildValidationRejectionMap(Boolean containsRejection) { List<Boolean> validationRejectionList = new ArrayList<>(); validationRejectionList.add(false); validationRejectionList.add(false); if (containsRejection) { validationRejectionList.add(true); } return validationRejectionList; } private CustomsData buildCustomsData(MessageDTO messageDTO) { CustomsData customsData = new CustomsData(); customsData.setSequenceNumber(BigInteger.ONE); customsData.setPayloadSpec("DDNTA/5.15"); customsData.setType(messageDTO.getMessageType()); customsData.setPayloadType(CustomsDataPayloadContentTypeEnum.XML.toString()); customsData.setPayload(messageDTO.getPayload()); return customsData; } private Configuration buildConfiguration() { Configuration configuration = new Configuration( "getBundleDeclarationInExternalSystemValidationRS", "ruleCode", new HashMap<>(), new HashMap<>(), "errorCode", LocalDateTime.now(ZoneOffset.UTC), LocalDateTime.now(ZoneOffset.UTC), LocalDateTime.now(ZoneOffset.UTC) ); // Add evaluation parameters: configuration.getEvaluationParams().put("enabled", "false"); return configuration; } private List<ValidationResultDTO> buildExternalValidationResultList(boolean missingData) { List<ValidationResultDTO> validationResultDTOList = new ArrayList<>(); List<ValidationInformationDTO> validationInformationDTOList = new ArrayList<>(); List<String> pointerList = new ArrayList<>(); RuleDTO ruleDTO = new RuleDTO(); ruleDTO.setRuleID("TEST_RULE_ID"); if (!missingData) { ValidationInformationDTO validationInformationDTO = new ValidationInformationDTO(); validationInformationDTO.setCode("TEST_CODE"); validationInformationDTO.setText("TEST_TEXT"); validationInformationDTO.setValidationInformationType("TEST_VALIDATION_INFORMATION_TYPE"); validationInformationDTOList.add(validationInformationDTO); } if (!missingData) { String pointer = "TEST_POINTER"; pointerList.add(pointer); } ValidationResultDTO validationResultDTO = new ValidationResultDTO(); validationResultDTO.setValidationResultType(VALIDATION_RESULT_TYPE); validationResultDTO.setViolatedRule(ruleDTO); validationResultDTO.setInformation(validationInformationDTOList); validationResultDTO.setPointers(pointerList); validationResultDTOList.add(validationResultDTO); return validationResultDTOList; } private ExternalValidationResponseEvent buildExternalValidationResponseEvent(String businessKey, String externalSystem) { ExternalValidationResponseEvent externalValidationResponseEvent = new ExternalValidationResponseEvent(); externalValidationResponseEvent.setBusinessKey(businessKey); externalValidationResponseEvent.setExternalSystem(externalSystem); return externalValidationResponseEvent; } private static Stream<Arguments> provideStatusArguments() { return Stream.of( Arguments.of(ExternalValidationRequestStatusEnum.PENDING.name()), Arguments.of(ExternalValidationRequestStatusEnum.FAILED.name()), Arguments.of(ExternalValidationRequestStatusEnum.CANCELLED.name()), Arguments.of(ExternalValidationRequestStatusEnum.COMPLETED.name()), Arguments.of(ExternalValidationRequestStatusEnum.EXPIRED.name()) ); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofdeparture.service; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.ddntav5152.messages.AddressType07; import com.intrasoft.ermis.ddntav5152.messages.AddressType09; import com.intrasoft.ermis.ddntav5152.messages.AddressType12; import com.intrasoft.ermis.ddntav5152.messages.AddressType17; import com.intrasoft.ermis.ddntav5152.messages.AddressType19; import com.intrasoft.ermis.ddntav5152.messages.AddressType20; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CC029CType; import com.intrasoft.ermis.ddntav5152.messages.CD001CType; import com.intrasoft.ermis.ddntav5152.messages.CD003CType; import com.intrasoft.ermis.ddntav5152.messages.CD038CType; import com.intrasoft.ermis.ddntav5152.messages.CD050CType; import com.intrasoft.ermis.ddntav5152.messages.CD115CType; import com.intrasoft.ermis.ddntav5152.messages.CD160CType; import com.intrasoft.ermis.ddntav5152.messages.CD165CType; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType02; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType03; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType04; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType05; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType06; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType07; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentItemType09; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType03; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType04; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType07; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType08; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType09; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType05; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType11; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType14; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType16; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType17; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType18; import com.intrasoft.ermis.ddntav5152.messages.HouseConsignmentType10; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.PartyManagementPort; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.domain.PartyIdentification; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.domain.PhysicalAddress; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.domain.organization.Organization; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @AllArgsConstructor(onConstructor_ = {@Autowired}) public class ProcessPersonDetailsServiceImpl implements ProcessPersonDetailsService { private static final String DUMMY_VALUE_FOR_VOID_DATA = "---"; public static final String STREET_AND_NUMBER = "streetAndNumber"; public static final String POSTCODE = "postcode"; public static final String CITY = "city"; public static final String COUNTRY = "country"; public static final String NAME = "name"; private final PartyManagementPort partyManagementPort; private final ErmisLogger log; private static final String IDENTIFICATION_TYPE_EORI = "1"; @Override public <T> void processEmptyPersonDetails(T ddntaMessage, String countryToBeUsed, CC015CType cc015cMessage) { if (ddntaMessage.getClass().equals(CD001CType.class)) { List<String> eoriNumbersFromCD001 = getEORIsFromCD001(ddntaMessage); log.info("processDetails;CD001 EORI Numbers: {}", eoriNumbersFromCD001); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCD001); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType11(((CD001CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType08(((CD001CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType07(((CD001CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CD001CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType09(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE001 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CD001CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType07(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType06(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } else if (ddntaMessage.getClass().equals(CD050CType.class)) { List<String> eoriNumbersFromCD050 = getEORIsFromCD050(ddntaMessage); log.info("processDetails;CD050 EORI Numbers: {}", eoriNumbersFromCD050); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCD050); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType17(((CD050CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType08(((CD050CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType07(((CD050CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CD050CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType09(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE050 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CD050CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType07(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType06(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } else if (ddntaMessage.getClass().equals(CD160CType.class)) { List<String> eoriNumbersFromCD160 = getEORIsFromCD160(ddntaMessage); log.info("processDetails;CD160 EORI Numbers: {}", eoriNumbersFromCD160); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCD160); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType17(((CD160CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType08(((CD160CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType07(((CD160CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CD160CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType09(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE160 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CD160CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType07(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType06(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } else if (ddntaMessage.getClass().equals(CD038CType.class)) { List<String> eoriNumbersFromCD038 = getEORIsFromCD038(ddntaMessage); log.info("processDetails;CD038 EORI Numbers: {}", eoriNumbersFromCD038); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCD038); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType16(((CD038CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType08(((CD038CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType07(((CD038CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CD038CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType09(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE038 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CD038CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType07(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType06(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } else if (ddntaMessage.getClass().equals(CD003CType.class)) { List<String> eoriNumbersFromCD003 = getEORIsFromCD003(ddntaMessage); log.info("processDetails;CD003 EORI Numbers: {}", eoriNumbersFromCD003); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCD003); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType16(((CD003CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType08(((CD003CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType07(((CD003CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CD003CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType09(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE003 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CD003CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType07(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType06(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } else if (ddntaMessage.getClass().equals(CD115CType.class)) { List<String> eoriNumbersFromCD115 = getEORIsFromCD115(ddntaMessage); log.info("processDetails;CD115 EORI Numbers: {}", eoriNumbersFromCD115); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCD115); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType18(((CD115CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType08(((CD115CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType07(((CD115CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CD115CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType09(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE115 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CD115CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType07(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType06(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } else if (ddntaMessage.getClass().equals(CD165CType.class)) { List<String> eoriNumbersFromCD165 = getEORIsFromCD165(ddntaMessage); log.info("processDetails;CD165 EORI Numbers: {}", eoriNumbersFromCD165); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCD165); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType18(((CD165CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType08(((CD165CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType07(((CD165CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CD165CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType09(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE165 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CD165CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType07(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType06(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } else if (ddntaMessage.getClass().equals(CC029CType.class)) { List<String> eoriNumbersFromCC029 = getEORIsFromCC029(ddntaMessage); log.info("processDetails;CC029 EORI Numbers: {}", eoriNumbersFromCC029); Map<String, Map<String, String>> eoriDetailsMap = getEoriDetails(eoriNumbersFromCC029); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getHolderOfTheTransitProcedure())) { HolderOfTheTransitProcedureType14 holderFromIE015 = getHolderFromIE015(cc015cMessage); editHolderOfTheTransitProcedureType05(((CC029CType) ddntaMessage).getHolderOfTheTransitProcedure(), countryToBeUsed, eoriDetailsMap, holderFromIE015); } if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getConsignment().getConsignor())) { ConsignorType07 consignmentConsignorFromIE015 = getConsignmentConsignorFromIE015(cc015cMessage); editConsignorType03(((CC029CType) ddntaMessage).getConsignment().getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentConsignorFromIE015); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getConsignment().getConsignee())) { ConsigneeType05 consignmentConsigneeFromIE015 = getConsignmentConsigneeFromIE015(cc015cMessage); editConsigneeType04(((CC029CType) ddntaMessage).getConsignment().getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentConsigneeFromIE015); } // Consignment.HouseConsignment.Consignor fields: AtomicInteger houseConsignmentConsignorCounter = new AtomicInteger(0); ((CC029CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { ConsignorType07 consignmentHCConsignorFromIE015 = getConsignmentHCConsignorFromIE015(houseConsignmentConsignorCounter, cc015cMessage); editConsignorType04(houseConsignment.getConsignor(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignorFromIE015); } houseConsignmentConsignorCounter.getAndIncrement(); // ConsignmentItems of IE029 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: AtomicInteger houseConsignmentConsigneeCounter = new AtomicInteger(0); ((CC029CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { ConsigneeType05 consignmentHCConsigneeFromIE015 = getConsignmentHCConsigneeFromIE015(houseConsignmentConsigneeCounter, cc015cMessage); editConsigneeType04(houseConsignment.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsigneeFromIE015); } // ConsignmentItems: AtomicInteger houseConsignmentCIConsigneeCounter = new AtomicInteger(0); houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { ConsigneeType02 consignmentHCConsignmentItemConsigneeFromIE015 = getConsignmentHCConsignmentItemConsigneeFromIE015(houseConsignmentConsigneeCounter, houseConsignmentCIConsigneeCounter, cc015cMessage); editConsigneeType03(consignmentItem.getConsignee(), countryToBeUsed, eoriDetailsMap, consignmentHCConsignmentItemConsigneeFromIE015); } houseConsignmentCIConsigneeCounter.getAndIncrement(); }); houseConsignmentConsigneeCounter.getAndIncrement(); }); } } } private <T> List<String> getEORIsFromCC029(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CC029CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CC029CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CC029CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CC029CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CC029CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE029 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CC029CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private <T> List<String> getEORIsFromCD165(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CD165CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CD165CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD165CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CD165CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CD165CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE165 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CD165CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private <T> List<String> getEORIsFromCD115(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CD115CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CD115CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD115CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CD115CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CD115CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE115 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CD115CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private <T> List<String> getEORIsFromCD003(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CD003CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CD003CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD003CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CD003CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CD003CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE003 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CD003CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private <T> List<String> getEORIsFromCD038(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); // HolderOfTheTransitProcedure fields: if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CD038CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CD038CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD038CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CD038CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CD038CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE038 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CD038CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private <T> List<String> getEORIsFromCD160(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CD160CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CD160CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD160CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CD160CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CD160CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE160 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CD160CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private <T> List<String> getEORIsFromCD050(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CD050CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CD050CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD050CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CD050CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CD050CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE050 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CD050CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private List<Organization> getOrganizations(List<String> eoriNumbers) { List<Organization> partyMgtResponse = new ArrayList<>(); try { // call the party-mgt endpoint partyMgtResponse = partyManagementPort.findOrganizationsByIdentificationValues(IDENTIFICATION_TYPE_EORI, eoriNumbers, false); } catch (Exception e) { // catch the failure in order to proceed with filling '---' in the messages log.error("ERROR while calling party management {}", e.getMessage()); } return partyMgtResponse; } private Map<String, Map<String, String>> getEoriDetails(List<String> eoriNumbers) { Map<String, Map<String, String>> eoriDetailsMap = new HashMap<>(); List<Organization> organizationList = getOrganizations(eoriNumbers); // For each EORI number found: eoriNumbers.forEach(eori -> // Iterate over all returned Organizations: organizationList.forEach(organization -> { // If Organization includes identification matching that of the EORI Number... if (organization.getIdentifications() .stream() .anyMatch(partyIdentification -> IDENTIFICATION_TYPE_EORI.equals(partyIdentification.getPartyIdentificationType()) && eori.equals(partyIdentification.getNumber()))) { // ...then add first address (if exists) to the eoriDetailsMap: Map<String, String> innerDetailsMap = new HashMap<>(); innerDetailsMap.put(NAME, organization.getName()); if (organization.getAddresses() != null && !organization.getAddresses().isEmpty() && organization.getAddresses().get(0) != null) { PhysicalAddress partyAddress = organization.getAddresses().get(0); innerDetailsMap.put(STREET_AND_NUMBER, partyAddress.getStreetAndNumber()); innerDetailsMap.put(POSTCODE, partyAddress.getZipCode()); innerDetailsMap.put(CITY, partyAddress.getCityName()); innerDetailsMap.put(COUNTRY, partyAddress.getCountry()); } eoriDetailsMap.put(eori, innerDetailsMap); } }) ); return eoriDetailsMap; } private <T> List<String> getEORIsFromCD001(T ddntaMessage) { Set<String> eoriNumbers = new HashSet<>(); if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getHolderOfTheTransitProcedure())) { eoriNumbers.add(getEORINumber(((CD001CType) ddntaMessage).getHolderOfTheTransitProcedure())); } if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getConsignment())) { // Consignment.Consignor fields: if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getConsignment().getConsignor())) { eoriNumbers.add(getEORINumber(((CD001CType) ddntaMessage).getConsignment().getConsignor())); } // Consignment.Consignee fields: if (ObjectUtils.isNotEmpty(((CD001CType) ddntaMessage).getConsignment().getConsignee())) { eoriNumbers.add(getEORINumber(((CD001CType) ddntaMessage).getConsignment().getConsignee())); } // Consignment.HouseConsignment.Consignor fields: ((CD001CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignor()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignor())); } // ConsignmentItems of IE001 have no Consignor. }); // Consignment.HouseConsignment.Consignee & Consignment.HouseConsignment.ConsignmentItem.Consignee fields: ((CD001CType) ddntaMessage).getConsignment().getHouseConsignment().forEach(houseConsignment -> { if (ObjectUtils.isNotEmpty((houseConsignment.getConsignee()))) { eoriNumbers.add(getEORINumber(houseConsignment.getConsignee())); } // ConsignmentItems: houseConsignment.getConsignmentItem().forEach(consignmentItem -> { if (ObjectUtils.isNotEmpty((consignmentItem.getConsignee()))) { eoriNumbers.add(getEORINumber(consignmentItem.getConsignee())); } }); }); } return eoriNumbers.stream().filter(Objects::nonNull).collect(Collectors.toList()); } private void editHolderOfTheTransitProcedureType05(HolderOfTheTransitProcedureType05 holderOfTheTransitProcedure, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, HolderOfTheTransitProcedureType14 holderFromIE015) { String nameFromIE015 = getNameOfHolderFromIE015(holderFromIE015); editNameFieldByReflection(holderOfTheTransitProcedure, eoriDetailsMap, nameFromIE015); if (ObjectUtils.isEmpty(holderOfTheTransitProcedure.getAddress())) { holderOfTheTransitProcedure.setAddress(new AddressType07()); } AddressType17 addressFromIE015 = getAddressOfHolderFromIE015(holderFromIE015); editAddressFieldsByReflection(holderOfTheTransitProcedure.getAddress(), countryToBeUsed, getEORINumber(holderOfTheTransitProcedure), eoriDetailsMap, addressFromIE015); } private void editHolderOfTheTransitProcedureType11(HolderOfTheTransitProcedureType11 holderOfTheTransitProcedure, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, HolderOfTheTransitProcedureType14 holderFromIE015) { String nameFromIE015 = getNameOfHolderFromIE015(holderFromIE015); editNameFieldByReflection(holderOfTheTransitProcedure, eoriDetailsMap, nameFromIE015); if (ObjectUtils.isEmpty(holderOfTheTransitProcedure.getAddress())) { holderOfTheTransitProcedure.setAddress(new AddressType20()); } AddressType17 addressFromIE015 = getAddressOfHolderFromIE015(holderFromIE015); editAddressFieldsByReflection(holderOfTheTransitProcedure.getAddress(), countryToBeUsed, getEORINumber(holderOfTheTransitProcedure), eoriDetailsMap, addressFromIE015); } private void editHolderOfTheTransitProcedureType16(HolderOfTheTransitProcedureType16 holderOfTheTransitProcedure, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, HolderOfTheTransitProcedureType14 holderFromIE015) { String nameFromIE015 = getNameOfHolderFromIE015(holderFromIE015); editNameFieldByReflection(holderOfTheTransitProcedure, eoriDetailsMap, nameFromIE015); if (ObjectUtils.isEmpty(holderOfTheTransitProcedure.getAddress())) { holderOfTheTransitProcedure.setAddress(new AddressType20()); } AddressType17 addressFromIE015 = getAddressOfHolderFromIE015(holderFromIE015); editAddressFieldsByReflection(holderOfTheTransitProcedure.getAddress(), countryToBeUsed, getEORINumber(holderOfTheTransitProcedure), eoriDetailsMap, addressFromIE015); } private void editHolderOfTheTransitProcedureType17(HolderOfTheTransitProcedureType17 holderOfTheTransitProcedure, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, HolderOfTheTransitProcedureType14 holderFromIE015) { String nameFromIE015 = getNameOfHolderFromIE015(holderFromIE015); editNameFieldByReflection(holderOfTheTransitProcedure, eoriDetailsMap, nameFromIE015); if (ObjectUtils.isEmpty(holderOfTheTransitProcedure.getAddress())) { holderOfTheTransitProcedure.setAddress(new AddressType20()); } AddressType17 addressFromIE015 = getAddressOfHolderFromIE015(holderFromIE015); editAddressFieldsByReflection(holderOfTheTransitProcedure.getAddress(), countryToBeUsed, getEORINumber(holderOfTheTransitProcedure), eoriDetailsMap, addressFromIE015); } private void editHolderOfTheTransitProcedureType18(HolderOfTheTransitProcedureType18 holderOfTheTransitProcedure, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, HolderOfTheTransitProcedureType14 holderFromIE015) { String nameFromIE015 = getNameOfHolderFromIE015(holderFromIE015); editNameFieldByReflection(holderOfTheTransitProcedure, eoriDetailsMap, nameFromIE015); if (ObjectUtils.isEmpty(holderOfTheTransitProcedure.getAddress())) { holderOfTheTransitProcedure.setAddress(new AddressType20()); } AddressType17 addressFromIE015 = getAddressOfHolderFromIE015(holderFromIE015); editAddressFieldsByReflection(holderOfTheTransitProcedure.getAddress(), countryToBeUsed, getEORINumber(holderOfTheTransitProcedure), eoriDetailsMap, addressFromIE015); } private void editConsignorType03(ConsignorType03 consignor, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsignorType07 consignorFromIE015) { String consignorNameFromIE015 = getNameOfConsignorFromIE015(consignorFromIE015); editNameFieldByReflection(consignor, eoriDetailsMap, consignorNameFromIE015); if (ObjectUtils.isEmpty(consignor.getAddress())) { consignor.setAddress(new AddressType07()); } AddressType17 consignorAddressFromIE015 = getAddressOfConsignorFromIE015(consignorFromIE015); editAddressFieldsByReflection(consignor.getAddress(), countryToBeUsed, getEORINumber(consignor), eoriDetailsMap, consignorAddressFromIE015); } private void editConsignorType04(ConsignorType04 consignor, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsignorType07 consignorFromIE015) { String consignorNameFromIE015 = getNameOfConsignorFromIE015(consignorFromIE015); editNameFieldByReflection(consignor, eoriDetailsMap, consignorNameFromIE015); if (ObjectUtils.isEmpty(consignor.getAddress())) { consignor.setAddress(new AddressType07()); } AddressType17 consignorAddressFromIE015 = getAddressOfConsignorFromIE015(consignorFromIE015); editAddressFieldsByReflection(consignor.getAddress(), countryToBeUsed, getEORINumber(consignor), eoriDetailsMap, consignorAddressFromIE015); } private void editConsignorType08(ConsignorType08 consignor, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsignorType07 consignorFromIE015) { String consignorNameFromIE015 = getNameOfConsignorFromIE015(consignorFromIE015); editNameFieldByReflection(consignor, eoriDetailsMap, consignorNameFromIE015); if (ObjectUtils.isEmpty(consignor.getAddress())) { consignor.setAddress(new AddressType20()); } AddressType17 consignorAddressFromIE015 = getAddressOfConsignorFromIE015(consignorFromIE015); editAddressFieldsByReflection(consignor.getAddress(), countryToBeUsed, getEORINumber(consignor), eoriDetailsMap, consignorAddressFromIE015); } private void editConsignorType09(ConsignorType09 consignor, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsignorType07 consignorFromIE015) { String consignorNameFromIE015 = getNameOfConsignorFromIE015(consignorFromIE015); editNameFieldByReflection(consignor, eoriDetailsMap, consignorNameFromIE015); if (ObjectUtils.isEmpty(consignor.getAddress())) { consignor.setAddress(new AddressType20()); } AddressType17 consignorAddressFromIE015 = getAddressOfConsignorFromIE015(consignorFromIE015); editAddressFieldsByReflection(consignor.getAddress(), countryToBeUsed, getEORINumber(consignor), eoriDetailsMap, consignorAddressFromIE015); } private void editConsigneeType03(ConsigneeType03 consignee, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsigneeType02 consigneeFromIE015) { String consigneeNameFromIE015 = getNameOfConsigneeType02FromIE015(consigneeFromIE015); editNameFieldByReflection(consignee, eoriDetailsMap, consigneeNameFromIE015); if (ObjectUtils.isEmpty(consignee.getAddress())) { consignee.setAddress(new AddressType09()); } AddressType12 consigneeAddressFromIE015 = getAddressOfConsigneeType02FromIE015(consigneeFromIE015); editAddressFieldsByReflection(consignee.getAddress(), countryToBeUsed, getEORINumber(consignee), eoriDetailsMap, consigneeAddressFromIE015); } private void editConsigneeType04(ConsigneeType04 consignee, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsigneeType05 consigneeFromIE015) { String consigneeNameFromIE015 = getNameOfConsigneeFromIE015(consigneeFromIE015); editNameFieldByReflection(consignee, eoriDetailsMap, consigneeNameFromIE015); if (ObjectUtils.isEmpty(consignee.getAddress())) { consignee.setAddress(new AddressType07()); } AddressType17 consigneeAddressFromIE015 = getAddressOfConsigneeFromIE015(consigneeFromIE015); editAddressFieldsByReflection(consignee.getAddress(), countryToBeUsed, getEORINumber(consignee), eoriDetailsMap, consigneeAddressFromIE015); } private void editConsigneeType06(ConsigneeType06 consignee, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsigneeType02 consigneeFromIE015) { String consigneeNameFromIE015 = getNameOfConsigneeType02FromIE015(consigneeFromIE015); editNameFieldByReflection(consignee, eoriDetailsMap, consigneeNameFromIE015); if (ObjectUtils.isEmpty(consignee.getAddress())) { consignee.setAddress(new AddressType19()); } AddressType12 consigneeAddressFromIE015 = getAddressOfConsigneeType02FromIE015(consigneeFromIE015); editAddressFieldsByReflection(consignee.getAddress(), countryToBeUsed, getEORINumber(consignee), eoriDetailsMap, consigneeAddressFromIE015); } private void editConsigneeType07(ConsigneeType07 consignee, String countryToBeUsed, Map<String, Map<String, String>> eoriDetailsMap, ConsigneeType05 consigneeFromIE015) { String consigneeNameFromIE015 = getNameOfConsigneeFromIE015(consigneeFromIE015); editNameFieldByReflection(consignee, eoriDetailsMap, consigneeNameFromIE015); if (ObjectUtils.isEmpty(consignee.getAddress())) { consignee.setAddress(new AddressType20()); } AddressType17 consigneeAddressFromIE015 = getAddressOfConsigneeFromIE015(consigneeFromIE015); editAddressFieldsByReflection(consignee.getAddress(), countryToBeUsed, getEORINumber(consignee), eoriDetailsMap, consigneeAddressFromIE015); } private <T> void editNameFieldByReflection(T input, Map<String, Map<String, String>> eoriDetailsMap, String nameFromIE015) { try { Field nameField = input.getClass().getDeclaredField("name"); nameField.setAccessible(true); String identificationNumber = getEORINumber(input); String nameProp = getKeyFromEoriDetailsMap(NAME, identificationNumber, eoriDetailsMap); log.info("processDetails;In editNameFieldByReflection, nameProperty '{}' for identificationNumber '{}'", nameProp, identificationNumber); if (StringUtils.isNotBlank(nameProp)) { nameField.set(input, nameProp); } else if (StringUtils.isNotBlank(nameFromIE015)) { nameField.set(input, nameFromIE015); } else { nameField.set(input, DUMMY_VALUE_FOR_VOID_DATA); } } catch (NoSuchFieldException | IllegalAccessException e) { log.error("ERROR: Failed to edit 'name' field in " + input.getClass().getSimpleName() + " Class."); } } private <T1, T2> void editAddressFieldsByReflection(T1 input, String countryToBeUsed, String identificationNumber, Map<String, Map<String, String>> eoriDetailsMap, T2 addressFromIE015) { try { Field streetAndNumberField = input.getClass().getDeclaredField(STREET_AND_NUMBER); Field postcodeField = input.getClass().getDeclaredField(POSTCODE); Field cityField = input.getClass().getDeclaredField(CITY); Field countryField = input.getClass().getDeclaredField(COUNTRY); streetAndNumberField.setAccessible(true); postcodeField.setAccessible(true); cityField.setAccessible(true); countryField.setAccessible(true); String streetAndNumberFromIE015 = null; String postCodeFromIE015 = null; String cityFromIE015 = null; String countryFromIE015 = null; // get details from IE015 if (addressFromIE015 != null) { Field streetAndNumberFieldFromIE015 = addressFromIE015.getClass().getDeclaredField(STREET_AND_NUMBER); Field postcodeFieldFromIE015 = addressFromIE015.getClass().getDeclaredField(POSTCODE); Field cityFieldFromIE015 = addressFromIE015.getClass().getDeclaredField(CITY); Field countryFieldFromIE015 = addressFromIE015.getClass().getDeclaredField(COUNTRY); streetAndNumberFieldFromIE015.setAccessible(true); postcodeFieldFromIE015.setAccessible(true); cityFieldFromIE015.setAccessible(true); countryFieldFromIE015.setAccessible(true); streetAndNumberFromIE015 = (String) streetAndNumberFieldFromIE015.get(addressFromIE015); postCodeFromIE015 = (String) postcodeFieldFromIE015.get(addressFromIE015); cityFromIE015 = (String) cityFieldFromIE015.get(addressFromIE015); countryFromIE015 = (String) countryFieldFromIE015.get(addressFromIE015); } log.info("processDetails; In editAddressFieldsByReflection for identificationNumber: '{}'", identificationNumber); log.info("streetAndNumberFromIE015 '{}' ", streetAndNumberFromIE015); log.info("postCodeFromIE015 '{}' ", postCodeFromIE015); log.info("cityFromIE015 '{}' ", cityFromIE015); log.info("countryFromIE015 '{}' ", countryFromIE015); String streetAndNumberProp = getKeyFromEoriDetailsMap(STREET_AND_NUMBER, identificationNumber, eoriDetailsMap); String postCodeProp = getKeyFromEoriDetailsMap(POSTCODE, identificationNumber, eoriDetailsMap); String cityProp = getKeyFromEoriDetailsMap(CITY, identificationNumber, eoriDetailsMap); String countryProp = getKeyFromEoriDetailsMap(COUNTRY, identificationNumber, eoriDetailsMap); log.info("streetAndNumberPropFromPM '{}' ", streetAndNumberProp); log.info("postCodePropFromPM '{}' ", postCodeProp); log.info("cityPropFromPM '{}' ", cityProp); log.info("countryPropFromPM '{}' ", countryProp); if (StringUtils.isNotBlank(streetAndNumberProp)) { streetAndNumberField.set(input, streetAndNumberProp); } else if (StringUtils.isNotBlank(streetAndNumberFromIE015)) { streetAndNumberField.set(input, streetAndNumberFromIE015); } else { streetAndNumberField.set(input, DUMMY_VALUE_FOR_VOID_DATA); } if (StringUtils.isNotBlank(postCodeProp)) { postcodeField.set(input, postCodeProp); } else if (StringUtils.isNotBlank(postCodeFromIE015)) { postcodeField.set(input, postCodeFromIE015); } else { postcodeField.set(input, DUMMY_VALUE_FOR_VOID_DATA); } if (StringUtils.isNotBlank(cityProp)) { cityField.set(input, cityProp); } else if (StringUtils.isNotBlank(cityFromIE015)) { cityField.set(input, cityFromIE015); } else { cityField.set(input, DUMMY_VALUE_FOR_VOID_DATA); } if (StringUtils.isNotBlank(countryProp)) { countryField.set(input, countryProp); } else if (StringUtils.isNotBlank(countryFromIE015)) { countryField.set(input, countryFromIE015); } else { countryField.set(input, countryToBeUsed); } } catch (NoSuchFieldException | IllegalAccessException e) { log.error("ERROR: Failed to edit fields streetAndNumber/postcode/city/country in " + input.getClass().getSimpleName() + " Class."); } } private String getKeyFromEoriDetailsMap(String key, String identificationNumber, Map<String, Map<String, String>> eoriDetailsMap) { Optional<Map<String, String>> optionalEoriDetailsMap = Optional.ofNullable(eoriDetailsMap.get(identificationNumber)); String value = null; if (optionalEoriDetailsMap.isPresent() && !optionalEoriDetailsMap.get().isEmpty()) { Map<String, String> eoriDetailsValues = optionalEoriDetailsMap.get(); log.debug("processdetails;Values from eoriDetailsValues: {}", eoriDetailsValues); value = eoriDetailsValues.get(key); } return value; } private <T> String getEORINumber(T input) { String eori = null; try { Field identificationNumberField = input.getClass().getDeclaredField("identificationNumber"); identificationNumberField.setAccessible(true); if (ObjectUtils.isNotEmpty(identificationNumberField.get(input))) { eori = identificationNumberField.get(input).toString(); } } catch (NoSuchFieldException | IllegalAccessException e) { log.error("ERROR: Failed to get 'identificationNumber' field from " + input.getClass().getSimpleName() + " Class."); } return eori; } private HolderOfTheTransitProcedureType14 getHolderFromIE015(CC015CType cc015cMessage) { log.info("processDetails;In getHolderFromIE015"); HolderOfTheTransitProcedureType14 holderFromIE015 = null; if (cc015cMessage != null) { holderFromIE015 = cc015cMessage.getHolderOfTheTransitProcedure(); } return holderFromIE015; } private ConsignorType07 getConsignmentConsignorFromIE015(CC015CType cc015cMessage) { log.info("processDetails;In getConsignmentConsignorFromIE015"); ConsignorType07 consignmentConsignorFromIE015 = null; if (cc015cMessage != null && cc015cMessage.getConsignment() != null) { consignmentConsignorFromIE015 = cc015cMessage.getConsignment().getConsignor(); } return consignmentConsignorFromIE015; } private ConsigneeType05 getConsignmentConsigneeFromIE015(CC015CType cc015cMessage) { log.info("processDetails;In getConsignmentConsigneeFromIE015"); ConsigneeType05 consignmentConsigneeFromIE015 = null; if (cc015cMessage != null && cc015cMessage.getConsignment() != null) { consignmentConsigneeFromIE015 = cc015cMessage.getConsignment().getConsignee(); } return consignmentConsigneeFromIE015; } private ConsigneeType05 getConsignmentHCConsigneeFromIE015(AtomicInteger houseConsignmentCounter, CC015CType cc015cMessage) { log.info("processDetails;In getConsignmentHCConsigneeFromIE015"); ConsigneeType05 consignmentHCConsigneeFromIE015 = null; HouseConsignmentType10 consignmentHC = getConsigneeOfHCFromIE015(houseConsignmentCounter, cc015cMessage); if (consignmentHC != null) { consignmentHCConsigneeFromIE015 = consignmentHC.getConsignee(); } return consignmentHCConsigneeFromIE015; } private HouseConsignmentType10 getConsigneeOfHCFromIE015(AtomicInteger houseConsignmentCounter, CC015CType cc015cMessage) { log.info("processDetails;In getConsigneeOfHCFromIE015"); HouseConsignmentType10 houseConsignmentType10 = null; if (cc015cMessage != null && cc015cMessage.getConsignment() != null && cc015cMessage.getConsignment().getHouseConsignment() != null) { try { houseConsignmentType10 = cc015cMessage.getConsignment() .getHouseConsignment() .get(houseConsignmentCounter.get()); } catch (IndexOutOfBoundsException e) { log.info("There is no houseConsignment({}) entry in CC015C", houseConsignmentCounter.get()); } } return houseConsignmentType10; } private ConsigneeType02 getConsignmentHCConsignmentItemConsigneeFromIE015(AtomicInteger houseConsignmentCounter, AtomicInteger hcConsignmentItemCounter, CC015CType cc015cMessage) { log.info("processDetails;In getConsignmentHCConsignmentItemConsigneeFromIE015"); ConsignmentItemType09 consignmentItemFromIE015 = null; ConsigneeType02 consignee = null; if (cc015cMessage != null && cc015cMessage.getConsignment() != null && cc015cMessage.getConsignment().getHouseConsignment() != null) { try { consignmentItemFromIE015 = cc015cMessage.getConsignment().getHouseConsignment() .get(houseConsignmentCounter.get()) .getConsignmentItem() .get(hcConsignmentItemCounter.get()); } catch (IndexOutOfBoundsException e) { log.info("There is no houseConsignment({}).consignmentItem({}) entry in CC015C", houseConsignmentCounter.get(), hcConsignmentItemCounter.get()); } } if (consignmentItemFromIE015 != null) { consignee = consignmentItemFromIE015.getConsignee(); } return consignee; } private ConsignorType07 getConsignmentHCConsignorFromIE015(AtomicInteger houseConsignmentCounter, CC015CType cc015cMessage) { log.info("processDetails;In getConsignmentHCConsignorFromIE015"); ConsignorType07 consignmentHCConsignorFromIE015 = null; HouseConsignmentType10 consignmentHC = getConsignorOfHCFromIE015(houseConsignmentCounter, cc015cMessage); if (consignmentHC != null) { consignmentHCConsignorFromIE015 = consignmentHC.getConsignor(); } return consignmentHCConsignorFromIE015; } private HouseConsignmentType10 getConsignorOfHCFromIE015(AtomicInteger houseConsignmentCounter, CC015CType cc015cMessage) { log.info("processDetails;In getConsignorOfHCFromIE015"); HouseConsignmentType10 houseConsignmentType10 = null; if (cc015cMessage != null && cc015cMessage.getConsignment() != null && cc015cMessage.getConsignment().getHouseConsignment() != null) { try { houseConsignmentType10 = cc015cMessage.getConsignment() .getHouseConsignment() .get(houseConsignmentCounter.get()); } catch (IndexOutOfBoundsException e) { log.info("There is no houseConsignment({}) entry in CC015C", houseConsignmentCounter.get()); } } return houseConsignmentType10; } private String getNameOfHolderFromIE015(HolderOfTheTransitProcedureType14 holderFromIE015) { log.info("processDetails;In getNameOfHolderFromIE015"); String nameFromIE015 = null; if (holderFromIE015 != null) { nameFromIE015 = holderFromIE015.getName(); } return nameFromIE015; } private String getNameOfConsignorFromIE015(ConsignorType07 consignorFromIE015) { log.info("processDetails;In getNameOfConsignorFromIE015"); String nameFromIE015 = null; if (consignorFromIE015 != null) { nameFromIE015 = consignorFromIE015.getName(); } return nameFromIE015; } private String getNameOfConsigneeFromIE015(ConsigneeType05 consigneeFromIE015) { log.info("processDetails;In getNameOfConsigneeFromIE015"); String nameFromIE015 = null; if (consigneeFromIE015 != null) { nameFromIE015 = consigneeFromIE015.getName(); } return nameFromIE015; } private String getNameOfConsigneeType02FromIE015(ConsigneeType02 consigneeFromIE015) { log.info("processDetails;In getNameOfConsigneeType02FromIE015"); String nameFromIE015 = null; if (consigneeFromIE015 != null) { nameFromIE015 = consigneeFromIE015.getName(); } return nameFromIE015; } private AddressType17 getAddressOfConsignorFromIE015(ConsignorType07 consignorFromIE015) { log.info("processDetails;In getAddressOfConsignorFromIE015"); AddressType17 addressFromIE015 = new AddressType17(); if (consignorFromIE015 != null) { addressFromIE015 = consignorFromIE015.getAddress(); } return addressFromIE015; } private AddressType17 getAddressOfConsigneeFromIE015(ConsigneeType05 consigneeFromIE015) { log.info("processDetails;In getAddressOfConsigneeFromIE015"); AddressType17 addressFromIE015 = new AddressType17(); if (consigneeFromIE015 != null) { addressFromIE015 = consigneeFromIE015.getAddress(); } return addressFromIE015; } private AddressType17 getAddressOfHolderFromIE015(HolderOfTheTransitProcedureType14 holderFromIE015) { log.info("processDetails;In getAddressOfHolderFromIE015"); AddressType17 addressFromIE015 = new AddressType17(); if (holderFromIE015 != null) { addressFromIE015 = holderFromIE015.getAddress(); } return addressFromIE015; } private AddressType12 getAddressOfConsigneeType02FromIE015(ConsigneeType02 consigneeFromIE015) { log.info("processDetails;In getAddressOfConsigneeType02FromIE015"); AddressType12 addressFromIE015 = new AddressType12(); if (consigneeFromIE015 != null) { addressFromIE015 = consigneeFromIE015.getAddress(); } return addressFromIE015; } }
package com.intrasoft.ermis.trs.officeofdeparture.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.ddntav5152.messages.AddressType12; import com.intrasoft.ermis.ddntav5152.messages.AddressType17; import com.intrasoft.ermis.ddntav5152.messages.AddressType19; import com.intrasoft.ermis.ddntav5152.messages.AddressType20; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CD001CType; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType02; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType05; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType06; import com.intrasoft.ermis.ddntav5152.messages.ConsigneeType07; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentItemType09; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentItemType11; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentType10; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentType20; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType07; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType08; import com.intrasoft.ermis.ddntav5152.messages.ConsignorType09; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType11; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType14; import com.intrasoft.ermis.ddntav5152.messages.HouseConsignmentType10; import com.intrasoft.ermis.ddntav5152.messages.HouseConsignmentType12; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.PartyManagementPort; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.domain.PartyIdentification; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.domain.PhysicalAddress; import com.intrasoft.ermis.platform.shared.adapter.party.management.core.domain.organization.Organization; import com.intrasoft.ermis.transit.officeofdeparture.domain.ExternalSystemResponseProperty; import com.intrasoft.ermis.transit.officeofdeparture.service.ProcessPersonDetailsServiceImpl; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class ProcessPersonDetailsServiceImplUT { @Mock private ErmisLogger log; private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String DUMMY_VALUE_FOR_VOID_DATA = "---"; private static final String DUMMY_VALUE_FOR_VOID_COUNTRY = "DK"; private static final String MOCKED_EXISTING_DATA = "DATA"; private static final String MOCKED_EXISTING_DATA_IE015 = "DATA_IE015"; private static final String EORI_1 = "DK222222221"; private static final String EORI_2 = "DK222222222"; private static final String EORI_3 = "DK222222223"; public static final String NAME_1 = "Thomas Richtigen"; public static final String NAME_2 = "Laura Pasparten"; public static final String NAME_3 = "Steve Stevensunt"; public static final String POST_CODE_1 = "65631"; public static final String POST_CODE_2 = "65632"; public static final String POST_CODE_3 = "65633"; public static final String STREET_AND_NUMBER_1 = "KarlStrasse 2"; public static final String STREET_AND_NUMBER_2 = "Philipou 2"; public static final String CITY_1 = "Berlin"; public static final String CITY_2 = "Athina"; public static final String COUNTRY_1 = "Germany"; public static final String COUNTRY_2 = "Greece"; private static final String MESSAGE_ID = "d7647fe0-e0cb-419e-81cc-2fd95e5ad555"; private static final String EXTERNAL_SYSTEM = "party-mgt"; private static final String IDENTIFICATION_TYPE_EORI = "1"; @Mock private PartyManagementPort partyManagementPort; @InjectMocks private ProcessPersonDetailsServiceImpl processPersonDetailsService; @ParameterizedTest @ValueSource(strings = {"empty", "incomplete"}) @DisplayName("Test - EORI Data Mock Utility Functionality Without EORIs for IE001") void testEORIPersonDetailsWithoutEORIsForIE001(String testCase) { boolean isEmptyTestCase = "empty".equals(testCase.toLowerCase(Locale.ROOT)); CD001CType cd001cTypeMessage = isEmptyTestCase? createEmptyIE001() : createIncompleteIE001(); log.info("Initial payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); // without external system properties List<Organization> partyMgtResponse = new ArrayList<>(); List<String> eoriNumbers = new ArrayList<>(); when(partyManagementPort.findOrganizationsByIdentificationValues(IDENTIFICATION_TYPE_EORI, eoriNumbers, false)).thenReturn(partyMgtResponse); processPersonDetailsService.processEmptyPersonDetails(cd001cTypeMessage, DUMMY_VALUE_FOR_VOID_COUNTRY, null); log.info("Modified payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); // HolderOfTheTransitProcedure fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCountry()); // Consignment.Consignor fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCountry()); // Consignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.Consignor fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCountry()); // Consignment.HouseConsignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.ConsignmentItem.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCountry()); } @Test @DisplayName("Test - EORI Data Mock Utility Functionality With EORI for IE001") void testEORIPersonDetailsWithEORIsForIE001_WithoutPartyMgtResponseData() { CD001CType cd001cTypeMessage = createIncompleteIE001WithEORIs(); log.info("Initial payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); List<Organization> partyMgtResponse = new ArrayList<>(); List<String> eoriNumbers = new ArrayList<>(); eoriNumbers.add(EORI_1); eoriNumbers.add(EORI_2); eoriNumbers.add(EORI_3); when(partyManagementPort.findOrganizationsByIdentificationValues(IDENTIFICATION_TYPE_EORI, eoriNumbers, false)).thenReturn(partyMgtResponse); processPersonDetailsService.processEmptyPersonDetails(cd001cTypeMessage, DUMMY_VALUE_FOR_VOID_COUNTRY, null); log.info("Modified payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); // HolderOfTheTransitProcedure fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCountry()); // Consignment.Consignor fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCountry()); // Consignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.Consignor fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCountry()); // Consignment.HouseConsignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.ConsignmentItem.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCountry()); } @Test @DisplayName("Test 1 - EORI Data Mock Utility Functionality With EORI for IE001 and IE015 data") void testEORIPersonDetailsWithEORIsForIE001_WithDataFromIE015() { CD001CType cd001cTypeMessage = createIncompleteIE001WithEORIs(); log.info("Initial payload IE001: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); CC015CType cc015cTypeMessage = createIncompleteIE015WithEORIs(); List<Organization> partyMgtResponse = new ArrayList<>(); List<String> eoriNumbers = new ArrayList<>(); eoriNumbers.add(EORI_1); eoriNumbers.add(EORI_2); eoriNumbers.add(EORI_3); when(partyManagementPort.findOrganizationsByIdentificationValues(IDENTIFICATION_TYPE_EORI, eoriNumbers, false)).thenReturn(partyMgtResponse); processPersonDetailsService.processEmptyPersonDetails(cd001cTypeMessage, DUMMY_VALUE_FOR_VOID_COUNTRY, cc015cTypeMessage); log.info("Modified payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); // HolderOfTheTransitProcedure fields: assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getHolderOfTheTransitProcedure().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getPostcode()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCountry()); // Consignment.Consignor fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getName()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCountry()); // Consignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getStreetAndNumber()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCity()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.Consignor fields: assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCountry()); // Consignment.HouseConsignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getPostcode()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.ConsignmentItem.Consignee fields: assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getName()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getPostcode()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCountry()); } @Test @DisplayName("Test 2 - EORI Data Mock Utility Functionality With EORI for IE001 and IE015 data") void testEORIPersonDetailsWithEORIsForIE001_WithDataFromIE015_NoHCCiMatch() { CD001CType cd001cTypeMessage = createIncompleteIE001WithEORIs(); log.info("Initial payload IE001: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); CC015CType cc015cTypeMessage = createIncompleteIE015WithEORIsNoHCCiMatch(); List<Organization> partyMgtResponse = new ArrayList<>(); List<String> eoriNumbers = new ArrayList<>(); eoriNumbers.add(EORI_1); eoriNumbers.add(EORI_2); eoriNumbers.add(EORI_3); when(partyManagementPort.findOrganizationsByIdentificationValues(IDENTIFICATION_TYPE_EORI, eoriNumbers, false)).thenReturn(partyMgtResponse); processPersonDetailsService.processEmptyPersonDetails(cd001cTypeMessage, DUMMY_VALUE_FOR_VOID_COUNTRY, cc015cTypeMessage); log.info("Modified payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); // HolderOfTheTransitProcedure fields: assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getHolderOfTheTransitProcedure().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getPostcode()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCountry()); // Consignment.Consignor fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getName()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCountry()); // Consignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getStreetAndNumber()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCity()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.Consignor fields: assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCountry()); // Consignment.HouseConsignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getPostcode()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.ConsignmentItem.Consignee fields: assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getName()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getPostcode()); assertEquals(MOCKED_EXISTING_DATA_IE015, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCountry()); } @Test @DisplayName("Test - EORI Data Mock Utility Functionality With EORI for IE001 and Party Mgt Response Data") void testEORIPersonDetailsWithEORIsForIE001_WithPartyMgtResponseData() { CD001CType cd001cTypeMessage = createIncompleteIE001WithEORIs(); log.info("Initial payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); List<Organization> partyMgtResponse = getPartyMgtResponseData(); List<String> eoriNumbers = new ArrayList<>(); eoriNumbers.add(EORI_1); eoriNumbers.add(EORI_2); eoriNumbers.add(EORI_3); when(partyManagementPort.findOrganizationsByIdentificationValues(eq(IDENTIFICATION_TYPE_EORI), any(), eq(false))).thenReturn(partyMgtResponse); processPersonDetailsService.processEmptyPersonDetails(cd001cTypeMessage, DUMMY_VALUE_FOR_VOID_COUNTRY, null); log.info("Modified payload: " + JSON_CONVERTER.convertToJsonString(cd001cTypeMessage)); // HolderOfTheTransitProcedure fields: assertEquals(NAME_1, cd001cTypeMessage.getHolderOfTheTransitProcedure().getName()); assertEquals(STREET_AND_NUMBER_1, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getStreetAndNumber()); assertEquals(POST_CODE_1, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getPostcode()); assertEquals(CITY_1, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCity()); assertEquals(COUNTRY_1, cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().getCountry()); // Consignment.Consignor fields: assertEquals(NAME_2, cd001cTypeMessage.getConsignment().getConsignor().getName()); assertEquals(STREET_AND_NUMBER_2, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getStreetAndNumber()); assertEquals(POST_CODE_2, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getPostcode()); assertEquals(CITY_2, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCity()); assertEquals(COUNTRY_2, cd001cTypeMessage.getConsignment().getConsignor().getAddress().getCountry()); // Consignment.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.Consignor fields: assertEquals(NAME_1, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getName()); assertEquals(STREET_AND_NUMBER_1, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getStreetAndNumber()); assertEquals(POST_CODE_1, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getPostcode()); assertEquals(CITY_1, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCity()); assertEquals(COUNTRY_1, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().getAddress().getCountry()); // Consignment.HouseConsignment.Consignee fields: assertEquals(NAME_2, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getName()); assertEquals(STREET_AND_NUMBER_2, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(POST_CODE_2, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getPostcode()); assertEquals(CITY_2, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCity()); assertEquals(COUNTRY_2, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().getCountry()); // Consignment.HouseConsignment.ConsignmentItem.Consignee fields: assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getName()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getStreetAndNumber()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getPostcode()); assertEquals(DUMMY_VALUE_FOR_VOID_DATA, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCity()); assertEquals(DUMMY_VALUE_FOR_VOID_COUNTRY, cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().getCountry()); } private List<Organization> getPartyMgtResponseData() { List<Organization> organizations = new ArrayList<>(); List<PartyIdentification> identifications1 = new ArrayList<>(); PartyIdentification identification1 = new PartyIdentification(IDENTIFICATION_TYPE_EORI, EORI_1, LocalDateTime.now().minusDays(1), LocalDateTime.now().plusDays(1)); identifications1.add(identification1); List<PhysicalAddress> addresses1 = new ArrayList<>(); PhysicalAddress physicalAddress1 = new PhysicalAddress(null,null,STREET_AND_NUMBER_1,null, CITY_1,POST_CODE_1,null,null,null,COUNTRY_1); addresses1.add(physicalAddress1); Organization org1 = new Organization(NAME_1,null,identifications1,null,addresses1,null, null,null,null,null,null,null,null,0, null,null,null,null,null,null); organizations.add(org1); List<PartyIdentification> identifications2 = new ArrayList<>(); PartyIdentification identification2 = new PartyIdentification(IDENTIFICATION_TYPE_EORI, EORI_2, LocalDateTime.now().minusDays(1), LocalDateTime.now().plusDays(1)); identifications2.add(identification2); List<PhysicalAddress> addresses2 = new ArrayList<>(); PhysicalAddress physicalAddress2 = new PhysicalAddress(null,null,STREET_AND_NUMBER_2,null, CITY_2,POST_CODE_2,null,null,null,COUNTRY_2); addresses2.add(physicalAddress2); Organization org2 = new Organization(NAME_2,null,identifications2,null,addresses2,null, null,null,null,null,null,null,null,0, null,null,null,null,null,null); organizations.add(org2); return organizations; } private Map<String, ExternalSystemResponseProperty> getExternalSystemProperties() { Map<String, ExternalSystemResponseProperty> propertyMap = new HashMap<>(); ExternalSystemResponseProperty property1 = new ExternalSystemResponseProperty(); property1.setMessageId(MESSAGE_ID); property1.setExternalSystem(EXTERNAL_SYSTEM); property1.setKey("name-" + EORI_1); property1.setValue(NAME_1); propertyMap.put("name-" + EORI_1, property1); ExternalSystemResponseProperty property2 = new ExternalSystemResponseProperty(); property2.setMessageId(MESSAGE_ID); property2.setExternalSystem(EXTERNAL_SYSTEM); property2.setKey("name-" + EORI_2); property2.setValue(NAME_2); propertyMap.put("name-" + EORI_2, property2); ExternalSystemResponseProperty property3 = new ExternalSystemResponseProperty(); property3.setMessageId(MESSAGE_ID); property3.setExternalSystem(EXTERNAL_SYSTEM); property3.setKey("name-" + EORI_3); property3.setValue(NAME_3); propertyMap.put("name-" + EORI_3, property3); ExternalSystemResponseProperty property4 = new ExternalSystemResponseProperty(); property4.setMessageId(MESSAGE_ID); property4.setExternalSystem(EXTERNAL_SYSTEM); property4.setKey("postcode-" + EORI_1); property4.setValue(POST_CODE_1); propertyMap.put("postcode-" + EORI_1, property4); ExternalSystemResponseProperty property5 = new ExternalSystemResponseProperty(); property5.setMessageId(MESSAGE_ID); property5.setExternalSystem(EXTERNAL_SYSTEM); property5.setKey("postcode-" + EORI_2); property5.setValue(POST_CODE_2); propertyMap.put("postcode-" + EORI_2, property5); ExternalSystemResponseProperty property6 = new ExternalSystemResponseProperty(); property6.setMessageId(MESSAGE_ID); property6.setExternalSystem(EXTERNAL_SYSTEM); property6.setKey("postcode-" + POST_CODE_3); property6.setValue(POST_CODE_3); propertyMap.put("postcode-" + EORI_3, property6); return propertyMap; } private CD001CType createEmptyIE001() { CD001CType cd001cTypeMessage = new CD001CType(); cd001cTypeMessage.setHolderOfTheTransitProcedure(new HolderOfTheTransitProcedureType11()); cd001cTypeMessage.setConsignment(new ConsignmentType10()); cd001cTypeMessage.getConsignment().setConsignor(new ConsignorType08()); cd001cTypeMessage.getConsignment().setConsignee(new ConsigneeType07()); cd001cTypeMessage.getConsignment().getHouseConsignment().add(new HouseConsignmentType12()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).setConsignor(new ConsignorType09()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).setConsignee(new ConsigneeType07()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().add(new ConsignmentItemType11()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).setConsignee(new ConsigneeType06()); return cd001cTypeMessage; } private CD001CType createIncompleteIE001() { CD001CType cd001cTypeMessage = createEmptyIE001(); cd001cTypeMessage.getHolderOfTheTransitProcedure().setName(MOCKED_EXISTING_DATA); cd001cTypeMessage.getHolderOfTheTransitProcedure().setAddress(new AddressType20()); cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().setCity(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getConsignor().setAddress(new AddressType20()); cd001cTypeMessage.getConsignment().getConsignor().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getConsignee().setAddress(new AddressType20()); cd001cTypeMessage.getConsignment().getConsignee().getAddress().setCountry(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getConsignee().getAddress().setPostcode(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().setName(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().setAddress(new AddressType20()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setAddress(new AddressType19()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setName(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA); return cd001cTypeMessage; } private CD001CType createIncompleteIE001WithEORIs() { CD001CType cd001cTypeMessage = createEmptyIE001(); cd001cTypeMessage.getHolderOfTheTransitProcedure().setIdentificationNumber(EORI_1); cd001cTypeMessage.getHolderOfTheTransitProcedure().setName(MOCKED_EXISTING_DATA); cd001cTypeMessage.getHolderOfTheTransitProcedure().setAddress(new AddressType20()); cd001cTypeMessage.getHolderOfTheTransitProcedure().getAddress().setCity(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getConsignor().setIdentificationNumber(EORI_2); cd001cTypeMessage.getConsignment().getConsignor().setAddress(new AddressType20()); cd001cTypeMessage.getConsignment().getConsignor().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getConsignee().setIdentificationNumber(EORI_3); cd001cTypeMessage.getConsignment().getConsignee().setAddress(new AddressType20()); cd001cTypeMessage.getConsignment().getConsignee().getAddress().setCountry(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getConsignee().getAddress().setPostcode(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().setIdentificationNumber(EORI_1); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().setName(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().setIdentificationNumber(EORI_2); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().setAddress(new AddressType20()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setIdentificationNumber(EORI_3); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setAddress(new AddressType19()); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setName(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA); cd001cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA); return cd001cTypeMessage; } private CC015CType createEmptyIE015() { CC015CType cc015cTypeMessage = new CC015CType(); cc015cTypeMessage.setHolderOfTheTransitProcedure(new HolderOfTheTransitProcedureType14()); cc015cTypeMessage.setConsignment(new ConsignmentType20()); cc015cTypeMessage.getConsignment().setConsignor(new ConsignorType07()); cc015cTypeMessage.getConsignment().setConsignee(new ConsigneeType05()); cc015cTypeMessage.getConsignment().getHouseConsignment().add(new HouseConsignmentType10()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).setConsignor(new ConsignorType07()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).setConsignee(new ConsigneeType05()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().add(new ConsignmentItemType09()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).setConsignee(new ConsigneeType02()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().add(new ConsignmentItemType09()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).setConsignee(new ConsigneeType02()); return cc015cTypeMessage; } private CC015CType createIncompleteIE015WithEORIs() { CC015CType cc015cTypeMessage = createEmptyIE015(); cc015cTypeMessage.getHolderOfTheTransitProcedure().setIdentificationNumber(EORI_1); cc015cTypeMessage.getHolderOfTheTransitProcedure().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getHolderOfTheTransitProcedure().setAddress(new AddressType17()); cc015cTypeMessage.getHolderOfTheTransitProcedure().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getConsignor().setIdentificationNumber(EORI_2); cc015cTypeMessage.getConsignment().getConsignor().setAddress(new AddressType17()); cc015cTypeMessage.getConsignment().getConsignor().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getConsignee().setIdentificationNumber(EORI_3); cc015cTypeMessage.getConsignment().getConsignee().setAddress(new AddressType17()); cc015cTypeMessage.getConsignment().getConsignee().getAddress().setCountry(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getConsignee().getAddress().setPostcode(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().setIdentificationNumber(EORI_1); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().setIdentificationNumber(EORI_2); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().setAddress(new AddressType17()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setIdentificationNumber(EORI_2); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setAddress(new AddressType12()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().setIdentificationNumber(EORI_3); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().setAddress(new AddressType12()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); return cc015cTypeMessage; } private CC015CType createIncompleteIE015WithEORIsNoHCCiMatch() { CC015CType cc015cTypeMessage = createEmptyIE015(); cc015cTypeMessage.getHolderOfTheTransitProcedure().setIdentificationNumber(EORI_1); cc015cTypeMessage.getHolderOfTheTransitProcedure().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getHolderOfTheTransitProcedure().setAddress(new AddressType17()); cc015cTypeMessage.getHolderOfTheTransitProcedure().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getConsignor().setIdentificationNumber(EORI_2); cc015cTypeMessage.getConsignment().getConsignor().setAddress(new AddressType17()); cc015cTypeMessage.getConsignment().getConsignor().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getConsignee().setIdentificationNumber(EORI_3); cc015cTypeMessage.getConsignment().getConsignee().setAddress(new AddressType17()); cc015cTypeMessage.getConsignment().getConsignee().getAddress().setCountry(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getConsignee().getAddress().setPostcode(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().setIdentificationNumber(EORI_1); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignor().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().setIdentificationNumber(EORI_2); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().setAddress(new AddressType17()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setIdentificationNumber(EORI_1); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setAddress(new AddressType12()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(0).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().setIdentificationNumber(EORI_2); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().setAddress(new AddressType12()); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().setName(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().getAddress().setStreetAndNumber(MOCKED_EXISTING_DATA_IE015); cc015cTypeMessage.getConsignment().getHouseConsignment().get(0).getConsignmentItem().get(1).getConsignee().getAddress().setCity(MOCKED_EXISTING_DATA_IE015); return cc015cTypeMessage; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class ProcessingStatusServiceImpl implements ProcessingStatusService{ private final DossierDataService dossierDataService; @Override public void saveProcessingStatus(String movementId, String status) { dossierDataService.saveProcessingStatus(createProcessingStatus(movementId, status)); } private ProcessingStatus createProcessingStatus(String movementId, String status) { ProcessingStatus processingStatus = new ProcessingStatus(); processingStatus.setStatus(status); processingStatus.setMovementId(movementId); return processingStatus; } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.mockito.Mockito.verify; import static org.junit.jupiter.api.Assertions.assertEquals; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ProcessingStatusServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ProcessingStatusServiceUT { private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID"; @Mock private DossierDataService dossierDataService; @InjectMocks private ProcessingStatusServiceImpl processingStatusService; @Captor private ArgumentCaptor<ProcessingStatus> processingStatusArgumentCaptor; @Test @DisplayName("Test - Save Processing Status") void testSaveProcessingStatus() { // Call ProcessingStatusService method: processingStatusService.saveProcessingStatus(MOVEMENT_ID, ProcessingStatusTypeEnum.CARGO_OODEST_WRITTEN_OFF.getItemCode()); // Verification & Assertions: verify(dossierDataService).saveProcessingStatus(processingStatusArgumentCaptor.capture()); assertEquals(MOVEMENT_ID, processingStatusArgumentCaptor.getValue().getMovementId()); assertEquals(ProcessingStatusTypeEnum.CARGO_OODEST_WRITTEN_OFF.getItemCode(), processingStatusArgumentCaptor.getValue().getStatus()); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofdeparture.service; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.ddntav5152.messages.PostponeEnquiryEvent; import com.intrasoft.ermis.transit.bpmnshared.BpmnManagementService; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnTimersEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.ProcessDefinitionEnum; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import java.util.Objects; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class CustomsOfficerActionServiceImpl implements CustomsOfficerActionService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private final ErmisLogger log; private final BpmnFlowService bpmnFlowService; private final BpmnManagementService bpmnManagementService; private final ProcessingStatusService processingStatusService; private final GuaranteeService guaranteeService; private final RecoveryService recoveryService; private final DossierDataService dossierDataService; private final PostReleaseTransitService postReleaseTransitService; private final AmendmentRequestService amendmentRequestService; private static final String FALLBACK_ACTIVITY_ID = "Gateway_Fallback"; private static final String CANCELLED_ACTIVITY_ID = "Gateway_0rylnq0"; @Override public void handleRecommendEnquiryAction(Movement movement) { if (ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode().equals(movement.getProcessingStatus())) { bpmnFlowService.correlateMessage(movement.getMrn(), BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITHOUT_006.getTypeValue()); } else if (ProcessingStatusTypeEnum.OODEP_ARRIVED.getItemCode().equals(movement.getProcessingStatus())) { bpmnFlowService.correlateMessage(movement.getMrn(), BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITH_006.getTypeValue()); } } @Override public void handlePostponeEnquiryAction(Movement movement, String messageId) throws JAXBException { Message postponeEnquiryMessage = dossierDataService.getMessageById(messageId); PostponeEnquiryEvent postponeEnquiryEvent = JSON_CONVERTER.convertStringToObject(postponeEnquiryMessage.getPayload(), PostponeEnquiryEvent.class); String formattedExpectedArrivalDate = Objects.nonNull(postponeEnquiryEvent.getExpectedArrivalDate()) ? "P" + ChronoUnit.DAYS.between(LocalDate.now(ZoneOffset.UTC), postponeEnquiryEvent.getExpectedArrivalDate()) + "D" : null; String formattedExpectedControlDate = Objects.nonNull(postponeEnquiryEvent.getExpectedControlDate()) ? "P" + ChronoUnit.DAYS.between(LocalDate.now(ZoneOffset.UTC), postponeEnquiryEvent.getExpectedControlDate()) + "D" : null; if (formattedExpectedArrivalDate != null) { amendmentRequestService.updateLimitDate(movement.getId(), postponeEnquiryEvent.getExpectedControlDate()); processingStatusService.saveProcessingStatus(movement.getId(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode()); log.info("Going to stop 'Time To Enquire Timer'"); postReleaseTransitService.stopTimeToEnquireHolderTimerIfActive(movement.getMrn()); boolean isTimerActive = bpmnManagementService.isTimerActive( movement.getMrn(), ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(), BpmnTimersEnum.AWAIT_RECEIPT_CONTROL_RESULTS.getActivityId()); if (isTimerActive) { bpmnManagementService.modifyProcessInstance( movement.getMrn(), ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(), FALLBACK_ACTIVITY_ID, Map.of(BpmnFlowVariablesEnum.ARRIVAL_ADVICE_TIMER.getTypeValue(), formattedExpectedArrivalDate, BpmnFlowVariablesEnum.IS_CONTROL_TIMER_ACTIVE.getTypeValue(), true, BpmnFlowVariablesEnum.IS_EXPECTED_ARRIVAL_DATE_EMPTY.getTypeValue(), false, BpmnFlowVariablesEnum.HAS_ENQUIRE_TIMER_STARTED.getTypeValue(), false), List.of(CANCELLED_ACTIVITY_ID) ); bpmnManagementService.changedDueDateOfTimer( movement.getMrn(), ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(), BpmnTimersEnum.AWAIT_RECEIPT_CONTROL_RESULTS.getActivityId(), formattedExpectedControlDate); } else { bpmnManagementService.modifyProcessInstance( movement.getMrn(), ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(), FALLBACK_ACTIVITY_ID, Map.of(BpmnFlowVariablesEnum.ARRIVAL_ADVICE_TIMER.getTypeValue(), formattedExpectedArrivalDate, BpmnFlowVariablesEnum.RECEIPT_CONTROL_RESULTS_TIMER.getTypeValue(), Objects.requireNonNull(formattedExpectedControlDate), BpmnFlowVariablesEnum.IS_CONTROL_TIMER_ACTIVE.getTypeValue(), false, BpmnFlowVariablesEnum.IS_EXPECTED_ARRIVAL_DATE_EMPTY.getTypeValue(), false, BpmnFlowVariablesEnum.HAS_ENQUIRE_TIMER_STARTED.getTypeValue(), false), List.of(CANCELLED_ACTIVITY_ID) ); } } else { processingStatusService.saveProcessingStatus(movement.getId(), ProcessingStatusTypeEnum.OODEP_ARRIVED.getItemCode()); log.info("Going to stop 'Time To Enquire Timer'"); postReleaseTransitService.stopTimeToEnquireHolderTimerIfActive(movement.getMrn()); bpmnManagementService.modifyProcessInstance( movement.getMrn(), ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(), FALLBACK_ACTIVITY_ID, Map.of(BpmnFlowVariablesEnum.RECEIPT_CONTROL_RESULTS_TIMER.getTypeValue(), Objects.requireNonNull(formattedExpectedControlDate), BpmnFlowVariablesEnum.IS_EXPECTED_ARRIVAL_DATE_EMPTY.getTypeValue(), true, BpmnFlowVariablesEnum.IS_CONTROL_TIMER_ACTIVE.getTypeValue(), false, BpmnFlowVariablesEnum.HAS_ENQUIRE_TIMER_STARTED.getTypeValue(), false), List.of(CANCELLED_ACTIVITY_ID) ); } } @Override public void handleGuaranteeIntegrityCheckAction(Movement movement, String messageId) { guaranteeService.sendGuaranteeChecksToGMS(movement, messageId); } @Override public void handleRecommendRecoveryAction(Movement movement) { ProcessingStatusTypeEnum processingStatus = ProcessingStatusTypeEnum.findByItemCode(movement.getProcessingStatus()); switch (processingStatus) { case OODEP_MOVEMENT_RELEASED: bpmnFlowService.correlateMessageWithValues(movement.getMrn(), BpmnFlowMessagesEnum.MANUALLY_RECOMMEND_RECOVERY.getTypeValue(), Map.of( BpmnFlowVariablesEnum.IS_RECOVERY_PROCEDURE_STARTED_BY_OFFICER.getTypeValue(), true)); break; default: recoveryService.startRecoveryForOfficerAction(movement.getId(), movement.getMrn()); break; } } }
package com.intrasoft.ermis.trs.officeofdeparture; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofdeparture.service.BpmnFlowService; import com.intrasoft.ermis.transit.officeofdeparture.service.CustomsOfficerActionServiceImpl; import java.util.UUID; import java.util.stream.Stream; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class CustomOfficerActionServiceUT { @Mock private BpmnFlowService bpmnFlowService; @InjectMocks private CustomsOfficerActionServiceImpl customOfficerActionService; @Captor private ArgumentCaptor<String> messageNameArgumentCaptor; @Captor private ArgumentCaptor<String> businessKeyArgumentCaptor; private static final String MRN = "TEST_MRN"; @ParameterizedTest @MethodSource("namedArguments") public void testHandlingOfRecommendEnquiryAction(String processingStatus) { customOfficerActionService.handleRecommendEnquiryAction(createMovement(processingStatus)); if (ProcessingStatusTypeEnum.OODEP_NONE.getItemCode().equals(processingStatus)) { verify(bpmnFlowService, times(0)).correlateMessage(any(), any()); } else { verify(bpmnFlowService, times(1)).correlateMessage(businessKeyArgumentCaptor.capture(), messageNameArgumentCaptor.capture()); assertEquals(MRN, businessKeyArgumentCaptor.getValue()); if (ProcessingStatusTypeEnum.OODEP_ARRIVED.getItemCode().equals(processingStatus)) { assertEquals(BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITH_006.getTypeValue(), messageNameArgumentCaptor.getValue()); } else if (ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode().equals(processingStatus)) { assertEquals(BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITHOUT_006.getTypeValue(), messageNameArgumentCaptor.getValue()); } } } static Stream<Arguments> namedArguments() { return Stream.of( Arguments.of(Named.of(" Arrived", "A01")), Arguments.of(Named.of(" Movement Released", "A03")), Arguments.of(Named.of(" None (not valid processing status)", "A0")) ); } private Movement createMovement(String processingStatus) { return Movement.builder() .id(UUID.randomUUID().toString()) .processingStatus(processingStatus) .mrn(MRN) .build(); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofexitfortransit.core.service; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CD165CType; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class InspectionServiceImpl implements InspectionService { private final DossierDataService dossierDataService; @Override public boolean isIE165Positive(String messageId) { try { Message message = dossierDataService.getMessageById(messageId); CD165CType cd165cType = XmlConverter.buildMessageFromXML(message.getPayload(), CD165CType.class); if (cd165cType.getTransitOperation().getRequestRejectionReasonCode() == null) { return true; } else { return cd165cType.getTransitOperation().getRequestRejectionReasonCode().isEmpty(); } } catch (Exception e) { throw new BaseException("isIE165Positive(): ERROR!", e); } } }
package com.intrasoft.ermis.transit.officeofexitfortransit.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CD165CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.ddntav5152.messages.TransitOperationType41; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.DossierDataService; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.InspectionServiceImpl; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class InspectionServiceUT { @Mock private DossierDataService dossierDataService; @InjectMocks private InspectionServiceImpl inquiryService; @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Test - Is IE165 Positive") void testIsIE165Positive(boolean requestRejectionCodeExists) { System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); Message message = createMessage(requestRejectionCodeExists); try { // Mocks: when(dossierDataService.getMessageById(any())).thenReturn(message); // Call InspectionService method: boolean expectedResult = inquiryService.isIE165Positive(UUID.randomUUID().toString()); // Assertion: assertEquals(expectedResult, !requestRejectionCodeExists); } catch (Exception e) { fail(); } } private Message createMessage(boolean requestRejectionCodeExists) { CD165CType cd165cTypeMessage = new CD165CType(); cd165cTypeMessage.setTransitOperation(new TransitOperationType41()); if (requestRejectionCodeExists) { cd165cTypeMessage.getTransitOperation().setRequestRejectionReasonCode("TEST"); } Message message = new Message(); message.setPayload(XmlConverter.marshal(cd165cTypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CD_165_C.value())); return message; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.MessageOverview; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.platform.contracts.dossier.dtos.MessageOverviewDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.PaginatedDTO; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierDeclarationPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMessagePort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMovementPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierProcessingStatusPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierValidationResultsPort; import java.util.ArrayList; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @Slf4j @Service @RequiredArgsConstructor public class DossierDataServiceImpl implements DossierDataService { // Ports: private final DossierMovementPort dossierMovementPort; private final DossierMessagePort dossierMessagePort; private final DossierProcessingStatusPort dossierProcessingStatusPort; private final DossierDeclarationPort dossierDeclarationPort; private final DossierValidationResultsPort dossierValidationResultsPort; // Mappers: private final MovementDTOMapper movementDTOMapper; private final MessageDTOMapper messageDTOMapper; private final MessageOverviewDTOMapper messageOverviewDTOMapper; private final ProcessingStatusDTOMapper processingStatusDTOMapper; private final DeclarationDTOMapper declarationDTOMapper; private final ValidationResultDTOMapper validationResultDTOMapper; @Override public Movement getMovementById(String movementId) { return movementDTOMapper.toDomain(dossierMovementPort.findById(movementId, false).getBody()); } @Override public Movement updateMovement(Movement movement) { return movementDTOMapper.toDomain(dossierMovementPort.update(movementDTOMapper.toDTO(movement), movement.getId()).getBody()); } @Override public List<MessageOverview> getMessageOverviewList(String movementId, String messageType, Boolean isRejected) { PaginatedDTO<MessageOverviewDTO> messageOverviewDTOListBody = dossierMessagePort.findOverviewByCriteria(movementId, messageType, null, isRejected, null, null, 0, 20, false).getBody(); if (messageOverviewDTOListBody != null) { return messageOverviewDTOMapper.toDomain(messageOverviewDTOListBody.getContent()); } else { log.error("Message Overview list body was NULL, returning empty list."); return new ArrayList<>(); } } @Override public Message saveMessage(Message message) { return messageDTOMapper.toDomain(dossierMessagePort.add(messageDTOMapper.toDTO(message)).getBody()); } @Override public Message getMessageById(String messageId) { return messageDTOMapper.toDomain(dossierMessagePort.findById(messageId, false, false, false).getBody()); } @Override public void associateMessageWithMovement(String messageId, String movementId) { dossierMessagePort.associateMovement(messageId, movementId); } @Override public Message updateMessageStatus(String id, String status) { return messageDTOMapper.toDomain(dossierMessagePort.update(id, status).getBody()); } @Override public void saveProcessingStatus(ProcessingStatus processingStatus) { dossierProcessingStatusPort.add(processingStatusDTOMapper.toDTO(processingStatus)); } @Override public void createDeclaration(Declaration declaration) { dossierDeclarationPort.add(declarationDTOMapper.toDTO(declaration)); } @Override public Declaration getLatestDeclarationByMovementId(String movementId) { try { return declarationDTOMapper.toDomain(dossierDeclarationPort.findCurrentVersionByMovementId(movementId, false, false).getBody()); } catch (NotFoundException e) { return null; } } @Override public void saveValidationResultList(List<ValidationResult> validationResultList) { dossierValidationResultsPort.saveValidationResults(validationResultDTOMapper.toDTO(validationResultList)); } @Override public List<ValidationResult> findValidationResultListByMessageId(String messageId) { return validationResultDTOMapper.toDomain(dossierValidationResultsPort.findValidationResultsByMessageId(messageId).getBody()); } @Override public boolean mrnExists(String mrn) { return Boolean.TRUE.equals(dossierMovementPort.existsByCriteria(mrn, null, null, null).getBody()); } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service.DossierDataServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult; import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum; import com.intrasoft.ermis.platform.contracts.dossier.dtos.DeclarationDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.MessageDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.MovementDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.PaginatedDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.ProcessingStatusDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.ValidationResultDTO; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierDeclarationPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMessagePort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMovementPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierProcessingStatusPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierValidationResultsPort; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.ResponseEntity; @ExtendWith(MockitoExtension.class) class DossierDataServiceUT { private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID"; private static final String MESSAGE_ID = "TEST_MESSAGE_ID"; private static final String MESSAGE_IDENTIFICATION = "TEST_MESSAGE_IDENTIFICATION"; private static final String MRN = "TEST_MRN"; @Mock private DossierMovementPort dossierMovementPort; @Mock private DossierMessagePort dossierMessagePort; @Mock private DossierProcessingStatusPort dossierProcessingStatusPort; @Mock private DossierDeclarationPort dossierDeclarationPort; @Mock private DossierValidationResultsPort dossierValidationResultsPort; @Spy private MovementDTOMapper movementDTOMapper = new MovementDTOMapperImpl(); @Spy private MessageDTOMapper messageDTOMapper = new MessageDTOMapperImpl(); @Spy private MessageOverviewDTOMapper messageOverviewDTOMapper = new MessageOverviewDTOMapperImpl(); @Spy private ProcessingStatusDTOMapper processingStatusDTOMapper = new ProcessingStatusDTOMapperImpl(); @Spy private DeclarationDTOMapper declarationDTOMapper = new DeclarationDTOMapperImpl(); @Spy private ValidationResultDTOMapper validationResultDTOMapper = new ValidationResultDTOMapperImpl(); @InjectMocks private DossierDataServiceImpl dossierDataService; @Captor private ArgumentCaptor<MovementDTO> movementDTOArgumentCaptor; @Captor private ArgumentCaptor<ProcessingStatusDTO> processingStatusDTOArgumentCaptor; @Captor private ArgumentCaptor<DeclarationDTO> declarationDTOArgumentCaptor; @Captor private ArgumentCaptor<MessageDTO> messageDTOArgumentCaptor; @Captor private ArgumentCaptor<List<ValidationResultDTO>> validationResultDTOListArgumentCaptor; @Captor private ArgumentCaptor<String> messageIdCaptor; @Captor private ArgumentCaptor<String> statusCaptor; @Test @DisplayName("Test - Get Movement by ID") void testGetMovementById() { // Stub: when(dossierMovementPort.findById(MOVEMENT_ID, false)).thenReturn(ResponseEntity.ok(new MovementDTO())); // Call DossierDataService method: dossierDataService.getMovementById(MOVEMENT_ID); // Verification: verify(dossierMovementPort, times(1)).findById(MOVEMENT_ID, false); } @Test @DisplayName("Test - Update Movement") void testUpdateMovement() { Movement testMovement = Movement.builder().id(MOVEMENT_ID).build(); // Stub: when(dossierMovementPort.update(any(), eq(MOVEMENT_ID))).thenReturn(ResponseEntity.ok(new MovementDTO())); // Call DossierDataService method: dossierDataService.updateMovement(testMovement); // Verification & Assertion: verify(dossierMovementPort, times(1)).update(movementDTOArgumentCaptor.capture(), eq(MOVEMENT_ID)); assertEquals(MOVEMENT_ID, movementDTOArgumentCaptor.getValue().getId()); } @Test @DisplayName("Test - Get Message Overview List") void testGetMessageOverviewList() { // Stub: when(dossierMessagePort.findOverviewByCriteria(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null, null, null, null, 0, 20, false)).thenReturn(ResponseEntity.ok(new PaginatedDTO<>())); // Call DossierDataService method: dossierDataService.getMessageOverviewList(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null); // Verification: verify(dossierMessagePort, times(1)).findOverviewByCriteria(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null, null, null, null, 0, 20, false); } @Test @DisplayName("Test - Save Message") void testSaveMessage() { Message testMessage = Message.builder().messageIdentification(MESSAGE_IDENTIFICATION).build(); // Stub: when(dossierMessagePort.add(any(MessageDTO.class))).thenReturn(ResponseEntity.ok(new MessageDTO())); // Call DossierDataService method: dossierDataService.saveMessage(testMessage); // Verification & Assertion: verify(dossierMessagePort, times(1)).add(messageDTOArgumentCaptor.capture()); assertEquals(MESSAGE_IDENTIFICATION, messageDTOArgumentCaptor.getValue().getMessageIdentification()); } @Test @DisplayName("Test - Get Message by ID") void testGetMessageById() { // Stub: when(dossierMessagePort.findById(MESSAGE_ID, false, false, false)).thenReturn(ResponseEntity.ok(new MessageDTO())); // Call DossierDataService method: dossierDataService.getMessageById(MESSAGE_ID); // Verification: verify(dossierMessagePort, times(1)).findById(MESSAGE_ID, false, false, false); } @Test @DisplayName("Test - Associate Message with Movement") void testAssociateMessageWithMovement() { // Stub: when(dossierMessagePort.associateMovement(MESSAGE_ID, MOVEMENT_ID)).thenReturn(ResponseEntity.ok(null)); // Call DossierDataService method: dossierDataService.associateMessageWithMovement(MESSAGE_ID, MOVEMENT_ID); // Verification: verify(dossierMessagePort, times(1)).associateMovement(MESSAGE_ID, MOVEMENT_ID); } @Test @DisplayName("Test - Update Message Status") void testUpdateMessageStatus() { // Stub: when(dossierMessagePort.update(MESSAGE_ID, MessageStatusEnum.REJECTED.name())).thenReturn(ResponseEntity.ok(new MessageDTO())); // Call DossierDataService method: dossierDataService.updateMessageStatus(MESSAGE_ID, MessageStatusEnum.REJECTED.name()); // Verification: verify(dossierMessagePort, times(1)).update(MESSAGE_ID, MessageStatusEnum.REJECTED.name()); } @Test @DisplayName("Test - Save Processing Status") void testSaveProcessingStatus() { ProcessingStatus testProcessingStatus = ProcessingStatus.builder() .movementId(MOVEMENT_ID) .status("TEST_STATUS") .reasonType("TEST_REASON") .build(); // Call DossierDataService method: dossierDataService.saveProcessingStatus(testProcessingStatus); // Verification & Assertions: verify(dossierProcessingStatusPort, times(1)).add(processingStatusDTOArgumentCaptor.capture()); assertEquals(testProcessingStatus.getMovementId(), processingStatusDTOArgumentCaptor.getValue().getMovementId()); assertEquals(testProcessingStatus.getStatus(), processingStatusDTOArgumentCaptor.getValue().getStatus()); assertEquals(testProcessingStatus.getReasonType(), processingStatusDTOArgumentCaptor.getValue().getReasonType()); } @Test @DisplayName("Test - Create Declaration") void testCreateDeclaration() { Declaration testMovement = Declaration.builder().movementId(MOVEMENT_ID).build(); // Call DossierDataService method: dossierDataService.createDeclaration(testMovement); // Verification & Assertion: verify(dossierDeclarationPort, times(1)).add(declarationDTOArgumentCaptor.capture()); assertEquals(MOVEMENT_ID, declarationDTOArgumentCaptor.getValue().getMovementId()); } @Test @DisplayName("Test - Get latest Declaration by Movement ID") void testGetLatestDeclarationByMovementId() { // Stub: when(dossierDeclarationPort.findCurrentVersionByMovementId(MOVEMENT_ID, false, false)).thenReturn(ResponseEntity.ok(new DeclarationDTO())); // Call DossierDataService method: dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID); // Verification: verify(dossierDeclarationPort, times(1)).findCurrentVersionByMovementId(MOVEMENT_ID, false, false); } @Test @DisplayName("Test - Save Validation Result List") void testSaveValidationResultList() { List<ValidationResult> testValidationResultList = new ArrayList<>(); ValidationResult testValidationResult = new ValidationResult(); testValidationResult.setMessageId(MESSAGE_ID); testValidationResultList.add(testValidationResult); // Call DossierDataService method: dossierDataService.saveValidationResultList(testValidationResultList); // Verification & Assertion: verify(dossierValidationResultsPort, times(1)).saveValidationResults(validationResultDTOListArgumentCaptor.capture()); assertEquals(MESSAGE_ID, validationResultDTOListArgumentCaptor.getValue().get(0).getMessageId()); } @Test @DisplayName("Test - Find Validation Result list by Message ID") void testFindValidationResultListByMessageId() { // Stub: when(dossierValidationResultsPort.findValidationResultsByMessageId(MESSAGE_ID)).thenReturn(ResponseEntity.ok(new ArrayList<>())); // Call DossierDataService method: dossierDataService.findValidationResultListByMessageId(MESSAGE_ID); // Verification: verify(dossierValidationResultsPort, times(1)).findValidationResultsByMessageId(MESSAGE_ID); } @ParameterizedTest @DisplayName("Test - MRN Exists") @ValueSource(booleans = {true, false}) void testMRNExists(boolean mrnExists) { // Stub: when(dossierMovementPort.existsByCriteria(MRN, null, null, null)) .thenReturn(ResponseEntity.ok(mrnExists)); // Call DossierDataService method: boolean returnedValue = dossierDataService.mrnExists(MRN); // Verification & Assertion: verify(dossierMovementPort, times(1)).existsByCriteria(MRN, null, null, null); assertEquals(mrnExists, returnedValue); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofdeparture.service; import static com.intrasoft.ermis.transit.common.util.TimerInfoUtil.convertToDelayWithTimeUnit; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CC170CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.platform.shared.client.configuration.core.ConfigurationDataPort; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.platform.shared.client.reference.data.core.ReferenceDataAdapter; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListDomain; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListItem; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.common.config.util.ConfigurationUtil; import com.intrasoft.ermis.transit.common.enums.CountryCodesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import com.intrasoft.ermis.transit.contracts.core.enums.DeclarationTypeEnum; import com.intrasoft.ermis.transit.contracts.core.enums.TimerInfoEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.domain.MovementAttribute; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.MovementAttributesEnum; import com.intrasoft.ermis.transit.officeofdeparture.service.property.PropertyService; import com.intrasoft.proddev.referencedata.shared.enums.CodelistKeyEnum; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class ReleaseTransitServiceImpl implements ReleaseTransitService { private static final String RECOVERY_RECOMMENDED_TIMER_RS = "getRecoveryRecommendedTimerDelayConfigRS"; private static final String INFORM_GUARANTOR_TIMER_RS = "getOoDepInformGuarantorTimerRS"; private static final String RECEIPT_CONTROL_RESULTS_TIMER_RS = "getReceiptControlResultsTimerDelayConfigRS"; private static final String MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS = "getMinimumAndMaximumDaysForArrivalRS"; private static final String TIME_TO_ENQUIRE_HOLDER_TIMER_RS = "getTimeToEnquireHolderDelayTimerRS"; public static final String END_OF_DAY_DATE_TIME_FORMAT_SUFFIX = "T23:59:59"; public static final String GET_CCN_GW_LOOPBACK_ENABLED_RS = "getCcnGwLoopbackEnabledRS"; private final ErmisLogger log; private final DossierDataService dossierDataService; private final TimerDelayExecutor timerDelayExecutor; private final PropertyService propertyService; private final SimplifiedDeclarationService simplifiedDeclarationService; private final ReferenceDataAdapter referenceDataAdapter; private final DeclarationService declarationService; private final ConfigurationDataPort configurationDataPort; private final ErmisConfigurationService ermisConfigurationService; private final ProcessingStatusService processingStatusService; @Override public boolean checkIfDeclarationIsTypeTIR(String movementId) { log.info("ENTER checkIfDeclarationIsTypeTIR()"); boolean isTypeTIR = false; CC015CType cc015cMessage = declarationService.getDeclarationPayload(movementId); if (cc015cMessage.getTransitOperation() != null && cc015cMessage.getTransitOperation().getDeclarationType() != null) { List<CodeListItem> typeOfDeclarationTIRList = referenceDataAdapter.getCodeListItems(CodelistKeyEnum.TYPE_OF_DECLARATION_TIR.getKey(), LocalDate.now(), null, null, "EN", CodeListDomain.NCTSP5); Set<String> typeOfDeclarationTIRListSet = typeOfDeclarationTIRList.stream().map(CodeListItem::getCode).collect(Collectors.toSet()); isTypeTIR = typeOfDeclarationTIRListSet.stream().anyMatch(type -> type.equals(cc015cMessage.getTransitOperation().getDeclarationType())); } log.info("EXIT checkIfDeclarationIsTypeTIR()"); return isTypeTIR; } @Override public boolean checkIfDeclarationIsElectronicallySubmitted(String movementId) { log.info("ENTER checkIfDeclarationIsElectronicallySubmitted()"); log.info("EXIT checkIfDeclarationIsElectronicallySubmitted()"); return declarationService.checkIfDeclarationIsElectronicallySubmitted(movementId); } @Override public boolean checkIfDeclaredOfficeOfExitForTransitExist(String movementId) { log.info("ENTER checkIfDeclaredOfficeOfExitExist()"); CC015CType cc015cMessage = declarationService.getDeclarationPayload(movementId); log.info("EXIT checkIfDeclaredOfficeOfExitExist()"); return cc015cMessage.getCustomsOfficeOfExitForTransitDeclared() == null || cc015cMessage.getCustomsOfficeOfExitForTransitDeclared().isEmpty(); } @Override public boolean isCcnGwLoopbackEnabled() { String isCcnGwLoopbackEnabled = null; List<Configuration> configurationList = configurationDataPort.getConfigurationsByRuleTemplateName(GET_CCN_GW_LOOPBACK_ENABLED_RS); Optional<Configuration> configurationOptional = configurationList.stream().filter(configuration -> this.isApplicable(configuration, LocalDateTime.now(ZoneOffset.UTC))).findFirst(); if (configurationOptional.isPresent()) { isCcnGwLoopbackEnabled = configurationOptional.get().getEvaluationParams().get("ccnGwLoopbackEnabled"); } return Boolean.parseBoolean(isCcnGwLoopbackEnabled); } @Override public void updateState(String movementId, String processingStatus) { Movement movement = dossierDataService.getMovementById(movementId); if (ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode().equals(movement.getProcessingStatus()) || ProcessingStatusTypeEnum.OODEP_ARRIVED.getItemCode().equals(movement.getProcessingStatus())) { processingStatusService.saveProcessingStatus(movementId, processingStatus); } } @Override public String getArrivalAdviceTimerDelayConfig(String movementId, String date, Boolean isPrelodged) throws Exception { String dueDate = date + END_OF_DAY_DATE_TIME_FORMAT_SUFFIX; CC015CType cc015CType = declarationService.getDeclarationPayload(movementId); // If message is simplified, arrivalAdviceTimer is set to limitDate of message: if (simplifiedDeclarationService.checkIfDeclarationIsSimplified(movementId, propertyService.getManualReleaseForTransitProperty())) { // If simplified Declaration is prelodged, return IE170 limitDate, if not found, return latest Declaration limitDate: // (IE013 limitDate if amended, else IE015 limitDate.) if (isPrelodged != null && isPrelodged) { CC170CType cc170cType = getCC170CMessage(movementId); if (cc170cType != null && ObjectUtils.isNotEmpty(cc170cType.getTransitOperation().getLimitDate())) { dueDate = calculateExpectedArrivalTime(cc170cType.getTransitOperation().getLimitDate()); } else { dueDate = calculateExpectedArrivalTime(cc015CType.getTransitOperation().getLimitDate()); } } else { if (cc015CType.getTransitOperation().getLimitDate() != null) { dueDate = calculateExpectedArrivalTime(cc015CType.getTransitOperation().getLimitDate()); } } } persistExpectedArrivalDate(movementId, dueDate); return dueDate; } /** * <pre> * @param arrivalAdviceDateInIso8601 : Initially was in 8601 Date format YYYY-MM-DD, then it was modified to 8601 DateAndTime Format with 'T23:59:59' in the time part * The current implementation detects the Date or DateTime format by checking for the existence of the time designator "T" in the value * @return the expiration date of the Timer in ISO8601 Date and time format. e.g. 2024-01-30T23:59:59. * Will add the suffix '23:59:59' to the calculated 8601 formatted Date * If the "Delay" Rule Instance parameter value is a non-positive number the method will return NULL and the Timer will not be started by the Camunda Flow */ @Override public String getInformGuarantorTimerDelayConfig(String arrivalAdviceDateInIso8601) { LocalDate arrivalAdviceDate = LocalDate.parse(arrivalAdviceDateInIso8601, arrivalAdviceDateInIso8601.contains("T") ? DateTimeFormatter.ISO_LOCAL_DATE_TIME : DateTimeFormatter.ISO_LOCAL_DATE); Map<String, String> params = ermisConfigurationService.getConfigurationByTemplateName(INFORM_GUARANTOR_TIMER_RS) .getEvaluationParams(); // If the [delay] param value is a non-positive integer then return NULL and the timer will not start if (Integer.parseInt(params.get(TimerInfoEnum.DELAY.getValue())) <= 0) { return null; } else { String timeUnit = params.get(TimerInfoEnum.TIMEUNIT.getValue()); String delay = params.get(TimerInfoEnum.DELAY.getValue()); Duration delayWithTimeUnit = convertToDelayWithTimeUnit(timeUnit, delay); LocalDateTime timerExpirationDateTime = arrivalAdviceDate.atStartOfDay().plus(delayWithTimeUnit); return timerExpirationDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE) + END_OF_DAY_DATE_TIME_FORMAT_SUFFIX; } } @Override public TimerInfo getRecoveryRecommendedTimerDelayConfig(String movementId) { Movement movement = dossierDataService.getMovementById(movementId); return getTimerInfo(movement.getCreatedDateTime(), RECOVERY_RECOMMENDED_TIMER_RS, true); } @Override public TimerInfo getTimeToEnquireHolderTimerDelayConfig(String movementId) { return getTimerInfo(LocalDateTime.now(ZoneOffset.UTC), TIME_TO_ENQUIRE_HOLDER_TIMER_RS, true); } @Override public TimerInfo getReceiptControlResultsTimerDelayConfig(String date) { return getTimerInfo(LocalDateTime.parse(date), RECEIPT_CONTROL_RESULTS_TIMER_RS, true); } private TimerInfo getTimerInfo(LocalDateTime date, String ruleSet, boolean expiresAtEndOfDay) { TimerInfo timerInfo; Optional<TimerInfo> optionalTimerInfo = timerDelayExecutor.getTimerDelayConfig(date, LocalDateTime.now(), ruleSet, expiresAtEndOfDay); if (optionalTimerInfo.isPresent()) { timerInfo = optionalTimerInfo.get(); } else { throw new IllegalStateException("Failed to setup timer!"); } return timerInfo; } @Override public boolean isOfficeOfTransitDeclared(String movementId) { log.info("ENTER isOfficeOfTransitDeclared()"); CC015CType cc015cMessage = declarationService.getDeclarationPayload(movementId); log.info("EXIT isOfficeOfTransitDeclared()"); return cc015cMessage.getCustomsOfficeOfTransitDeclared() == null || cc015cMessage.getCustomsOfficeOfTransitDeclared().isEmpty(); } public boolean isT1DeclarationMovementType(String movementId) { CC015CType cc015CType = declarationService.getDeclarationPayload(movementId); return cc015CType.getTransitOperation() != null && cc015CType.getTransitOperation().getDeclarationType() != null && DeclarationTypeEnum.T1.getValue().equals(cc015CType.getTransitOperation().getDeclarationType()); } /* Should return TRUE, if DeclarationType is 'T' and: * ALL Consignment Items of one House Consignment are 'T1' * OR * A House Consignment consists of a mix of Consignment Items * [mix of ‘T1’ and (‘T2’ or ‘T2F’)] * --- * This can be reduced to the following logic: * A House Consignment exists with at least one 'T1' Consignment Item. * --- * ELSE FALSE */ public boolean isMixedDeclarationTypeWithT1ConsignmentItem(String movementId) { CC015CType cc015cTypeMessage = declarationService.getDeclarationPayload(movementId); return cc015cTypeMessage.getTransitOperation() != null && DeclarationTypeEnum.T.getValue() .equals(cc015cTypeMessage.getTransitOperation().getDeclarationType()) && cc015cTypeMessage.getConsignment().getHouseConsignment().stream().anyMatch(houseConsignment -> houseConsignment.getConsignmentItem().stream().anyMatch(item -> DeclarationTypeEnum.T1.getValue().equals(item.getDeclarationType()))); } @Override public boolean isRussiaCountryOfDestination(String movementId) { CC015CType cc015cMessage = declarationService.getDeclarationPayload(movementId); if (Objects.nonNull(cc015cMessage.getConsignment()) && !StringUtils.isBlank(cc015cMessage.getConsignment().getCountryOfDestination()) && CountryCodesEnum.RUSSIA.getCountryCode().equals(cc015cMessage.getConsignment().getCountryOfDestination())) { return true; } else if (!cc015cMessage.getConsignment().getHouseConsignment().isEmpty()) { return cc015cMessage.getConsignment() .getHouseConsignment() .stream() .flatMap(houseConsignment -> houseConsignment.getConsignmentItem().stream()) .filter(Objects::nonNull) .anyMatch(consignmentItem -> CountryCodesEnum.RUSSIA.getCountryCode().equals(consignmentItem.getCountryOfDestination())); } return false; } private CC170CType getCC170CMessage(String movementId) { CC170CType cc170cType = null; try { List<MessageOverview> ie170MessageOverviewList = dossierDataService.getMessagesOverview(movementId, MessageTypes.CC_170_C.value(), false); if (!ie170MessageOverviewList.isEmpty()) { Message cc170cTypeMessage = dossierDataService.getMessageById(ie170MessageOverviewList.get(0).getId()); cc170cType = XmlConverter.buildMessageFromXML(cc170cTypeMessage.getPayload(), CC170CType.class); } } catch (JAXBException e) { throw new BaseException("Error building message from XML string ", e); } catch (Exception e) { throw new BaseException("Error getting message from DB ", e); } return cc170cType; } private boolean isApplicable(Configuration configuration, LocalDateTime referenceDate) { return ConfigurationUtil.isApplicableForEffectiveDate(configuration, referenceDate); } private String calculateExpectedArrivalTime(LocalDate payloadLimitDate) { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS); long minimumDays; long maximumDays; try { minimumDays = Long.parseLong(configuration.getEvaluationParams().get("minimumDays")); maximumDays = Long.parseLong(configuration.getEvaluationParams().get("maximumDays")); if (minimumDays <= 0 || maximumDays <= 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new BaseException("Wrong configuration parameters"); } if (payloadLimitDate.isBefore(LocalDate.now(ZoneOffset.UTC).plusDays(minimumDays)) || payloadLimitDate.isAfter(LocalDate.now(ZoneOffset.UTC).plusDays(maximumDays))) { return LocalDateTime.now(ZoneOffset.UTC).plusDays(minimumDays).withHour(23).withMinute(59).withSecond(59).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); } LocalDateTime payloadLimitDateTime = payloadLimitDate.atStartOfDay(); return payloadLimitDateTime.withHour(23).withMinute(59).withSecond(59).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); } /** * Persist expected arrival date as movement attribute for future references (e.g. diversion messages) Note: can be utilized be release related messages (IE * 029/001/050/160) which currently utilize bpmn variable * * @param movementId id of the movement * @param expectedArrivalDateTime the expected arrival due date at date time format */ private void persistExpectedArrivalDate(String movementId, String expectedArrivalDateTime) { log.info("persistExpectedArrivalDate for movementId={} and expectedArrivalDateTime={}", movementId, expectedArrivalDateTime); MovementAttribute movementAttribute = MovementAttribute.builder() .movementId(movementId) .attrKey(MovementAttributesEnum.EXPECTED_ARRIVAL_DATE.getValue()) .attrValue(expectedArrivalDateTime.split("T")[0]) .build(); dossierDataService.saveMovementAttribute(movementAttribute); } }
package com.intrasoft.ermis.trs.officeofdeparture.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CC170CType; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentItemType09; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentType20; import com.intrasoft.ermis.ddntav5152.messages.HouseConsignmentType10; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.ddntav5152.messages.TransitOperationType06; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.contracts.core.enums.DeclarationTypeEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.service.DeclarationService; import com.intrasoft.ermis.transit.officeofdeparture.service.ReleaseTransitServiceImpl; import com.intrasoft.ermis.transit.officeofdeparture.service.SimplifiedDeclarationService; import com.intrasoft.ermis.transit.officeofdeparture.service.property.PropertyService; import com.intrasoft.ermis.trs.officeofdeparture.util.GeneratorHelper; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class ReleaseTransitServiceUT extends GeneratorHelper { @Mock private ErmisLogger log; private static final String MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS = "getMinimumAndMaximumDaysForArrivalRS"; private static final String MINIMUM_DAYS = "1"; private static final String MAXIMUM_DAYS = "30"; private static final String ERROR_MESSAGE = "Wrong configuration parameters"; private static final String EXISTING_DUE_DATE = "2020-02-02"; @Mock private ErmisConfigurationService ermisConfigurationService; @Mock private PropertyService propertyService; @Mock private SimplifiedDeclarationService simplifiedDeclarationService; @Mock private DeclarationService declarationService; @InjectMocks private ReleaseTransitServiceImpl releaseTransitService; @ParameterizedTest @MethodSource("namedArguments") @DisplayName("Test that limit date is not between the allowed bounds for normal simplified") void test_getExpectedArrivalTimerIfLimitDateIsWrongForNormalSimplifiedDeclaration(LocalDate limitDate) { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); cc015CType.getTransitOperation().setLimitDate(limitDate); when(declarationService.getDeclarationPayload(MOVEMENT_ID)).thenReturn(cc015CType); when(simplifiedDeclarationService.checkIfDeclarationIsSimplified(anyString(), anyBoolean())).thenReturn(true); when(ermisConfigurationService.getConfigurationByTemplateName(MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS)) .thenReturn(createConfiguration(MINIMUM_DAYS, MAXIMUM_DAYS)); String dueDate = releaseTransitService.getArrivalAdviceTimerDelayConfig(MOVEMENT_ID, EXISTING_DUE_DATE, false); assertEquals(LocalDate.now(ZoneOffset.UTC).plusDays(Long.parseLong(MINIMUM_DAYS)), LocalDate.parse(dueDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); assertNotEquals(cc015CType.getTransitOperation().getLimitDate(), LocalDate.parse(dueDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } catch (Exception e) { fail(); } } @Test @DisplayName("Test that limit date is between the allowed bounds for presented prelodged simplified") void test_getExpectedArrivalTimerIfLimitDateIsCorrectForPrelodgedSimplifiedWithGPR() { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); CC170CType cc170CType = XmlConverter.buildMessageFromXML(loadTextFile("CC170C"), CC170CType.class); cc015CType.getTransitOperation().setLimitDate(LocalDate.now(ZoneOffset.UTC).plusDays(15)); cc170CType.getTransitOperation().setLimitDate(LocalDate.now(ZoneOffset.UTC).plusDays(20)); Message cc170cMessage = createCC170CMessage(cc170CType); when(declarationService.getDeclarationPayload(MOVEMENT_ID)).thenReturn(cc015CType); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CC_170_C.value(), false)).thenReturn(List.of(cc170cMessage)); when(dossierDataService.getMessageById(anyString())).thenReturn(cc170cMessage); when(simplifiedDeclarationService.checkIfDeclarationIsSimplified(anyString(), anyBoolean())).thenReturn(true); when(ermisConfigurationService.getConfigurationByTemplateName(MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS)) .thenReturn(createConfiguration(MINIMUM_DAYS, MAXIMUM_DAYS)); String dueDate = releaseTransitService.getArrivalAdviceTimerDelayConfig(MOVEMENT_ID, EXISTING_DUE_DATE, true); assertEquals(cc170CType.getTransitOperation().getLimitDate(), LocalDate.parse(dueDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); assertNotEquals(cc015CType.getTransitOperation().getLimitDate(), LocalDate.parse(dueDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } catch (Exception e) { fail(); } } @Test @DisplayName("Test that limit date is between the allowed bounds for non presented prelodged simplified") void test_getExpectedArrivalTimerIfLimitDateIsCorrectForPrelodgedSimplifiedWithoutGPR() { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); cc015CType.getTransitOperation().setLimitDate(LocalDate.now(ZoneOffset.UTC).plusDays(15)); when(declarationService.getDeclarationPayload(MOVEMENT_ID)).thenReturn(cc015CType); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CC_170_C.value(), false)).thenReturn(List.of()); when(simplifiedDeclarationService.checkIfDeclarationIsSimplified(anyString(), anyBoolean())).thenReturn(true); when(ermisConfigurationService.getConfigurationByTemplateName(MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS)) .thenReturn(createConfiguration(MINIMUM_DAYS, MAXIMUM_DAYS)); String dueDate = releaseTransitService.getArrivalAdviceTimerDelayConfig(MOVEMENT_ID, EXISTING_DUE_DATE, true); assertEquals(cc015CType.getTransitOperation().getLimitDate(), LocalDate.parse(dueDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } catch (Exception e) { fail(); } } @Test @DisplayName("Test that limit date is between the allowed bounds for normal simplified") void test_getExpectedArrivalTimerIfLimitDateIsCorrectForNormalSimplifiedDeclaration() { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); cc015CType.getTransitOperation().setLimitDate(LocalDate.now(ZoneOffset.UTC).plusDays(15)); when(declarationService.getDeclarationPayload(MOVEMENT_ID)).thenReturn(cc015CType); when(simplifiedDeclarationService.checkIfDeclarationIsSimplified(anyString(), anyBoolean())).thenReturn(true); when(ermisConfigurationService.getConfigurationByTemplateName(MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS)) .thenReturn(createConfiguration(MINIMUM_DAYS, MAXIMUM_DAYS)); String dueDate = releaseTransitService.getArrivalAdviceTimerDelayConfig(MOVEMENT_ID, EXISTING_DUE_DATE, false); assertEquals(cc015CType.getTransitOperation().getLimitDate(), LocalDate.parse(dueDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } catch (Exception e) { fail(); } } @ParameterizedTest @MethodSource("namedArguments2") @DisplayName("Test that configuration values are incorrect") void test_getExpectedArrivalTimerWithWrongConfigurationValues(int configurationParameter, String value) { String configParam1 = MINIMUM_DAYS; String configParam2 = MAXIMUM_DAYS; if(configurationParameter == 1) { configParam1 = value; } else { configParam2 = value; } try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); cc015CType.getTransitOperation().setLimitDate(LocalDate.now(ZoneOffset.UTC).plusDays(15)); when(declarationService.getDeclarationPayload(MOVEMENT_ID)).thenReturn(cc015CType); when(simplifiedDeclarationService.checkIfDeclarationIsSimplified(anyString(), anyBoolean())).thenReturn(true); when(ermisConfigurationService.getConfigurationByTemplateName(MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS)) .thenReturn(createConfiguration(configParam1, configParam2)); BaseException thrownException = assertThrows(BaseException.class, () -> releaseTransitService.getArrivalAdviceTimerDelayConfig(MOVEMENT_ID, EXISTING_DUE_DATE, false)); assertEquals(ERROR_MESSAGE, thrownException.getMessage()); } catch (Exception e) { fail(); } } @Test @DisplayName("Test that the existing due date is used for non simplified") void test_getExpectedArrivalTimerForNoSimplified() { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C_valid"), CC015CType.class); when(declarationService.getDeclarationPayload(MOVEMENT_ID)).thenReturn(cc015CType); when(simplifiedDeclarationService.checkIfDeclarationIsSimplified(anyString(), anyBoolean())).thenReturn(false); String dueDate = releaseTransitService.getArrivalAdviceTimerDelayConfig(MOVEMENT_ID, EXISTING_DUE_DATE, false); assertEquals(EXISTING_DUE_DATE+"T23:59:59", dueDate); verify(ermisConfigurationService, times(0)).getConfigurationByTemplateName(MINIMUM_AND_MAXIMUM_EXPECTED_ARRIVAL_TIME_RS); } catch (Exception e) { fail(); } } @ParameterizedTest @DisplayName("Test - Is Mixed Declaration Type With T1 Consignment Item") @ValueSource(booleans = {true, false}) void testIsMixedDeclarationTypeWithT1ConsignmentItem(boolean isExternalTransit) { // Mocks/Stubs: when(declarationService.getDeclarationPayload(MOVEMENT_ID)).thenReturn(buildIE015(DeclarationTypeEnum.T.getValue(), isExternalTransit)); // Call service method: boolean returnedValue = releaseTransitService.isMixedDeclarationTypeWithT1ConsignmentItem(MOVEMENT_ID); // Verification & Assertion: verify(declarationService, times(1)).getDeclarationPayload(MOVEMENT_ID); assertEquals(isExternalTransit, returnedValue); } static Stream<Arguments> namedArguments() { return Stream.of( Arguments.of(Named.of(" after maximum days", LocalDate.now(ZoneOffset.UTC).plusDays(50))), Arguments.of(Named.of(" before minimum days", LocalDate.now(ZoneOffset.UTC).minusDays(10))) ); } static Stream<Arguments> namedArguments2() { return Stream.of( Arguments.of(Named.of(" minimumDays", 1), Named.of(" alphanumeric", "abc123")), Arguments.of(Named.of(" minimumDays", 1), Named.of(" zero", "0")), Arguments.of(Named.of(" minimumDays", 1), Named.of(" negative", "-19")), Arguments.of(Named.of(" maximumDays", 2), Named.of(" alphanumeric", "abc123")), Arguments.of(Named.of(" maximumDays", 2), Named.of(" zero", "0")), Arguments.of(Named.of(" maximumDays", 2), Named.of(" negative", "-19")) ); } private Configuration createConfiguration(String minDays, String maxDays) { Map<String, String> evalParams = Map.of("minimumDays", minDays, "maximumDays", maxDays); return new Configuration( null, null, null, evalParams, null, null, null, null); } private Message createCC170CMessage(CC170CType cc170CType) { return Message.builder() .id(MESSAGE_ID) .messageType(MessageTypes.CC_170_C.value()) .payload(XmlConverter.marshal(cc170CType)) .build(); } private CC015CType buildIE015(String declarationType, boolean isExternalTransit) { CC015CType ie015 = new CC015CType(); ie015.setTransitOperation(new TransitOperationType06()); ie015.getTransitOperation().setDeclarationType(declarationType); ie015.setConsignment(new ConsignmentType20()); ie015.getConsignment().getHouseConsignment().add(buildIE015HouseConsignment(false)); ie015.getConsignment().getHouseConsignment().add(buildIE015HouseConsignment(isExternalTransit)); return ie015; } private HouseConsignmentType10 buildIE015HouseConsignment(boolean isExternalTransit) { HouseConsignmentType10 houseConsignment = new HouseConsignmentType10(); houseConsignment.getConsignmentItem().add(buildIE015ConsignmentItem(false)); houseConsignment.getConsignmentItem().add(buildIE015ConsignmentItem(isExternalTransit)); return houseConsignment; } private ConsignmentItemType09 buildIE015ConsignmentItem(boolean isExternalTransit) { ConsignmentItemType09 consignmentItem = new ConsignmentItemType09(); if (isExternalTransit) { consignmentItem.setDeclarationType(DeclarationTypeEnum.T1.getValue()); } else { consignmentItem.setDeclarationType(DeclarationTypeEnum.T2.getValue()); } return consignmentItem; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.management.core.service.report; import static com.intrasoft.ermis.transit.management.core.service.report.ReportServiceImpl.VALID_NP_REPORT_MESSAGE_TYPES; import static com.intrasoft.ermis.transit.management.core.service.report.ReportServiceImpl.VALID_TAD_REPORT_MESSAGE_TYPES; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC013CType; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CC029CType; import com.intrasoft.ermis.ddntav5152.messages.CD001CType; import com.intrasoft.ermis.ddntav5152.messages.CD003CType; import com.intrasoft.ermis.ddntav5152.messages.CD038CType; import com.intrasoft.ermis.ddntav5152.messages.CD050CType; import com.intrasoft.ermis.ddntav5152.messages.CD115CType; import com.intrasoft.ermis.ddntav5152.messages.CD160CType; import com.intrasoft.ermis.ddntav5152.messages.CD165CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.management.domain.Message; import java.util.Objects; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.springframework.stereotype.Service; /** * <pre> * Generates a CC029C type message from a compatible DDNTA message type of one of the following types * CC015C * If the input message is already a CC029C type, then no conversion takes place * The generated CC029C message will be fed to the existing TAD report generation implementation */ @Service @RequiredArgsConstructor public class ReportMessageTranslatorImpl implements ReportMessageTranslatorService{ private final MessageTypeMapper messageTypeMapper; public Message generateCC029CTypeMessageFromOriginalMessage(Message originalMessage) { MessageTypes originalMessageType = findMessageType(originalMessage); if (originalMessageType == MessageTypes.CC_029_C) { return originalMessage; } else if (VALID_TAD_REPORT_MESSAGE_TYPES.contains(originalMessageType)) { return mapToCC029C(originalMessage, originalMessageType); } else { throw new BaseException(String.format("IE message of type: '%s' is not valid for TAD generation", originalMessageType.value())); } } public Message generateCC015CTypeMessageFromOriginalMessage(Message originalMessage) { MessageTypes originalMessageType = findMessageType(originalMessage); if (originalMessageType == MessageTypes.CC_015_C) { return originalMessage; } else if (VALID_NP_REPORT_MESSAGE_TYPES.contains(originalMessageType)) { return mapToCC015C(originalMessage, originalMessageType); } else { throw new BaseException(String.format("IE message of type: '%s' is not valid for TAD generation", originalMessageType.value())); } } public static MessageTypes findMessageType(Message message) { String messageId = message.getId(); String messageType = message.getMessageType(); try { return MessageTypes.fromValue(messageType); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException(String.format("Unknown DDNTA message type: '%s' for IE message with id '%s'.", messageType, messageId), ex); } } protected Message mapToCC029C(Message message, MessageTypes messageType) { return generateCC029CMessage(message.getPayload(), generateDDNTAClassFromMessageType(messageType)); } protected Message mapToCC015C(Message message, MessageTypes messageType) { return generateCC015CMessage(message.getPayload(), generateDDNTAClassFromMessageType(messageType)); } @SneakyThrows protected <T> Message generateCC029CMessage(String xmlPayload, Class<T> clazz) { T t = XmlConverter.buildMessageFromXML(xmlPayload, clazz); return Message.builder().payload( XmlConverter.marshal( enhanceGeneratedCC029C(convertToCC029C(t)))) .messageType(MessageTypes.CC_029_C.value()) .build(); } @SneakyThrows protected <T> Message generateCC015CMessage(String xmlPayload, Class<T> clazz) { T t = XmlConverter.buildMessageFromXML(xmlPayload, clazz); return Message.builder().payload( XmlConverter.marshal( enhanceGeneratedCC015C(convertToCC015C(t)))) .messageType(MessageTypes.CC_015_C.value()) .build(); } protected <T> CC029CType convertToCC029C(T t) { CC029CType result; var messageType = MessagTypesConvertibleToCC029CEnum.fromValue(t.getClass().getSimpleName()); switch (Objects.requireNonNull(messageType)) { case CC015C: result = messageTypeMapper.fromCC015CtoCC029C((CC015CType) t); break; case CD001C: result = messageTypeMapper.fromCD001CToCC029C((CD001CType) t); break; case CD003C: result = messageTypeMapper.fromCD003CToCC029C((CD003CType) t); break; case CD160C: result = messageTypeMapper.fromCD160CToCC029C((CD160CType) t); break; case CD165C: result = messageTypeMapper.fromCD165CToCC029C((CD165CType) t); break; case CD050C: result = messageTypeMapper.fromCD050CToCC029C((CD050CType) t); break; case CD115C: result = messageTypeMapper.fromCD115CToCC029C((CD115CType) t); break; case CD038C: result = messageTypeMapper.fromCD038CToCC029C((CD038CType) t); break; default: throw new BaseException("Invalid message Type Class: " + t.getClass().getSimpleName()); } result.setMessageType(MessageTypes.CC_029_C); return result; } protected <T> CC015CType convertToCC015C(T t) { CC015CType result; var messageType = MessageTypesConvertibleToCC013CEnum.fromValue(t.getClass().getSimpleName()); switch (Objects.requireNonNull(messageType)) { case CC013C: result = messageTypeMapper.fromCC013toCC015CType((CC013CType) t); break; default: throw new BaseException("Invalid message Type Class: " + t.getClass().getSimpleName()); } result.setMessageType(MessageTypes.CC_015_C); return result; } /** * Potentially enrich the generated CC029C with possible extra elements that are missing in the Original Documents and are needed in the TAD document. * Nothing found till now though e.g. <combinedNomenclatureCode></combinedNomenclatureCode> */ private static CC029CType enhanceGeneratedCC029C(CC029CType cc029CType) { return cc029CType; } private static CC015CType enhanceGeneratedCC015C(CC015CType cc015Type) { return cc015Type; } @SneakyThrows public static Class<?> generateDDNTAClassFromMessageType(MessageTypes messageType) { return Class.forName(MessageTypes.class.getPackageName() + "." + messageType.value() + "Type"); } @RequiredArgsConstructor enum MessagTypesConvertibleToCC029CEnum { CD001C(CD001CType.class.getSimpleName()), CD003C(CD003CType.class.getSimpleName()), CD160C(CD160CType.class.getSimpleName()), CD165C(CD165CType.class.getSimpleName()), CD050C(CD050CType.class.getSimpleName()), CD115C(CD115CType.class.getSimpleName()), CD038C(CD038CType.class.getSimpleName()), CC015C(CC015CType.class.getSimpleName()); private final String classSimpleName; public static MessagTypesConvertibleToCC029CEnum fromValue(String value) { for (MessagTypesConvertibleToCC029CEnum e : values()) { if (e.classSimpleName.equals(value)) { return e; } } return null; } } @RequiredArgsConstructor enum MessageTypesConvertibleToCC013CEnum { CC013C(CC013CType.class.getSimpleName()); private final String classSimpleName; public static MessageTypesConvertibleToCC013CEnum fromValue(String value) { for (MessageTypesConvertibleToCC013CEnum e : values()) { if (e.classSimpleName.equals(value)) { return e; } } return null; } } }
package com.intrasoft.ermis.transit.management.core.service; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapperImpl; import com.intrasoft.ermis.transit.management.core.service.report.ReportMessageTranslatorImpl; import com.intrasoft.ermis.transit.management.domain.Message; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(MockitoExtension.class) class ReportMessageTranslatorUT { @Spy private MessageTypeMapper messageTypeMapper = new MessageTypeMapperImpl(); @InjectMocks private ReportMessageTranslatorImpl messageTranslator; @Test void testGenerateCC029CTypeMessageFromOriginalMessage() { Message originalMessage = Message.builder() .id("123") .messageType("CC015C") .payload("<xml>...</xml>") .build(); Message resultMessage = messageTranslator.generateCC029CTypeMessageFromOriginalMessage(originalMessage); assertNotNull(resultMessage); assertEquals("CC029C", resultMessage.getMessageType()); } @Test void testGenerateCC029CTypeMessageFromOriginalMessageWhenAlreadyCC029C() { // Test the case where input type is already CC029C Message originalMessage = Message.builder() .id("123") .messageType("CC029C") .payload("<xml>...</xml>") .build(); Message resultMessage = messageTranslator.generateCC029CTypeMessageFromOriginalMessage(originalMessage); assertNotNull(resultMessage); assertEquals(originalMessage, resultMessage); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofdeparture.service; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CC191CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.officeofdeparture.domain.DomainBase; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.domain.MovementAttribute; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowVariablesEnum; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBException; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.MovementAttributesEnum; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class InitializationServiceImpl implements InitializationService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String GET_AES_NCTS_COMMUNICATION_ENABLED_RS = "getAESCommunicationEnabledRS"; public static final String GET_SUBMITTED_ENABLED_RS = "getSubmittedEnabledRS"; private static final String CONTROL_DECISION_NOTIFICATION_ENABLED_RS = "getControlDecisionNotificationEnabledRS"; private static final String SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS = "getSendControlDecisionNotificationAutomaticallyEnabledRS"; private static final String DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS = "getDependOnRiskResponseForNotifyingDeclarantEnabledRS"; private static final String VALUE_LITERAL = "value"; private final ErmisLogger log; private final ProcessingStatusService processingStatusService; private final GenerateMessageService generateMessageService; private final DossierDataService dossierDataService; private final BpmnEngine bpmnEngine; private final ErmisConfigurationService ermisConfigurationService; private final TransitAfterAESService transitAfterAESService; @Override public void registerMessage(String movementId) throws JAXBException { processingStatusService.saveProcessingStatus(movementId, ProcessingStatusTypeEnum.OODEP_SUBMITTED.getItemCode()); generateMessageService.generateIE928(movementId); } @Override public void acceptMessage(String movementId, String mrn, boolean isTransitAfterAES) throws JAXBException { processingStatusService.saveProcessingStatus(movementId, ProcessingStatusTypeEnum.OODEP_ACCEPTED.getItemCode()); generateMessageService.generateIE028(movementId, mrn); } @Override public void rejectMessage(String movementId, String messageId, boolean fetchNonRejectedMessages, boolean negativeIE191, boolean isManuallyRejected, boolean gprTimerExpiration) throws JAXBException { processingStatusService.saveProcessingStatus(movementId, ProcessingStatusTypeEnum.OODEP_REJECTED.getItemCode()); /* Generate IE056 based on IE015 */ generateMessageService.generateIE056(movementId, messageId, CC015CType.class, fetchNonRejectedMessages, negativeIE191, isManuallyRejected, false); } @Override public boolean isSubmittedStateEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(GET_SUBMITTED_ENABLED_RS); String isSubmittedEnabled = configuration.getEvaluationParams().get("submittedEnabled"); return Boolean.parseBoolean(isSubmittedEnabled); } @Override public void handleIE191Message(String movementId, String messageId) { Message message = dossierDataService.getMessageById(messageId); List<MessageOverview> messageOverview = dossierDataService.getMessagesOverview(movementId, MessageTypes.CC_013_C.value()); String processBusinessKey = null; if (!messageOverview.isEmpty()) { Movement movement = dossierDataService.getMovementById(movementId); messageOverview.sort(Comparator.comparing(DomainBase::getCreatedDateTime)); if (movement == null) { throw new NotFoundException("No movement found for movement id".concat(movementId)); } processBusinessKey = movement.getMrn().concat("-").concat(messageOverview.get(messageOverview.size() - 1).getId()); } if (message != null) { CC191CType cc191cMessage; try { cc191cMessage = XmlConverter.buildMessageFromXML(message.getPayload(), CC191CType.class); Boolean isIE191MessagePositive = "1".equals(cc191cMessage.getAESResults().getGlobalValidationResponse()); // IE191 message relates to AES Communication Purpose, this deals with 2 (= Allocation of declaration MRNs...) after (implicit) Initial cross-check of MRNs Boolean isAesCommPurposeAlloc = cc191cMessage.getAESResults().getAESCommunicationPurpose() != null && "2".equals( cc191cMessage.getAESResults().getAESCommunicationPurpose()); final CorrelateBpmnMessageCommand correlateBpmnMessageCommand = createBpmnMessageCommandForIe191PurposeAndResult(movementId, isIE191MessagePositive, isAesCommPurposeAlloc, processBusinessKey); bpmnEngine.correlateMessage(correlateBpmnMessageCommand); } catch (JAXBException e) { log.error("Processing FAILED for handleIE191Message of Message {} and Movement: {}", messageId, movementId); } } } @Override public boolean isControlDecisionNotificationEnabled() { return isControlDecisionNotificationSwitchEnabled(); } @Override public boolean shouldSendControlDecisionNotificationAutomatically() { return isSendControlDecisionNotificationAutomaticallySwitchEnabled(); } @Override public boolean shouldSendNotificationToDeclarant(String movementId) { if (isDependOnRiskForNotifyingDeclarantSwitchEnabled()) { return shouldNotifyDeclarant(movementId); } else { // If switch is off, then IE060 should always be sent. return true; } } @Override public MovementAttribute saveMovementAttribute(String movementId) { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(GET_AES_NCTS_COMMUNICATION_ENABLED_RS); MovementAttribute movementAttribute = null; if (configuration != null) { movementAttribute = MovementAttribute.builder() .movementId(movementId) .attrKey(MovementAttributesEnum.AES_COMMUNICATION_ENABLED.getValue()) .attrValue(configuration.getEvaluationParams().get(MovementAttributesEnum.AES_COMMUNICATION_ENABLED.getValue())) .build(); dossierDataService.saveMovementAttribute(movementAttribute); } return movementAttribute; } @Override public boolean isDeclarationManuallySubmitted(String messageId) { Message cc015cMessage = dossierDataService.getMessageById(messageId); return cc015cMessage.isManualInserted(); } private CorrelateBpmnMessageCommand createBpmnMessageCommandForIe191PurposeAndResult(String movementId, Boolean isPositive, Boolean isAlloc, String processBusinessKey) { Map<String, Object> processVariables = new HashMap<>(); processVariables.put((Boolean.TRUE.equals(isAlloc) ? BpmnFlowVariablesEnum.IS_IE191_MESSAGE_POSITIVE_COMM_PURPOSE_ALLOC.getTypeValue() : BpmnFlowVariablesEnum.IS_IE191_MESSAGE_POSITIVE.getTypeValue()), isPositive); return (CorrelateBpmnMessageCommand .builder() .businessKey(processBusinessKey != null ? processBusinessKey : movementId) .messageName(Boolean.TRUE.equals(isAlloc) ? BpmnFlowMessagesEnum.IE191_MESSAGE_RECEIVED_COMM_PURPOSE_ALLOC.getTypeValue() : BpmnFlowMessagesEnum.IE191_MESSAGE_RECEIVED.getTypeValue()) .values(processVariables) .build() ); } /** * Method holding switch logic to enable/disable Control Decision Notification (IE060). * * @return TRUE/FALSE based on found configuration template. */ private boolean isControlDecisionNotificationSwitchEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(CONTROL_DECISION_NOTIFICATION_ENABLED_RS); return Boolean.parseBoolean(configuration.getEvaluationParams().get(VALUE_LITERAL)); } /** * Method holding switch logic to enable/disable sending Control Decision Notification automatically (IE060). * * @return TRUE/FALSE based on found configuration template. */ private boolean isSendControlDecisionNotificationAutomaticallySwitchEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS); return Boolean.parseBoolean(configuration.getEvaluationParams().get(VALUE_LITERAL)); } /** * Method holding switch logic to enable/disable notification suppression. * * @return TRUE/FALSE based on found configuration template. */ private boolean isDependOnRiskForNotifyingDeclarantSwitchEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS); return Boolean.parseBoolean(configuration.getEvaluationParams().get(VALUE_LITERAL)); } /** * Method holding decision logic to notify Declarant (IE060) * <br/> based on latest response data from Risk Assessment. * * @param movementId ID of movement to retrieve risk assessment response of. * @return TRUE/FALSE based on data found within risk assessment response. */ private boolean shouldNotifyDeclarant(String movementId) { List<MessageOverview> riskAssessmentResponseMessageOverviewList = dossierDataService.getMessagesOverview(movementId, RiskAssessmentResponseEvent.class.getSimpleName()); Comparator<MessageOverview> messageOverviewComparator = Comparator.comparing(DomainBase::getCreatedDateTime); if (!riskAssessmentResponseMessageOverviewList.isEmpty()) { // Sort and reverse riskAssessmentResponseMessageOverviewList so the latest is on index[0]: riskAssessmentResponseMessageOverviewList.sort(messageOverviewComparator); Collections.reverse(riskAssessmentResponseMessageOverviewList); try { Message riskAssessmentResponseMessage = dossierDataService.getMessageById(riskAssessmentResponseMessageOverviewList.get(0).getId()); RiskAssessmentResponseEvent riskAssessmentResponseEvent = JSON_CONVERTER.convertStringToObject(riskAssessmentResponseMessage.getPayload(), RiskAssessmentResponseEvent.class); // If at least one (1) control instruction has involvesNotifyingDeclarant == FALSE, then suppress notification: return riskAssessmentResponseEvent.getRiskAssessmentResults() .stream() .takeWhile(riskAssessmentResult -> riskAssessmentResult.getControlInstructions() .stream() .anyMatch(controlInstruction -> Boolean.FALSE.equals(controlInstruction.isInvolvesNotifyingDeclarant()))) .findAny() .isEmpty(); } catch (Exception e) { // Default TRUE if an Exception was thrown for provided movement ID (non-interrupting exception handling): log.warn("Failed to retrieve Risk Assessment Response data for movementId: " + movementId + ". Defaulting to TRUE."); return true; } } else { // Default TRUE if no Risk Assessment Response Event Messages were found for provided movement ID: log.warn("shouldNotifyDeclarant(): No Risk Assessment Response Event Messages found. Defaulting to TRUE."); return true; } } }
package com.intrasoft.ermis.trs.officeofdeparture.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.ControlInstruction; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResult; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofdeparture.service.DossierDataService; import com.intrasoft.ermis.transit.officeofdeparture.service.GenerateMessageService; import com.intrasoft.ermis.transit.officeofdeparture.service.InitializationServiceImpl; import com.intrasoft.ermis.transit.officeofdeparture.service.ProcessingStatusService; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class InitializationServiceUT { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String CONTROL_DECISION_NOTIFICATION_ENABLED_RS = "getControlDecisionNotificationEnabledRS"; private static final String SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS = "getSendControlDecisionNotificationAutomaticallyEnabledRS"; private static final String DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS = "getDependOnRiskResponseForNotifyingDeclarantEnabledRS"; private static final String MOVEMENT_ID = UUID.randomUUID().toString(); private static final String LATEST_MESSAGE_ID = "MESSAGE_ID_0"; private static final int NUMBER_OF_MESSAGE_OVERVIEWS = 3; private static final int NUMBER_OF_RISK_ASSESSMENT_RESULTS = 2; private static final int NUMBER_OF_CONTROL_INSTRUCTIONS = 4; @Mock private ProcessingStatusService processingStatusService; @Mock private GenerateMessageService generateMessageService; @Mock private BpmnEngine bpmnEngine; @Mock private DossierDataService dossierDataService; @Mock private ErmisConfigurationService ermisConfigurationService; @InjectMocks private InitializationServiceImpl initializationService; @ParameterizedTest @DisplayName("Test - Is Control Decision Notification Enabled") @ValueSource(strings = {"true", "false", "invalidParameter"}) void testIsControlDecisionNotificationEnabled(String valueParameter) { // Stubs: when(ermisConfigurationService.getConfigurationByTemplateName(CONTROL_DECISION_NOTIFICATION_ENABLED_RS)) .thenReturn(buildConfiguration(CONTROL_DECISION_NOTIFICATION_ENABLED_RS, valueParameter)); // Call tested service method: boolean returnedValue = initializationService.isControlDecisionNotificationEnabled(); // Verifications & Assertions: verify(ermisConfigurationService, times(1)).getConfigurationByTemplateName(CONTROL_DECISION_NOTIFICATION_ENABLED_RS); if ("invalidParameter".equals(valueParameter)) { assertFalse(returnedValue); } else { assertEquals(Boolean.parseBoolean(valueParameter), returnedValue); } } @ParameterizedTest @DisplayName("Test - Should Send Control Decision Notification Automatically") @ValueSource(strings = {"true", "false", "invalidParameter"}) void testShouldSendControlDecisionNotificationAutomatically(String valueParameter) { // Stubs: when(ermisConfigurationService.getConfigurationByTemplateName(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS)) .thenReturn(buildConfiguration(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS, valueParameter)); // Call tested service method: boolean returnedValue = initializationService.shouldSendControlDecisionNotificationAutomatically(); // Verifications & Assertions: verify(ermisConfigurationService, times(1)) .getConfigurationByTemplateName(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS); if ("invalidParameter".equals(valueParameter)) { assertFalse(returnedValue); } else { assertEquals(Boolean.parseBoolean(valueParameter), returnedValue); } } @ParameterizedTest @DisplayName("Test - Should Send Notification To Declarant") @CsvSource({"true,true", "true,false", "false,true", "false,false",}) void testShouldSendNotificationToDeclarant(boolean switchEnabled, boolean suppressNotification) { // Stubs: when(ermisConfigurationService.getConfigurationByTemplateName(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS)) .thenReturn(buildConfiguration(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS, String.valueOf(switchEnabled))); if (switchEnabled) { when(dossierDataService.getMessagesOverview(MOVEMENT_ID, RiskAssessmentResponseEvent.class.getSimpleName())) .thenReturn(buildMessageOverviewList()); when(dossierDataService.getMessageById(LATEST_MESSAGE_ID)) .thenReturn(buildMessage(suppressNotification)); } // Call tested service method: boolean returnedValue = initializationService.shouldSendNotificationToDeclarant(MOVEMENT_ID); // Verifications & Assertions: verify(ermisConfigurationService, times(1)).getConfigurationByTemplateName(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS); if (switchEnabled) { // If switch is enabled, further REST calls should be made: verify(dossierDataService, times(1)).getMessagesOverview(MOVEMENT_ID, RiskAssessmentResponseEvent.class.getSimpleName()); verify(dossierDataService, times(1)).getMessageById(LATEST_MESSAGE_ID); // If at least one involvesNotifyingDeclarant within control instructions is found FALSE, suppress notification: if (suppressNotification) { assertFalse(returnedValue); } else { assertTrue(returnedValue); } } else { // If switch is disabled, no further REST calls should be made and should notify declarant: verify(dossierDataService, times(0)).getMessagesOverview(MOVEMENT_ID, RiskAssessmentResponseEvent.class.getSimpleName()); verify(dossierDataService, times(0)).getMessageById(LATEST_MESSAGE_ID); assertTrue(returnedValue); } } private Configuration buildConfiguration(String ruleTemplate, String value) { return new Configuration( ruleTemplate, "ruleCode", new HashMap<>(), Map.of("value", value), "errorCode", LocalDateTime.now(ZoneOffset.UTC), LocalDateTime.now(ZoneOffset.UTC).minusDays(60), LocalDateTime.now(ZoneOffset.UTC).plusDays(60)); } private List<MessageOverview> buildMessageOverviewList() { List<MessageOverview> messageOverviewList = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_MESSAGE_OVERVIEWS; i++) { MessageOverview messageOverview = MessageOverview.builder() .id("MESSAGE_ID_" + i) .messageType(RiskAssessmentResponseEvent.class.getSimpleName()) .createdDateTime(LocalDateTime.now(ZoneOffset.UTC).minusDays(i)) .build(); messageOverviewList.add(messageOverview); } return messageOverviewList; } private Message buildMessage(boolean suppressNotification) { Message message = new Message(); RiskAssessmentResponseEvent riskAssessmentResponseEvent = new RiskAssessmentResponseEvent(); riskAssessmentResponseEvent.setRiskAssessmentResults(new ArrayList<>()); riskAssessmentResponseEvent.getRiskAssessmentResults().addAll(buildRiskAssessmentResultList(suppressNotification)); message.setMessageIdentification(LATEST_MESSAGE_ID); message.setMessageType(RiskAssessmentResponseEvent.class.getSimpleName()); message.setPayload(JSON_CONVERTER.convertToJsonString(riskAssessmentResponseEvent)); return message; } private List<RiskAssessmentResult> buildRiskAssessmentResultList(boolean suppressNotification) { List<RiskAssessmentResult> riskAssessmentResultList = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_RISK_ASSESSMENT_RESULTS; i++) { RiskAssessmentResult riskAssessmentResult = new RiskAssessmentResult(); for (int j = 0; j < NUMBER_OF_CONTROL_INSTRUCTIONS; j++) { ControlInstruction controlInstruction = new ControlInstruction(); controlInstruction.setInvolvesNotifyingDeclarant(true); riskAssessmentResult.getControlInstructions().add(controlInstruction); } riskAssessmentResultList.add(riskAssessmentResult); } if (suppressNotification) { riskAssessmentResultList.get(0).getControlInstructions().get(0).setInvolvesNotifyingDeclarant(false); } return riskAssessmentResultList; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.management.core.service; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC013CType; import com.intrasoft.ermis.ddntav5152.messages.CC014CType; import com.intrasoft.ermis.ddntav5152.messages.CC044CType; import com.intrasoft.ermis.ddntav5152.messages.CD018CType; import com.intrasoft.ermis.ddntav5152.messages.CD150CType; import com.intrasoft.ermis.ddntav5152.messages.CD151CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.EnquiryStatusEnum; import com.intrasoft.ermis.transit.common.enums.InvalidationExpectedStatusesEnum; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.contracts.core.enums.YesNoEnum; import com.intrasoft.ermis.transit.contracts.validation.enums.ErrorCode; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.util.ValidationHelper; import com.intrasoft.ermis.transit.management.core.util.ViolationUtils; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.MessageOverview; import com.intrasoft.ermis.transit.management.domain.Movement; import com.intrasoft.ermis.transit.management.domain.Violation; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; /** * <pre> * Any Message Validation "Custom logic" can be placed within this class * Mainly logic that needs το Validate any Incoming DDNTA message type against existing relevant data in the Dossier Database (e.g. for the same MRN) * Not intended by any means to call the Validation MicroService via the {@link com.intrasoft.ermis.transit.management.core.port.outbound.ValidationService} */ @Service @RequiredArgsConstructor public class DDNTAMessageCustomValidationServiceImpl { public static final String MRN_PATH = "/%s/TransitOperation/MRN"; public static final String MESSAGE_RECIPIENT_PATH = "/messageRecipient"; public static final String MESSAGE_GROSS_MASS_PATH = "/Consignment/HouseConsignment/grossMass"; private static final String XSD_ERROR_REASON = "XSD"; private static final String INVALID_GROSS_MASS_VALUE = "The value '0' of element 'grossMass' is not valid"; private final ErmisLogger log; private final GetCountryCodeService getCountryCodeService; private final TransitionPeriodService transitionPeriodService; @FunctionalInterface private interface DDNTAMessageCustomValidator { List<Violation> validateMessageType(List<Movement> movements, Message message) throws JAXBException; } private static final Set<MessageTypes> NOT_ALLOWED_IN_INVALIDATION_AFTER_RELEASE = Set.of( MessageTypes.CD_006_C, MessageTypes.CD_118_C, MessageTypes.CD_168_C, MessageTypes.CD_180_C); private final DossierDataService dossierDataService; private final ConfigurationSwitchService configurationSwitchService; @SneakyThrows protected List<Violation> performCustomValidationPerMessageType(List<Movement> movements, Message message) { MessageTypes messageType = Objects.requireNonNull(MessageTypes.fromValue(message.getMessageType()), "Invalid/Unknown Message Type: [" + message.getMessageType() + "]"); List<Violation> violationsList = getDDNTAMessageCustomValidator(messageType).validateMessageType(movements, message); if (!violationsList.isEmpty()) { log.error( "performCustomValidationPerMessageType() : CUSTOM VALIDATION FAILED for Message Type [{}] with MRN: [{}]", messageType.value(), message.getMrn()); } return violationsList; } private DDNTAMessageCustomValidator getDDNTAMessageCustomValidator(MessageTypes messageType) { switch (messageType) { case CD_181_C: return this::validateIE181; case CD_010_C: return this::validateIE010; case CD_018_C: return this::validateIE018; case CD_150_C: return this::validateIE150; case CD_151_C: return this::validateIE151; case CD_152_C: return this::validateIE152; case CC_013_C: return this::validateIE013; case CC_014_C: return this::validateIE014; case CC_141_C: return this::validateIE141; case CD_143_C: return this::validateIE143; case CC_007_C: case CC_015_C: case CC_170_C: return this::validateMessageDestination; case CC_044_C: return this::validateIE044; default: // For rest of message types that do not need Custom Validation, return a dummy implementation return (movements, message) -> List.of(); } } /** * <pre> * Custom Validation ( for NL) only for {@link com.intrasoft.ermis.ddntav5152.messages.CC170CType} type and only if the MRN Communication Rule is enabled * In that case and if declaration is pre-lodged the received CC170C type should have a required [TransitOperation/MRN] element with a non-empty MRN value * It has been implemented as a separate public method because it is being called initially when the IE170 is received and before any attempt to associate * the IE170 message to an existing movement */ public List<Violation> validateIE170MrnIfMrnCommunicationIsEnabled(Message message) { List<Violation> violations = new ArrayList<>(); if (MessageTypes.CC_170_C.value().equals(message.getMessageType())) { if (configurationSwitchService.isMRNCommunicationInPelodgedEnabled()) { if (StringUtils.isBlank(message.getMrn())) { violations.add( ViolationUtils.createViolation( String.format(MRN_PATH, message.getMessageType()), MessageUtil.ERROR_REASON_FOR_906, "", ErrorCode.MISSING.getCode()) ); } } else { if (StringUtils.isNotBlank(message.getMrn())) { violations.add( ViolationUtils.createViolation( String.format(MRN_PATH, message.getMessageType()), MessageUtil.ERROR_REASON_FOR_906, message.getMrn(), ErrorCode.NOT_SUPPORTED_HERE.getCode()) ); } } } return violations; } /** * <pre> * ********************************************************************************************************************************** * Validator Methods per Message Type. These are all Implementations of the {@link DDNTAMessageCustomValidator} functional interface * ********************************************************************************************************************************** */ private List<Violation> validateIE010(List<Movement> movements, Message message) { List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverviewByMrnAndMessageTypes(message.getMrn(), List.of( MessageTypes.CD_180_C, MessageTypes.CD_181_C, MessageTypes.CD_006_C, MessageTypes.CD_118_C, MessageTypes.CD_168_C)); if (!messageOverviewList.isEmpty()) { log.error( "validateIE010() FAILED validation for MRN: [{}] and Message Type: [{}]. Found {} message(s) of type IE180/IE181 for the same MRN", message.getMrn(), MessageTypes.fromValue(message.getMessageType()).value(), messageOverviewList.size()); messageOverviewList.forEach( messageOverview -> log.warn("\t-> Message type: [{}], direction: [{}], messageId: [{}], id: [{}]", messageOverview.getMessageType(), messageOverview.getDirection(), messageOverview.getMessageIdentification(), messageOverview.getId())); return List.of(ViolationUtils.createOutOfOrderViolation(message.getMessageType())); } return List.of(); } private List<Violation> validateIE018(List<Movement> movements, Message message) throws JAXBException { List<Violation> violations = new ArrayList<>(); CD018CType messagePayload = XmlConverter.buildMessageFromXML(message.getPayload(), CD018CType.class); if (transitionPeriodService.isNowNCTSTransitionPeriod() && isGrossMassZeroInCD018C(messagePayload) && message.isManualInserted()) { log.error("validate IE018() : Invalid value '0' in gross mass"); violations.add(ViolationUtils.createViolation(message.getMessageType().concat(MESSAGE_GROSS_MASS_PATH), INVALID_GROSS_MASS_VALUE, XSD_ERROR_REASON, ErrorCode.INVALID_XML_FORMAT.getCode())); } return violations; } private boolean isGrossMassZeroInCD018C(CD018CType message) { if (message == null || message.getConsignment() == null || message.getConsignment().getHouseConsignment() == null) { return false; } return message.getConsignment() .getHouseConsignment() .stream() .anyMatch(cd018HouseConsignment -> cd018HouseConsignment.getGrossMass() != null && BigDecimal.ZERO.compareTo(cd018HouseConsignment.getGrossMass()) == 0); } private List<Violation> validateIE152(List<Movement> movements, Message message) { for (Movement movement : movements) { if (!movement.getOfficeRoleType().equals(OfficeRoleTypesEnum.DEPARTURE.getValue()) && cd151PositiveExists(movement, message)) { return List.of(ViolationUtils.createOutOfOrderViolation(message.getMessageType())); } } return List.of(); } //R0520 rule implementation private List<Violation> validateIE013(List<Movement> movements, Message message) { List<Violation> violations = validateMessageDestination(movements, message); CC013CType cc013CTypeMessage = dossierDataService.getDDNTAMessageById(message.getId(), CC013CType.class); for (Movement movement : movements) { if (OfficeRoleTypesEnum.DEPARTURE.getValue().equals(movement.getOfficeRoleType()) && isAmendmentTypeFlagInvalid(movement, cc013CTypeMessage)) { violations.add(ViolationUtils.createViolation(ValidationHelper.AMENDMENT_TYPE_FLAG_POINTER, ValidationHelper.R0520_REASON, cc013CTypeMessage.getTransitOperation().getAmendmentTypeFlag(), ValidationHelper.SEMANTIC_ERROR_CODE)); return violations; } } return violations; } private List<Violation> validateIE014(List<Movement> movements, Message message) { List<Violation> violations = validateMessageDestination(movements, message); for (Movement movement : movements) { /* If movement is in 'After Release' state... */ if (OfficeRoleTypesEnum.DEPARTURE.getValue().equals(movement.getOfficeRoleType()) && InvalidationExpectedStatusesEnum.OODEP_AFTER_RELEASE.getOfficeRoleTypeStatuses() .getStatuses() .contains(movement.getProcessingStatus())) { violations.addAll(validateIE014AInAfterReleaseState(message, movement)); return violations; } } // G0101 implementation: violations.addAll(applyG0101OnIE014(message)); return violations; } private List<Violation> validateIE014AInAfterReleaseState(Message message, Movement movement) { if (message.isManualInserted()) { List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverviewByMrnAndMessageTypes(movement.getMrn(), NOT_ALLOWED_IN_INVALIDATION_AFTER_RELEASE); if (!messageOverviewList.isEmpty()) { return List.of(ViolationUtils.createViolation("/" + message.getMessageType(), "N/A", null, MessageUtil.ERROR_CODE_FOR_906)); } return List.of(); } else { if (configurationSwitchService.isElectronicIE014EnabledInReleaseState()) { List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverviewByMrnAndMessageTypes(movement.getMrn(), NOT_ALLOWED_IN_INVALIDATION_AFTER_RELEASE); if (!messageOverviewList.isEmpty() || ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE.getItemCode() .equals(movement.getProcessingStatus())) { return List.of(ViolationUtils.createViolation("/" + message.getMessageType(), "N/A", null, MessageUtil.ERROR_CODE_FOR_906)); } return List.of(); } else { return List.of(ViolationUtils.createViolation("/" + message.getMessageType(), "N/A", null, MessageUtil.ERROR_CODE_FOR_906)); } } } /** * Technical Description: <br/> N/A <br/> <br/> Functional Description: <br/> The value of the Data Item 'Invalidation.initiatedByCustoms' is <br/> ‘0’ * ('No') when the request to invalidate is initiated by the trader; <br/> The value of the Data Item 'Invalidation.initiatedByCustoms' is <br/> ‘1’ ('Yes') * when the request to invalidate is initiated by the customs. * * @param message Message holding the CC014C XML in its payload. * @return List of Violation if G0101 is violated, else empty List. */ private List<Violation> applyG0101OnIE014(Message message) { try { CC014CType cc014cTypeMessage = XmlConverter.buildMessageFromXML(message.getPayload(), CC014CType.class); String errorPointer = "/".concat(message.getMessageType()).concat("/Invalidation/initiatedByCustoms"); String errorReason = "G0101"; Predicate<CC014CType> isInitiatedByCustoms = inputMessage -> "1".equals(inputMessage.getInvalidation().getInitiatedByCustoms()); Predicate<CC014CType> isNotInitiatedByCustoms = inputMessage -> "0".equals(inputMessage.getInvalidation().getInitiatedByCustoms()); if ((message.isManualInserted() && isNotInitiatedByCustoms.test(cc014cTypeMessage)) || (!message.isManualInserted() && isInitiatedByCustoms.test(cc014cTypeMessage))) { return List.of(ViolationUtils.createViolation(errorPointer, errorReason, cc014cTypeMessage.getInvalidation().getInitiatedByCustoms(), ValidationHelper.GUIDELINE_ERROR_CODE)); } else { return List.of(); } } catch (JAXBException e) { log.warn("applyG0101OnIE014(): Failed to convert XML payload of Message with ID: " .concat(message.getId()) .concat(". Will skip G0101.") ); return List.of(); } } /** * block the National IE150 messages between the same NA */ @SneakyThrows private List<Violation> validateIE150(List<Movement> movements, Message message) { CD150CType cd150CType = XmlConverter.buildMessageFromXML(message.getPayload(), CD150CType.class); String officeRequesting = cd150CType.getCustomsOfficeOfRecoveryRequesting().getReferenceNumber(); String officeRequested = cd150CType.getCustomsOfficeOfRecoveryRequested().getReferenceNumber(); if (officeRequested.startsWith(officeRequesting.substring(0, 2))) { return List.of(ViolationUtils.createOutOfOrderViolation(message.getMessageType())); } return List.of(); } @SneakyThrows private List<Violation> validateIE151(List<Movement> movements, Message message) { final List<MessageOverview> ie150MessageOverviewList = dossierDataService.getMessagesOverviewByMrnAndMessageTypes(message.getMrn(), List.of(MessageTypes.CD_150_C)).stream() .filter(messageOverview -> Objects.equals(messageOverview.getDirection(), DirectionEnum.SENT.getDirection())) .sorted(Comparator.comparing(MessageOverview::getCreatedDateTime).reversed()) .collect(Collectors.toList()); // If more than one found log if (ie150MessageOverviewList.size() > 1) { log.warn( "validateIE151() : For IE151-RECEIVED with MRN: [{}] found more than one IE150-SENT messages ({}). Will peek the last one with id: [{}] and compare the Office Reference Numbers...#$%^&*@! Ids found: {}", message.getMrn(), ie150MessageOverviewList.size(), ie150MessageOverviewList.get(0).getId(), ie150MessageOverviewList.stream().map(MessageOverview::getId).collect(Collectors.toList())); } if (ie150MessageOverviewList.isEmpty()) { // TODO: Check for IE143 with code = 4. Do not raise a Violation Error till final implemantation! log.info( "validateIE151() : For IE151-RECEIVED with MRN: [{}] found NONE IE150-SENT messages. Will probably look for IE143 with Code 4 which is NOT yet implemented. TODO!", message.getMrn()); } else { CD150CType cd150CTypeSent = dossierDataService.getDDNTAMessageById(ie150MessageOverviewList.get(0).getId(), CD150CType.class); CD151CType cd151CTypeReceived = XmlConverter.buildMessageFromXML(message.getPayload(), CD151CType.class); if (!validateReceivedIE151AgainstSentIE150(cd151CTypeReceived, cd150CTypeSent)) { return List.of(ViolationUtils.createOutOfOrderViolation(message.getMessageType())); } } return List.of(); } /** * PSD-2577 Performs customs validation for IE181 message. If movement exists in office of destination and state not equals to AAR_CREATED, then CD906C * message should be sent. */ @SneakyThrows private List<Violation> validateIE181(List<Movement> movements, Message message) { return movements.stream().filter(movement -> OfficeRoleTypesEnum.DESTINATION.getValue() .equals(movement.getOfficeRoleType()) && !movement .getProcessingStatus() .equals(ProcessingStatusTypeEnum.OODEST_AAR_CREATED.getItemCode()) ).map(movement -> ViolationUtils.createOutOfOrderViolation(message.getMessageType())).collect(Collectors.toList()); } private List<Violation> validateIE141(List<Movement> movements, Message message) { List<Violation> violations = validateMessageDestination(movements, message); violations.addAll(validateEnquiryState(message.getMrn(), message.getMessageType())); return violations; } private List<Violation> validateIE143(List<Movement> movements, Message message) { return validateEnquiryState(message.getMrn(), message.getMessageType()); } private List<Violation> validateIE044(List<Movement> movements, Message message) throws JAXBException { List<Violation> violations = new ArrayList<>(); CC044CType messagePayload = XmlConverter.buildMessageFromXML(message.getPayload(), CC044CType.class); if (transitionPeriodService.isNowNCTSTransitionPeriod() && isGrossMassZeroInCC044C(messagePayload)) { log.error("validate IE044() : Invalid value '0' in gross mass"); violations.add(ViolationUtils.createViolation(message.getMessageType().concat(MESSAGE_GROSS_MASS_PATH), INVALID_GROSS_MASS_VALUE, XSD_ERROR_REASON, ErrorCode.INVALID_XML_FORMAT.getCode())); } return violations; } private boolean isGrossMassZeroInCC044C(CC044CType message) { if (message == null || message.getConsignment() == null || message.getConsignment().getHouseConsignment() == null) { return false; } return message.getConsignment() .getHouseConsignment() .stream() .anyMatch(cc044HouseConsignment -> cc044HouseConsignment.getGrossMass() != null && BigDecimal.ZERO.compareTo(cc044HouseConsignment.getGrossMass()) == 0); } /** * For : CC015C, CC013C, CC014C, CC170C, CC141C, CC007C, CC044C Message Recipient should be: NTA.{Operating Country} i.e. NTA.DK (or any one of the * accommodating Countries. e.g. IS for Operating Country NO) */ private List<Violation> validateMessageDestination(List<Movement> movements, Message message) { List<Violation> violations = new ArrayList<>(); String destinationCountryCode = MessageUtil.getCountryCodeFromMessageRecipient(message.getDestination()); String operatingCountryCode = getCountryCodeService.getCountryCode(); if (!operatingCountryCode.equals(destinationCountryCode) && (message.getMessageType().equals(MessageTypes.CC_007_C.value()) && !getCountryCodeService.getAccommodatingCountryCodes().contains(destinationCountryCode)) ) { log.error("validateMessageDestination() : Invalid destination country code: {}. Opc: {} , Acc: {} ", destinationCountryCode, operatingCountryCode, getCountryCodeService.getAccommodatingCountryCodes()); violations.add(ViolationUtils.createViolation("/" + message.getMessageType().concat(MESSAGE_RECIPIENT_PATH), MessageUtil.ERROR_REASON_FOR_906, message.getDestination(), ErrorCode.NOT_SUPPORTED_CODE_VALUE.getCode())); } return violations; } // ************************************* Helper Methods *********************************************************************** private boolean validateReceivedIE151AgainstSentIE150(CD151CType cd151CTypeReceived, CD150CType cd150CTypeSent) { AtomicInteger errorCount = new AtomicInteger(); String ie151OfficeOfRecoveryRequestingCountry = MessageUtil.extractOfficeCountryCode(cd151CTypeReceived.getCustomsOfficeOfRecoveryRequesting().getReferenceNumber()); String ie150OfficeOfRecoveryRequestingCountry = MessageUtil.extractOfficeCountryCode(cd150CTypeSent.getCustomsOfficeOfRecoveryRequesting().getReferenceNumber()); String ie151OfficeOfRecoveryRequestedCountry = MessageUtil.extractOfficeCountryCode(cd151CTypeReceived.getCustomsOfficeOfRecoveryRequested().getReferenceNumber()); String ie150OfficeOfRecoveryRequestedCountry = MessageUtil.extractOfficeCountryCode(cd150CTypeSent.getCustomsOfficeOfRecoveryRequested().getReferenceNumber()); if (!Objects.equals(ie151OfficeOfRecoveryRequestingCountry, ie150OfficeOfRecoveryRequestingCountry)) { errorCount.incrementAndGet(); log.error( "validateReceivedIE151AgainstSentIE150() : Country Mismatch [{}] <> [{}] between : IE151/CustomsOfficeOfRecoveryRequesting: [{}] and IE150/CustomsOfficeOfRecoveryRequesting: [{}]", ie151OfficeOfRecoveryRequestingCountry, ie150OfficeOfRecoveryRequestingCountry, cd151CTypeReceived.getCustomsOfficeOfRecoveryRequesting().getReferenceNumber(), cd150CTypeSent.getCustomsOfficeOfRecoveryRequesting().getReferenceNumber()); } if (!Objects.equals(ie151OfficeOfRecoveryRequestedCountry, ie150OfficeOfRecoveryRequestedCountry)) { errorCount.incrementAndGet(); log.error( "validateReceivedIE151AgainstSentIE150() : Country Mismatch [{}] <> [{}] between : IE151/CustomsOfficeOfRecoveryRequested: [{}] and IE150/CustomsOfficeOfRecoveryRequested: [{}]", ie151OfficeOfRecoveryRequestedCountry, ie150OfficeOfRecoveryRequestedCountry, cd151CTypeReceived.getCustomsOfficeOfRecoveryRequested().getReferenceNumber(), cd150CTypeSent.getCustomsOfficeOfRecoveryRequested().getReferenceNumber()); } return errorCount.get() == 0; } private boolean cd151PositiveExists(Movement movement, Message message) { List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverview(MessageTypes.CD_151_C.value(), movement.getId(), false); boolean cd151PositiveExists = false; if (!messageOverviewList.isEmpty()) { for (MessageOverview messageOverview : messageOverviewList) { CD151CType cd151CTypeMessage = dossierDataService.getDDNTAMessageById(messageOverview.getId(), CD151CType.class); if (YesNoEnum.YES.getValue().equals(cd151CTypeMessage.getRecovery().getRecoveryAcceptance())) { log.error( "cd151PositiveExists() FAILED validation for MRN: [{}] and Incoming Message Type: [{}]. Found POSITIVE \"Recovery Acceptance Notification\" (IE151) message for the same MRN. Message will be rejected.", movement.getMrn(), message.getMessageType()); log.error("\t-> IE151 Message found: direction: [{}], messageId: [{}], id: [{}] on movementId: [{}]", messageOverview.getDirection(), messageOverview.getMessageIdentification(), messageOverview.getId(), movement.getId()); cd151PositiveExists = true; break; } } } return cd151PositiveExists; } private boolean isAmendmentTypeFlagInvalid(Movement movement, CC013CType cc013CTypeMessage) { return (ProcessingStatusTypeEnum.OODEP_GUARANTEE_UNDER_AMENDMENT.getItemCode().equals(movement.getProcessingStatus()) && !"1".equals( cc013CTypeMessage.getTransitOperation().getAmendmentTypeFlag())) || ( !ProcessingStatusTypeEnum.OODEP_GUARANTEE_UNDER_AMENDMENT.getItemCode().equals(movement.getProcessingStatus()) && "1".equals( cc013CTypeMessage.getTransitOperation().getAmendmentTypeFlag())); } /** * There can only be one (1) Trader Enquiry (IE140), so only accept the IE141 response if: EnquiryStatus is OPEN, meaning a valid IE141 has not yet been * received, else status would be CLOSED. * * @param mrn * @param messageType * @return */ private List<Violation> validateEnquiryState(String mrn, String messageType) { if (dossierDataService.enquiryExistsByMrnAndStatus(mrn, EnquiryStatusEnum.OPEN.getTypeValue(), MessageTypes.CD_143_C.value().equals(messageType))) { return List.of(); } return List.of(ViolationUtils.createOutOfOrderViolation(messageType)); } }
package com.intrasoft.ermis.transit.management.core.service; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC014CType; import com.intrasoft.ermis.ddntav5152.messages.CC044CType; import com.intrasoft.ermis.ddntav5152.messages.CD018CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.InvalidationExpectedStatusesEnum; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.util.ValidationHelper; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.MessageOverview; import com.intrasoft.ermis.transit.management.domain.Movement; import com.intrasoft.ermis.transit.management.domain.Violation; import com.intrasoft.ermis.transit.shared.testing.util.FileHelpers; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Stream; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @Slf4j @ExtendWith(MockitoExtension.class) public class DDNTAMessageCustomValidationServiceImplUT { @Mock private DossierDataService dossierDataService; @Mock private ConfigurationSwitchService configurationSwitchService; @Mock private ErmisLogger logger; @Mock private GetCountryCodeService getCountryCodeService; @Mock private TransitionPeriodService transitionPeriodService; @InjectMocks DDNTAMessageCustomValidationServiceImpl ddntaMessageCustomValidationService; @ParameterizedTest @MethodSource("namedArguments") @SneakyThrows void test_IE014CustomValidation(boolean isElectronicallySubmittedEnabled, boolean isManuallyInserted, String existingInvalidMessageType, ProcessingStatusTypeEnum processingStatus) { String MRN = "22DKFUECYSBTH9ARK2"; Set<MessageTypes> invalidMessageTypes = Set.of(MessageTypes.CD_006_C, MessageTypes.CD_118_C, MessageTypes.CD_168_C, MessageTypes.CD_180_C); List<MessageOverview> invalidMessageOverviewList = new ArrayList<>(); if(Objects.nonNull(existingInvalidMessageType) && existingInvalidMessageType.matches("CD168C|CD118C|CD006C|CD180C")) { invalidMessageOverviewList.add(MessageOverview.builder().messageType(existingInvalidMessageType).build()); } String cc014cMessage = FileHelpers.xmlToString(MessageTypes.CC_014_C.value() + ".xml"); CC014CType cc014CType = XmlConverter.buildMessageFromXML(cc014cMessage, CC014CType.class); if (isManuallyInserted) { cc014CType.getInvalidation().setInitiatedByCustoms("1"); } cc014cMessage = XmlConverter.marshal(cc014CType, NamespacesEnum.NTA.getValue(), MessageTypes.CC_014_C.value()); Message message = Message.builder() .messageType(MessageTypes.CC_014_C.value()) .destination("NTA.GR") .manualInserted(isManuallyInserted) .payload(cc014cMessage) .build(); List<Movement> movements = new ArrayList<>(); movements.add(Movement.builder() .officeRoleType(OfficeRoleTypesEnum.DEPARTURE.getValue()) .mrn(MRN) .processingStatus(processingStatus.getItemCode()) .build()); List<Violation> violations = new ArrayList<>(); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); if (!isManuallyInserted) { when(configurationSwitchService.isElectronicIE014EnabledInReleaseState()).thenReturn(isElectronicallySubmittedEnabled); } if ((isManuallyInserted || isElectronicallySubmittedEnabled) && !InvalidationExpectedStatusesEnum.OODEP_BEFORE_RELEASE.getOfficeRoleTypeStatuses().getStatuses().contains(processingStatus.getItemCode())) { when(dossierDataService.getMessagesOverviewByMrnAndMessageTypes(MRN, invalidMessageTypes)).thenReturn(invalidMessageOverviewList); } violations = ddntaMessageCustomValidationService.performCustomValidationPerMessageType(movements, message); if((InvalidationExpectedStatusesEnum.OODEP_AFTER_RELEASE.getOfficeRoleTypeStatuses().getStatuses().contains(processingStatus.getItemCode()) && (isElectronicallySubmittedEnabled || isManuallyInserted) && Objects.isNull(existingInvalidMessageType) && !ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE.equals(processingStatus)) || InvalidationExpectedStatusesEnum.OODEP_BEFORE_RELEASE.getOfficeRoleTypeStatuses().getStatuses().contains(processingStatus.getItemCode())) { assertTrue(violations.isEmpty()); } else if(Objects.nonNull(existingInvalidMessageType)) { assertEquals(1, invalidMessageOverviewList.size()); assertEquals(existingInvalidMessageType, invalidMessageOverviewList.get(0).getMessageType()); IE014ViolationAssertions(violations); } else if(!isManuallyInserted && ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE.equals(processingStatus)) { assertTrue(invalidMessageOverviewList.isEmpty()); IE014ViolationAssertions(violations); } else if(!isManuallyInserted && !isElectronicallySubmittedEnabled) { verify(dossierDataService, times(0)).getMessagesOverviewByMrnAndMessageTypes(any(), any()); IE014ViolationAssertions(violations); } } @Test @SneakyThrows void test_IE018CustomValidation() { String cd018cMessage = FileHelpers.xmlToString(MessageTypes.CD_018_C.value() + "-GrossMassZero.xml"); CD018CType cc018CType = XmlConverter.buildMessageFromXML(cd018cMessage, CD018CType.class); cd018cMessage = XmlConverter.marshal(cc018CType, NamespacesEnum.NTA.getValue(), MessageTypes.CD_018_C.value()); Message message = Message.builder() .messageType(MessageTypes.CD_018_C.value()) .destination("NTA.GR") .payload(cd018cMessage) .build(); List<Movement> movements = new ArrayList<>(); List<Violation> violations; message.setManualInserted(true); when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(true); violations = ddntaMessageCustomValidationService.performCustomValidationPerMessageType(movements, message); assertFalse(violations.isEmpty()); } @Test @SneakyThrows void test_IE044CustomValidation() { String cc044cMessage = FileHelpers.xmlToString(MessageTypes.CC_044_C.value() + "-NoGrossMass.xml"); CC044CType cc044CType = XmlConverter.buildMessageFromXML(cc044cMessage, CC044CType.class); cc044cMessage = XmlConverter.marshal(cc044CType, NamespacesEnum.NTA.getValue(), MessageTypes.CC_044_C.value()); Message message = Message.builder() .messageType(MessageTypes.CC_044_C.value()) .destination("NTA.GR") .payload(cc044cMessage) .build(); List<Movement> movements = new ArrayList<>(); List<Violation> violations; when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(true); violations = ddntaMessageCustomValidationService.performCustomValidationPerMessageType(movements, message); assertTrue(violations.isEmpty()); } private void IE014ViolationAssertions(List<Violation> violations) { assertEquals(1, violations.size()); assertEquals("/CC014C", violations.get(0).getFieldName()); assertEquals("N/A", violations.get(0).getReason()); assertNull(violations.get(0).getRejectedValue()); assertEquals(MessageUtil.ERROR_CODE_FOR_906, violations.get(0).getCode()); } private static Stream<Arguments> namedArguments() { return Stream.of( Arguments.of(true, true, null, ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(true, true, null, ProcessingStatusTypeEnum.OODEP_ACCEPTED), Arguments.of(true, false, null, ProcessingStatusTypeEnum.OODEP_UNDER_ENQUIRY_PROCEDURE), Arguments.of(true, false, MessageTypes.CD_118_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(true, false, MessageTypes.CD_168_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(true, false, MessageTypes.CD_180_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(true, false, MessageTypes.CD_006_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(false, true, MessageTypes.CD_118_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(false, true, MessageTypes.CD_168_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(false, true, MessageTypes.CD_180_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(false, true, MessageTypes.CD_006_C.value(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED), Arguments.of(false, false, null, ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED) ); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class ArrivalPresentationServiceImpl implements ArrivalPresentationService { private final DossierDataService dossierDataService; private static final String RULE_ID = "CARGO_ARRIVAL_PRESENTATION_TIMER_EXPIRATION"; private static final String ERROR_CODE = "N/A"; private static final String ERROR_POINTER = "/TB015C/preparationDateAndTime"; @Override public void handleArrivalPresentationTimeout(String messageId) { // Persist rejecting Validation Result due to Cargo Arrival Presentation timer expiration: List<ValidationResult> validationResultList = new ArrayList<>(); ValidationResult rejectingValidationResult = ValidationResult.builder() .messageId(messageId) .createdDateTime(LocalDateTime.now(ZoneOffset.UTC)) .rejecting(true) .ruleId(RULE_ID) .errorCode(ERROR_CODE) .pointer(ERROR_POINTER) .build(); validationResultList.add(rejectingValidationResult); dossierDataService.saveValidationResultList(validationResultList); } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.mockito.Mockito.verify; import static org.junit.jupiter.api.Assertions.assertEquals; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ArrivalPresentationServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ArrivalPresentationServiceUT { private static final String MESSAGE_ID = "TEST_MESSAGE_ID"; private static final String RULE_ID = "CARGO_ARRIVAL_PRESENTATION_TIMER_EXPIRATION"; private static final String ERROR_CODE = "N/A"; private static final String ERROR_POINTER = "/TB015C/preparationDateAndTime"; @Mock private DossierDataService dossierDataService; @InjectMocks private ArrivalPresentationServiceImpl arrivalPresentationService; @Captor private ArgumentCaptor<List<ValidationResult>> validationResultListArgumentCaptor; @Test @DisplayName("Test - Handle Arrival Presentation Timeout") void testHandleArrivalPresentationTimeout() { // Call ArrivalPresentationService method: arrivalPresentationService.handleArrivalPresentationTimeout(MESSAGE_ID); // Verification & Assertions: verify(dossierDataService).saveValidationResultList(validationResultListArgumentCaptor.capture()); ValidationResult validationResultActual = validationResultListArgumentCaptor.getValue().get(0); assertEquals(MESSAGE_ID, validationResultActual.getMessageId()); assertEquals(RULE_ID, validationResultActual.getRuleId()); assertEquals(ERROR_CODE, validationResultActual.getErrorCode()); assertEquals(ERROR_POINTER, validationResultActual.getPointer()); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.cargov1.messages.TB015CType; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationArrivalNotificationFacade; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationInvalidationFacade; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationMainFacade; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import java.time.LocalDateTime; import java.time.ZoneOffset; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class ProcessMessageServiceImpl implements ProcessMessageService { private final ErmisLogger logger; private final DossierDataService dossierDataService; private final CargoOoDestinationMainFacade mainFacade; private final CargoOoDestinationArrivalNotificationFacade arrivalNotificationFacade; private final CargoOoDestinationInvalidationFacade invalidationFacade; @Override public void process(String messageId, String messageType, String movementId) { try { MessageTypes cargoMessageType = MessageTypes.fromValue(messageType); switch (cargoMessageType) { case TB_007_C: handleTB007C(movementId, messageId); break; case TB_014_C: handleTB014C(movementId, messageId); break; case TB_015_C: handleTB015C(movementId, messageId); break; default: logger.warn("Failed to process Message with type: {}, ignoring.", cargoMessageType.value()); break; } } catch (IllegalArgumentException exception) { logger.error(String.format("process(): MESSAGE PROCESSING EXCEPTION -> messageType: [%s], messageId: [%s], movementId: [%s]", messageType, messageId, movementId), exception); } } private void handleTB007C(String movementId, String messageId) { arrivalNotificationFacade.initProcessInstance(movementId, messageId); } private void handleTB014C(String movementId, String messageId) { invalidationFacade.initProcessInstance(movementId, messageId); } private void handleTB015C(String movementId, String messageId) { Movement movement = getMovement(movementId); Message message = getMessage(messageId); if (movement != null && message != null) { // Create Declaration and update Movement: createDeclaration(message, movementId); updateMovementWithDeclarationDataFromMessage(movement, message); mainFacade.initProcessInstance(movementId, messageId); } } private Movement getMovement(String movementId) { try { return dossierDataService.getMovementById(movementId); } catch (NotFoundException e) { logger.info("No Movement with ID: {} was found.", movementId); return null; } } private Message getMessage(String messageId) { try { return dossierDataService.getMessageById(messageId); } catch (NotFoundException e) { logger.info("No Message with ID: {} was found.", messageId); return null; } } private void createDeclaration(Message message, String movementId) { logger.info("Create Declaration for messageId: {} and movementId: {}", message.getId(), movementId); Declaration declaration = Declaration.builder() .movementId(movementId) .payloadType(message.getMessageType()) .payload(message.getPayload()) .build(); dossierDataService.createDeclaration(declaration); } private void updateMovementWithDeclarationDataFromMessage(Movement movement, Message message) { try { TB015CType tb015cTypeMessage = XmlConverter.buildMessageFromXML(message.getPayload(), TB015CType.class); movement.setDeclarationType(tb015cTypeMessage.getTransitOperation().getDeclarationType()); movement.setSubmitterIdentification(tb015cTypeMessage.getHolderOfTheTransitProcedure().getIdentificationNumber()); movement.setOfficeOfDeparture(tb015cTypeMessage.getCustomsOfficeOfDeparture().getReferenceNumber()); movement.setOfficeOfDestination(tb015cTypeMessage.getCustomsOfficeOfDestinationDeclared().getReferenceNumber()); movement.setCountryOfDestination(tb015cTypeMessage.getConsignment().getCountryOfDestination()); movement.setAcceptanceDateTime(LocalDateTime.now(ZoneOffset.UTC)); dossierDataService.updateMovement(movement); } catch (JAXBException e) { throw new BaseException("updateMovementWithDeclarationData(): ERROR during Message XML conversion.", e); } } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.cargov1.messages.TB015CType; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationArrivalNotificationFacade; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationInvalidationFacade; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationMainFacade; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ProcessMessageServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.cargoofficeofdestination.test.util.TestDataUtilities; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ProcessMessageServiceUT { private static final String MOVEMENT_ID_PREFIX = "MOVEMENT_ID_"; private static final String MESSAGE_ID_PREFIX = "MESSAGE_ID_"; private static final String TEST_DEPARTURE_OFFICE = "DK000000"; private static final String TEST_DESTINATION_OFFICE = "DK111111"; @Mock private ErmisLogger logger; @Mock private DossierDataService dossierDataService; @Mock private CargoOoDestinationMainFacade mainFacade; @Mock private CargoOoDestinationArrivalNotificationFacade arrivalNotificationFacade; @Mock private CargoOoDestinationInvalidationFacade invalidationFacade; @InjectMocks private ProcessMessageServiceImpl processMessageService; @Captor private ArgumentCaptor<Declaration> declarationArgumentCaptor; @Captor private ArgumentCaptor<Movement> movementArgumentCaptor; @ParameterizedTest @DisplayName("Test - Process Message Service") @MethodSource("provideTestArguments") void testProcessMessageService(String messageType) { // Test variables: String messageId = MESSAGE_ID_PREFIX + messageType; String movementId = MOVEMENT_ID_PREFIX + messageType; Message testMessage = null; TB015CType testTB015CType = null; MessageTypes cargoMessageType = MessageTypes.fromValue(messageType); // Mocks/Stubs per test case: switch (cargoMessageType) { case TB_007_C: case TB_014_C: // TODO: Add needed mocks/stubs when implemented. break; case TB_015_C: testTB015CType = TestDataUtilities.createTB015C(TEST_DEPARTURE_OFFICE, TEST_DESTINATION_OFFICE); testMessage = TestDataUtilities.createMessage(messageId, messageType, XmlConverter.marshal(testTB015CType, NamespacesEnum.NTA.getValue(), MessageTypes.TB_015_C.value())); when(dossierDataService.getMovementById(movementId)).thenReturn(TestDataUtilities.createMovement(movementId)); when(dossierDataService.getMessageById(messageId)).thenReturn(testMessage); break; default: break; } // Call ProcessMessageService method: processMessageService.process(messageId, messageType, movementId); // Verifications & assertions per test case: switch (cargoMessageType) { case TB_007_C: verify(arrivalNotificationFacade, times(1)).initProcessInstance(movementId, messageId); break; case TB_014_C: verify(invalidationFacade, times(1)).initProcessInstance(movementId, messageId); break; case TB_015_C: verify(dossierDataService, times(1)).getMovementById(movementId); verify(dossierDataService, times(1)).getMessageById(messageId); verify(dossierDataService, times(1)).createDeclaration(declarationArgumentCaptor.capture()); verify(dossierDataService, times(1)).updateMovement(movementArgumentCaptor.capture()); verify(mainFacade, times(1)).initProcessInstance(movementId, messageId); Movement capturedMovement = movementArgumentCaptor.getValue(); Declaration capturedDeclaration = declarationArgumentCaptor.getValue(); assertEquals(testTB015CType.getTransitOperation().getDeclarationType(), capturedMovement.getDeclarationType()); assertEquals(testTB015CType.getHolderOfTheTransitProcedure().getIdentificationNumber(), capturedMovement.getSubmitterIdentification()); assertEquals(testTB015CType.getCustomsOfficeOfDeparture().getReferenceNumber(), capturedMovement.getOfficeOfDeparture()); assertEquals(testTB015CType.getCustomsOfficeOfDestinationDeclared().getReferenceNumber(), capturedMovement.getOfficeOfDestination()); assertEquals(testTB015CType.getConsignment().getCountryOfDestination(), capturedMovement.getCountryOfDestination()); assertEquals(movementId, capturedDeclaration.getMovementId()); assertEquals(messageType, capturedDeclaration.getPayloadType()); assertEquals(testMessage.getPayload(), capturedDeclaration.getPayload()); break; default: // Invalid Cargo Message type provided as test argument. fail(); break; } } private static Stream<Arguments> provideTestArguments() { return Stream.of( Arguments.of(MessageTypes.TB_007_C.value()), Arguments.of(MessageTypes.TB_014_C.value()), Arguments.of(MessageTypes.TB_015_C.value()) ); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofdeparture.service; import com.intrasoft.ermis.ddntav5152.messages.GuaranteeType06; import com.intrasoft.ermis.platform.shared.client.reference.data.core.ReferenceDataAdapter; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeList; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListDomain; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListItem; import com.intrasoft.ermis.transit.officeofdeparture.domain.ExchangeRate; import com.intrasoft.ermis.transit.officeofdeparture.domain.ExchangeRates; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.stream.Collectors; import com.intrasoft.proddev.referencedata.shared.enums.CodelistKeyEnum; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class CurrencyConverterService { public static final String EUR = "EUR"; // Most of Rate Values in CL048 have 4 decimals private static final int RATE_SCALE = 4; private static final int CURRENCY_SCALE = 2; private static final String RATE_VALUE_ATTRIBUTE_KEY_LITERAL = "RateValue"; private final ReferenceDataAdapter referenceDataAdapter; /** * Retrieves from Reference Data and stores in a {@link ExchangeRates} instance all the Exchange Rates for Related currencies, * excluding EUR currency if set as so. */ public ExchangeRates getRelatedExchangeRates(List<GuaranteeType06> guaranteeType06List, boolean excludeEuroCurrency) { final CodeList codeList = referenceDataAdapter.getCodeList(CodelistKeyEnum.CURRENCY_CODES.getKey(), CodeListDomain.NCTSP5); Set<String> relatedCurrencies = extractDistinctCurrenciesFromGuarantees(guaranteeType06List, excludeEuroCurrency); List<CodeListItem> filteredCodelistItemList = codeList.getItems() .stream() .filter(item -> relatedCurrencies.contains(item.getCode().toUpperCase(Locale.ROOT))) .collect(Collectors.toList()); ExchangeRates exchangeRates = new ExchangeRates(); filteredCodelistItemList.forEach(item -> { BigDecimal euro2CurrencyRate = getRateValueFromCodeListItem(item); if (euro2CurrencyRate.doubleValue() > 0) { exchangeRates.putExchangeRate(ExchangeRate.builder() .currencyCL(item.getCode().toUpperCase(Locale.ROOT)) .euro2CurrencyRate(euro2CurrencyRate) .currency2EuroRate(BigDecimal.ONE.divide(euro2CurrencyRate, RATE_SCALE, RoundingMode.HALF_EVEN)) .build()); } }); return exchangeRates; } public BigDecimal convertEuro2Currency(BigDecimal amountInEuro, @NonNull String currencyCLTo, ExchangeRates exchangeRates) { return amountInEuro.multiply(exchangeRates.getExchangeRate(currencyCLTo).getEuro2CurrencyRate()).setScale(CURRENCY_SCALE, RoundingMode.HALF_EVEN); } public BigDecimal convertCurrency2Euro(BigDecimal amountInCurrency, @NonNull String currencyCLFrom, ExchangeRates exchangeRates) { return amountInCurrency.multiply(exchangeRates.getExchangeRate(currencyCLFrom).getCurrency2EuroRate()).setScale(CURRENCY_SCALE, RoundingMode.HALF_EVEN); } public BigDecimal convertCurrency2Currency(BigDecimal amount, @NonNull String currencyCLFrom, @NonNull String currencyCLTo, ExchangeRates exchangeRates) { if (currencyCLFrom.equalsIgnoreCase(currencyCLTo)) return amount; // If one of the currencies is EUR avoid the unnecessary double conversion if (EUR.equalsIgnoreCase(currencyCLFrom)) return convertEuro2Currency(amount, currencyCLTo, exchangeRates); else if (EUR.equalsIgnoreCase(currencyCLTo)) return convertCurrency2Euro(amount, currencyCLFrom, exchangeRates); else { // None of the 2 currencies is EUR return convertEuro2Currency( convertCurrency2Euro(amount, currencyCLFrom, exchangeRates), currencyCLTo, exchangeRates); } } private Set<String> extractDistinctCurrenciesFromGuarantees(List<GuaranteeType06> guaranteeType06List, boolean excludeEuroCurrency) { return guaranteeType06List.stream() .flatMap(guaranteeType06 -> guaranteeType06.getGuaranteeReference().stream()) .map(guaranteeReference -> guaranteeReference.getCurrency().toUpperCase(Locale.ROOT)) .filter(currency -> !excludeEuroCurrency || !EUR.equalsIgnoreCase(currency)) .collect(Collectors.toSet()); } private BigDecimal getRateValueFromCodeListItem(CodeListItem codeListItem) { return new BigDecimal( codeListItem.getAttributes() .stream() .filter(attribute -> attribute.getKey().equals(RATE_VALUE_ATTRIBUTE_KEY_LITERAL)) .findFirst() .orElseThrow(() -> new RuntimeException( "No Attribute: [" + RATE_VALUE_ATTRIBUTE_KEY_LITERAL + "] found in CodeListItem: " + codeListItem.getCode())) .getValue()); } }
package com.intrasoft.ermis.trs.officeofdeparture.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; import com.intrasoft.ermis.ddntav5152.messages.GuaranteeReferenceType04; import com.intrasoft.ermis.ddntav5152.messages.GuaranteeType06; import com.intrasoft.ermis.platform.shared.client.reference.data.core.ReferenceDataAdapter; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.Attribute; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeList; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListDomain; import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListItem; import com.intrasoft.ermis.transit.officeofdeparture.domain.ExchangeRates; import com.intrasoft.ermis.transit.officeofdeparture.service.CurrencyConverterService; import com.intrasoft.proddev.referencedata.shared.enums.CodelistKeyEnum; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class CurrencyConverterServiceUT { private static final String RATE_VALUE_ATTRIBUTE_KEY_LITERAL = "RateValue"; private static final int RATE_SCALE = 4; @Mock private ReferenceDataAdapter referenceDataAdapter; @InjectMocks private CurrencyConverterService currencyConverterService; @ParameterizedTest @DisplayName("Test - Get Related Exchange Rates") @ValueSource(booleans = {true, false}) void testGetRelatedExchangeRates(boolean excludeEuroCurrency) { // Test data: CodeList mockCodelist = buildMockCodelist(); List<GuaranteeType06> mockGuaranteeList = buildGuaranteeList(); // Stubs: when(referenceDataAdapter.getCodeList(CodelistKeyEnum.CURRENCY_CODES.getKey(), CodeListDomain.NCTSP5)).thenReturn(mockCodelist); // Call tested method: ExchangeRates result = currencyConverterService.getRelatedExchangeRates(mockGuaranteeList, excludeEuroCurrency); // Assertions: try { result.getExchangeRate("GBP"); // Fail if above call does not throw exception: fail(); } catch (IllegalArgumentException exception) { if (!"Currency code not valid or not supported : 'GBP'".equals(exception.getMessage())) { fail(); } } if (excludeEuroCurrency) { try { result.getExchangeRate("EUR"); // Fail if above call does not throw exception: fail(); } catch (IllegalArgumentException exception) { if (!"Currency code not valid or not supported : 'EUR'".equals(exception.getMessage())) { fail(); } } } else { assertEquals("EUR", result.getExchangeRate("EUR").getCurrencyCL()); assertEquals(BigDecimal.valueOf(1.0), result.getExchangeRate("EUR").getEuro2CurrencyRate()); assertEquals(BigDecimal.valueOf(1.0).setScale(RATE_SCALE, RoundingMode.HALF_EVEN), result.getExchangeRate("EUR").getCurrency2EuroRate()); } assertEquals("DKK", result.getExchangeRate("DKK").getCurrencyCL()); assertEquals(BigDecimal.valueOf(5.0), result.getExchangeRate("DKK").getEuro2CurrencyRate()); assertEquals(BigDecimal.valueOf(0.2).setScale(RATE_SCALE, RoundingMode.HALF_EVEN), result.getExchangeRate("DKK").getCurrency2EuroRate()); } private CodeList buildMockCodelist() { CodeListItem itemDKK = CodeListItem.builder() .code("DKK") .attributes(List.of(Attribute.builder().key(RATE_VALUE_ATTRIBUTE_KEY_LITERAL).value("5.0").build())) .build(); CodeListItem itemEUR = CodeListItem.builder() .code("EUR") .attributes(List.of(Attribute.builder().key(RATE_VALUE_ATTRIBUTE_KEY_LITERAL).value("1.0").build())) .build(); CodeListItem itemGBP = CodeListItem.builder() .code("GBP") .attributes(List.of(Attribute.builder().key(RATE_VALUE_ATTRIBUTE_KEY_LITERAL).value("2.0").build())) .build(); return CodeList.builder() .code(CodelistKeyEnum.CURRENCY_CODES.getKey()) .items(List.of(itemDKK, itemEUR, itemGBP)) .build(); } private List<GuaranteeType06> buildGuaranteeList() { GuaranteeType06 firstGuarantee = new GuaranteeType06(); GuaranteeReferenceType04 firstGuaranteeReferenceOne = new GuaranteeReferenceType04(); GuaranteeReferenceType04 firstGuaranteeReferenceTwo = new GuaranteeReferenceType04(); firstGuaranteeReferenceOne.setCurrency("DKK"); firstGuaranteeReferenceOne.setAmountConcerned(BigDecimal.TEN); firstGuaranteeReferenceTwo.setCurrency("EUR"); firstGuaranteeReferenceTwo.setAmountConcerned(BigDecimal.ONE); firstGuarantee.getGuaranteeReference().addAll(List.of(firstGuaranteeReferenceOne, firstGuaranteeReferenceTwo)); GuaranteeType06 secondGuarantee = new GuaranteeType06(); GuaranteeReferenceType04 secondGuaranteeReferenceOne = new GuaranteeReferenceType04(); secondGuaranteeReferenceOne.setCurrency("DKK"); secondGuaranteeReferenceOne.setAmountConcerned(BigDecimal.TEN); secondGuarantee.getGuaranteeReference().add(secondGuaranteeReferenceOne); return new ArrayList<>(List.of(firstGuarantee, secondGuarantee)); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.management.core.service.report; import static java.text.MessageFormat.format; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CD003CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.management.core.exception.BadRequestException; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.service.ConfigurationSwitchService; import com.intrasoft.ermis.transit.management.domain.Declaration; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.MessageOverview; import com.intrasoft.ermis.transit.management.domain.Movement; import com.intrasoft.ermis.transit.management.domain.Violation; import com.intrasoft.ermis.transit.management.domain.enums.PrintType; import com.intrasoft.ermis.transit.management.domain.enums.TADVersionEnum; import com.intrasoft.ermis.transit.management.domain.report.CC029CRootRM; import com.intrasoft.ermis.transit.management.domain.report.PrintConfiguration; import com.intrasoft.ermis.transit.management.domain.report.TemplateConfiguration; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.DateTimeException; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.EnumMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class ReportServiceImpl implements ReportService { /* @formatter:off */ public static final Map<com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum, Set<MessageTypes>> VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE = new EnumMap<>( Map.of( com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.DEPARTURE, Set.of(MessageTypes.CC_029_C), com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.DESTINATION, Set.of(MessageTypes.CD_001_C, MessageTypes.CD_003_C), com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.EXIT, Set.of(MessageTypes.CD_160_C, MessageTypes.CD_165_C), com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.TRANSIT, Set.of(MessageTypes.CD_050_C, MessageTypes.CD_115_C), com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.INCIDENT, Set.of(MessageTypes.CD_038_C), com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.LODGEMENT, Set.of(MessageTypes.CC_015_C) )); /* @formatter:on */ protected static final EnumMap<com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum, Set<MessageTypes>> VALID_NP_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE = new EnumMap<>( Map.of( com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.DEPARTURE, Set.of(MessageTypes.CC_013_C, MessageTypes.CC_015_C) )); protected static final Set<MessageTypes> VALID_TAD_REPORT_MESSAGE_TYPES = VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); protected static final Set<MessageTypes> VALID_NP_REPORT_MESSAGE_TYPES = VALID_NP_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); public static final String SECURITY_0 = "0"; public static final String JRXML_CC029C = "CC029C"; private static final String TEMPLATE_RESOURCE_URL = "reports/iemessages/{0}/p5/Master.jrxml"; private static final String TRANSLATIONS_RESOURCE_URL = "reports.iemessages.i18n.IEMessages"; private static final String TEMPLATE_RESOURCE_URL_P4 = "reports/iemessages/{0}/p4/tad/TAD.jrxml"; private static final String TEMPLATE_TSAD_RESOURCE_URL_P4 = "reports/iemessages/{0}/p4/tad/TAD_SEC.jrxml"; private static final String TRANSLATIONS_RESOURCE_URL_P4 = "reports.iemessages.i18n.TAD_P4"; public static final String JRXML_NP_RESOURCE_BASE_URL = "reports/iemessages/{0}/Master.jrxml"; public static final String MASTER_JRXML_RESOURCE_BUNDLE = "reports.iemessages.i18n.IEMessages"; // **************** Dependencies ************************ private final DossierDataService dossierDataService; private final CC029CPrintDataAggregator cc029CPrintDataAggregator; private final CC015CPrintDataAggregator cc015CPrintDataAggregator; private final PrintService printer; private final P4PrintModelMapper p4PrintModelMapper; private final ErmisLogger ermisLogger; private final ReportMessageTranslatorService reportMessageTranslatorService; private final ConfigurationSwitchService configurationSwitchService; @Override public byte[] printMessage(String mrn, String officeRoleType, String messageId, PrintType printType, String language, String country, String datePattern, String timezone, String version, String security) throws BadRequestException { var printConfiguration = validatePrintConfiguration(PrintConfiguration.builder() .printType(printType) .language(language) .country(country) .datePattern(datePattern) .timezone(timezone) .username("") .build()); validateOfficeRoleType(officeRoleType); ermisLogger.debug("Will print IE message with id '{}' as {} (the relevant MRN is '{}').", messageId, printConfiguration.getPrintType().name(), mrn); Message originalMessage; if (StringUtils.isNotBlank(messageId)) { // If the [messageId] param has been provided in the Rest endpoint, then fetch the Message directly by Message ID. // Optimised approach, used on Office of DEPARTURE with CC029C originalMessage = dossierDataService.getMessageById(messageId, false); } else if (StringUtils.isBlank(officeRoleType)) { // If only the [MRN] param has been provided, assume that the request is from DEPARTURE and the message type is CC029C originalMessage = getMessageByMRN(mrn); if (originalMessage == null) { throw new NotFoundException( String.format( "Couldn't find message for MRN: [%s], default Office Role Type: [DEPARTURE] and default Message Type: [CC029C]. Cannot generate TAD document!", mrn)); } } else { // Finally if [MRN] and [officeRoleType] params have been provided, search into the Dossier for the suitable message. // Non optimised approach. Multiple Dossier calls involved originalMessage = getMessageByMRNAndOfficeRoleType(mrn, null, officeRoleType, VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE); if (originalMessage == null) { throw new NotFoundException( String.format("Couldn't find message for MRN: [%s], Office Role Type: [%s] and Message Type in: %s. Cannot generate TAD document!", mrn, officeRoleType, printReportMessageTypesForOfficeRoleType(officeRoleType))); } } // Call relevant print method. Object printModel = cc029CPrintDataAggregator.aggregatePrintData(mrn, reportMessageTranslatorService.generateCC029CTypeMessageFromOriginalMessage(originalMessage)); String finalVersion = decideTadVersion(ReportMessageTranslatorImpl.findMessageType(originalMessage), version); if (TADVersionEnum.P4.getVersion().equals(finalVersion)) { printConfiguration.setTemplate( new TemplateConfiguration(format(computeP4JrxmlResourcePath(security), MessageTypes.CC_029_C.value()), TRANSLATIONS_RESOURCE_URL_P4)); printModel = p4PrintModelMapper.factoringDeclarationPrintDataTO((CC029CRootRM) printModel); } else { printConfiguration.setTemplate(new TemplateConfiguration(format(TEMPLATE_RESOURCE_URL, MessageTypes.CC_029_C.value()), TRANSLATIONS_RESOURCE_URL)); } byte[] bytes = printer.print(printConfiguration, printModel); saveTADToDisk(originalMessage.getMessageType(), "TAD", mrn, bytes); ermisLogger.info("Generated TAD document from message with id '{}' and type [{}] (the relevant MRN is '{}') from message type: [{}]", originalMessage.getMessageIdentification(), printConfiguration.getPrintType().name(), mrn, originalMessage.getMessageType()); return bytes; } @Override public byte[] printNationalPrintMessage(String mrn, String lrn, String officeRoleType, String messageId, PrintType printType, String language, String country, String datePattern, String timezone, String version) throws BadRequestException, JAXBException { var printConfiguration = validatePrintConfiguration(PrintConfiguration.builder() .printType(printType) .language(language) .country(country) .datePattern(datePattern) .timezone(timezone) .username("") .template(getNationalPrintTemplate()) .build()); validateOfficeRoleType(officeRoleType); ermisLogger.debug("Will print IE message with id '{}' as {} (the relevant MRN is '{}').", messageId, printConfiguration.getPrintType().name(), mrn); mrn = cleanInput(mrn); lrn = cleanInput(lrn); String finalMrn = mrn; Movement movement = dossierDataService .findByCriteria(mrn, lrn, officeRoleType, null, 2) .stream() .findFirst() .orElseThrow(() -> new NotFoundException("No DEPARTURE Movement found for mrn: [" + finalMrn + "]")); Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movement.getId()); CC015CType cc015cTypeMessage = XmlConverter.buildMessageFromXML(declaration.getPayload(), CC015CType.class); Message originalMessage = Message.builder() .messageIdentification(cc015cTypeMessage.getMessageIdentification()) .messageType(cc015cTypeMessage.getMessageType().value()) .source(cc015cTypeMessage.getMessageSender()) .destination(cc015cTypeMessage.getMessageRecipient()) .domain(MessageDomainTypeEnum.EXTERNAL.name()) .payload(declaration.getPayload()) .direction(DirectionEnum.SENT.getDirection()) .build(); Object printModel = cc015CPrintDataAggregator.aggregatePrintData(mrn, lrn, originalMessage); byte[] bytes = printer.print(printConfiguration, printModel); saveTADToDisk(originalMessage.getMessageType(), "NATIONAL_PRINT" , mrn, bytes); ermisLogger.info("Generated NP document from message with id '{}' and type [{}] (the relevant MRN is '{}') from message type: [{}]", originalMessage.getMessageIdentification(), printConfiguration.getPrintType().name(), mrn, originalMessage.getMessageType()); return bytes; } @SneakyThrows public Message getMessageByMRNAndOfficeRoleType(String mrn, String lrn, String officeRoleType, Map<com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum, Set<MessageTypes>> officeRolesTypesMap) { com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum officeRoleTypesEnum = Objects.requireNonNull(com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.of(officeRoleType)); for (MessageTypes messageTypes : officeRolesTypesMap.get(officeRoleTypesEnum)) { var message = findLastMessageByMrnOfficeRoleTypeAndMessageType(mrn, lrn, officeRoleType, messageTypes.value()); if (message != null) { if (message.getMessageType().equals(MessageTypes.CD_003_C.value())) { // Special treatment on CD003C. Needs to be a 'positive' CD003C in order to be considered for TAD Generation CD003CType cd003CType = XmlConverter.buildMessageFromXML(message.getPayload(), CD003CType.class); String requestRejectedReasonCode = cd003CType.getTransitOperation().getRequestRejectionReasonCode(); if (StringUtils.isNotBlank(requestRejectedReasonCode)) { ermisLogger.info( "CD003C message with id: [{}] for MRN: [{}] and OfficeRoleType: [{}] is not POSITIVE with requestRejectionReasonCode=[{}]. Will not be considered for TAD Generation", message.getMessageIdentification(), mrn, officeRoleType, requestRejectedReasonCode); continue; } else { return message; } } ermisLogger.info("Found suitable message with Id: [{}] and Type: [{}] for TAD generation on MRN: [{}] and OfficeRoleType: [{}]", message.getId(), message.getMessageType(), mrn, officeRoleType); return message; } } return null; } /** * @return : Message if found or NULL if not found */ public Message findLastMessageByMrnOfficeRoleTypeAndMessageType(String mrn, String lrn, String officeRoleType, String messageType) { ermisLogger.info("findLastMessageByMrnOfficeRoleTypeAndMessageType w mrn: {}, lrn: {}, officeRoleType: {}", mrn, lrn, officeRoleType); // Step 1.) -> Find the MOVEMENT record by MRN and OFFICE_ROLE_TYPE Movement movement = dossierDataService .findByCriteria(mrn, lrn, officeRoleType, null, 2) .stream() .findFirst() .orElseThrow(() -> new NotFoundException( String.format("Couldn't find movement for MRN: [%s], LRN: [%s] Office RoleType: [%s]. Cannot generate TAD document", mrn, lrn, officeRoleType))); // Step 2.) -> Find the Message ID by Movement Id and Message Type String messageId = findMessageIdByMovementIdAndMessageType(movement.getId(), messageType); return messageId != null ? dossierDataService.getMessageById(messageId, false) : null; } /** * @return : Message if found or NULL if not found */ private Message getMessageByMRN(String mrn) { Movement movement = dossierDataService .findByCriteria(mrn, null, OfficeRoleTypesEnum.DEPARTURE.getValue(), null, 2) .stream() .findFirst() .orElseThrow(() -> new NotFoundException("No DEPARTURE Movement found for mrn: [" + mrn + "]")); String messageId = findMessageIdByMovementIdAndMessageType(movement.getId(), MessageTypes.CC_029_C.value()); return messageId != null ? dossierDataService.getMessageById(messageId, false) : null; } /** * @return : MOVEMENT.ID if movement found , NULL if Movement not found */ public String findMessageIdByMovementIdAndMessageType(String movementId, String messageType) { return dossierDataService .getMessagesOverview(messageType, movementId, false) .stream() .findFirst() .orElseGet(() -> MessageOverview.builder().build()) .getId(); } private String decideTadVersion(MessageTypes originalMessageType, String version) { if (MessageTypes.CC_029_C == originalMessageType) { return version; } else if (MessageTypes.CC_015_C == originalMessageType) { return TADVersionEnum.P5.getVersion(); } else { return retrieveTadVersionFromBusinessRule(); } } String retrieveTadVersionFromBusinessRule() { return translateTadVersionValueIfNeeded(configurationSwitchService.retrieveTADVersion()); } /** * Rule Instance parameter [TADVersion] values are stored as 'P4' or 'P5' in the Configuration database. Convert them to "NCTS_P4" or "NCTS_P5" to match the * {@link TADVersionEnum#getVersion} */ private static String translateTadVersionValueIfNeeded(String value) { if (value.contains("P4")) { return TADVersionEnum.P4.getVersion(); } else if (value.contains("P5")) { return TADVersionEnum.P5.getVersion(); } else { throw new BaseException(String.format("Unknown Value: [%s] returned from Rule: [%s]", value, ConfigurationSwitchService.GET_TAD_VERSION_RS)); } } /** * <pre> * Useful on Local Development where WEB UI is not available and there is no "OPEN/SAVE AS" functionality via a web browser to view the PDF document * Add an extra VM option [-Dcwm.api-gateway.saveTadToDisk=true] in the Spring Boot Run/Debug Configuration * The generated PDF Document will be saved locally in the OS default temporary-file directory * Double-click on the file and view the PDF content */ @SuppressWarnings("findsecbugs:PATH_TRAVERSAL_IN") private void saveTADToDisk(String originalMessageType, String reportType, String mrn, byte[] bytes) { if ("true".equalsIgnoreCase(System.getProperty("cwm.api-gateway.saveTadToDisk"))) { try { Path root = Files.createTempDirectory(".." + reportType + "_"); var path = Paths.get(root.toFile().getAbsolutePath(), System.currentTimeMillis() + "_" + originalMessageType + "_" + mrn + ".pdf"); Files.write(path, bytes); ermisLogger.info(":=> Saved " + reportType + " PDF into: [" + path.toAbsolutePath() + "]"); } catch (IOException e) { ermisLogger.error("Could not save " + reportType + " document to disk!!", e); } } } public static String printReportMessageTypesForOfficeRoleType(String officeRoleType) { return VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE .get(Objects.requireNonNull(com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.of(officeRoleType))) .stream() .map(messageType -> "[" + (messageType != MessageTypes.CC_029_C ? messageType.value() : "CC_029_C") + "]") .collect(Collectors.joining(",")); } // **************************** Validators ******************************* private static PrintConfiguration validatePrintConfiguration(PrintConfiguration printConfig) throws BadRequestException { if (printConfig == null) { return PrintConfiguration.createDefault(); } var pc = new PrintConfiguration(); pc.setPrintType(printConfig.getPrintType()); pc.setLanguage(validateLanguage(printConfig.getLanguage())); pc.setCountry(validateCountry(printConfig.getCountry())); pc.setDatePattern(validateDatePattern(printConfig.getDatePattern())); pc.setTimezone(validateTimezone(printConfig.getTimezone())); pc.setUsername(printConfig.getUsername()); pc.setTemplate(printConfig.getTemplate()); return pc; } private static String validateTimezone(String timezone) throws BadRequestException { try { ZoneId.of(timezone); return timezone; } catch (DateTimeException | NullPointerException ex) { throw new BadRequestException(List.of(Violation.builder().reason("Invalid timezone " + timezone).build())); } } private static String validateLanguage(String language) throws BadRequestException { Set<String> languages = Set.of(Locale.getISOLanguages()); if (language == null || language.isBlank() || !languages.contains(language.toLowerCase(Locale.US))) { throw new BadRequestException(List.of(Violation.builder().reason("Invalid language " + language).build())); } return language.toLowerCase(Locale.US); } private static String validateCountry(String country) throws BadRequestException { Set<String> countries = Set.of(Locale.getISOCountries()); if (country == null || country.isBlank() || !countries.contains(country.toUpperCase(Locale.US))) { throw new BadRequestException(List.of(Violation.builder().reason("Invalid country: " + country).build())); } return country.toUpperCase(Locale.US); } private static String validateDatePattern(String datePattern) throws BadRequestException { try { DateTimeFormatter.ofPattern(datePattern); return datePattern; } catch (IllegalArgumentException | NullPointerException ex) { throw new BadRequestException(List.of(Violation.builder().reason("Invalid datePattern: " + datePattern).build())); } } public static void validateOfficeRoleType(String officeRoleType) throws BadRequestException { if (StringUtils.isNotBlank(officeRoleType)) { com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum officeRoleTypesEnum = Objects.requireNonNull(com.intrasoft.ermis.platform.contracts.dossier.enums.OfficeRoleTypesEnum.of(officeRoleType), String.format("Unknown OfficeRoleType: [%s]. Cannot generate TAD document", officeRoleType)); if (!VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE.containsKey(officeRoleTypesEnum)) { throw new BadRequestException( List.of( Violation.builder() .reason(String.format("Invalid OfficeRoleType: [%s]. Not supported for TAD Generation", officeRoleType)) .build())); } } } private static TemplateConfiguration getNationalPrintTemplate() { return new TemplateConfiguration(format(JRXML_NP_RESOURCE_BASE_URL, "np"), MASTER_JRXML_RESOURCE_BUNDLE); } private static String cleanInput(String input) { if ("null".equals(input)) { input = null; } return input; } private String computeP4JrxmlResourcePath(String security) { if (SECURITY_0.equals(security)) { return format(TEMPLATE_RESOURCE_URL_P4, JRXML_CC029C); } else { return format(TEMPLATE_TSAD_RESOURCE_URL_P4, JRXML_CC029C); } } }
package com.intrasoft.ermis.transit.management.core.service; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.service.report.ReportServiceImpl; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.MessageOverview; import com.intrasoft.ermis.transit.management.domain.Movement; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.List; import static com.intrasoft.ermis.transit.management.core.service.report.ReportServiceImpl.VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @DisplayName("Report Service Implementation Unit Tests") @ExtendWith(MockitoExtension.class) class ReportServiceImplUT { @Mock private DossierDataService dossierDataService; @Mock private ErmisLogger ermisLogger; @InjectMocks private ReportServiceImpl reportService; @Test void testValidateOfficeRoleTypeWithValidType() { String validOfficeRoleType = "DEPARTURE"; assertDoesNotThrow(() -> ReportServiceImpl.validateOfficeRoleType(validOfficeRoleType)); } @Test void testValidateOfficeRoleTypeWithInvalidType() { String invalidOfficeRoleType = "InvalidType"; Throwable exception = assertThrows(NullPointerException.class, () -> ReportServiceImpl.validateOfficeRoleType(invalidOfficeRoleType)); assertEquals("Unknown OfficeRoleType: [InvalidType]. Cannot generate TAD document", exception.getMessage()); } @Test void testValidateOfficeRoleTypeWithBlankType() { String blankOfficeRoleType = ""; assertDoesNotThrow(() -> ReportServiceImpl.validateOfficeRoleType(blankOfficeRoleType)); } @Test void testPrintReportMessageTypesForOfficeRoleType() { String resultDeparture = ReportServiceImpl.printReportMessageTypesForOfficeRoleType("DEPARTURE"); assertEquals("[CC_029_C]", resultDeparture); } @Test void testPrintReportMessageTypesForNullOfficeRoleType() { assertThrows(NullPointerException.class, () -> ReportServiceImpl.printReportMessageTypesForOfficeRoleType(null)); } @Test void testPrintReportMessageTypesForInvalidOfficeRoleType() { String invalidOfficeRoleType = "InvalidType"; assertThrows(NullPointerException.class, () -> ReportServiceImpl.printReportMessageTypesForOfficeRoleType(invalidOfficeRoleType)); } @Test void testGetMessageByMRNAndOfficeRoleType() { String mrn = "22DKHMEAOZJLUULEJ2"; String officeRoleType = "DEPARTURE"; when(dossierDataService.findByCriteria(mrn, null, officeRoleType, null, 2)).thenReturn(getListOfMovements()); when(dossierDataService.getMessagesOverview(any(), any(), anyBoolean())).thenReturn(getListOfMessageOverviews()); when(dossierDataService.getMessageById(any(), anyBoolean())).thenReturn(getMessage("CC_029_C")); Message message = reportService.getMessageByMRNAndOfficeRoleType(mrn, null, officeRoleType, VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE); assertNotNull(message); } @Test void testGetMessageByMRNAndOfficeRoleType_caseOfCD003CPositive() { String mrn = "22DKHMEAOZJLUULEJ2"; String officeRoleType = "DESTINATION"; when(dossierDataService.findByCriteria(mrn, null, officeRoleType, null, 2)).thenReturn(getListOfMovements()); when(dossierDataService.getMessagesOverview(any(), any(), anyBoolean())).thenReturn(getListOfMessageOverviews()); doReturn(getPositiveCD003C("CD003C")).when(dossierDataService).getMessageById(any(), anyBoolean()); Message message = reportService.getMessageByMRNAndOfficeRoleType(mrn, null, officeRoleType, VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE); assertNotNull(message); } @Test void testGetMessageByMRNAndOfficeRoleType_caseOfCD003CNegative() { String mrn = "22DKHMEAOZJLUULEJ2"; String officeRoleType = "DESTINATION"; when(dossierDataService.findByCriteria(mrn, null, officeRoleType, null, 2)).thenReturn(getListOfMovements()); when(dossierDataService.getMessagesOverview(any(), any(), anyBoolean())).thenReturn(getListOfMessageOverviews()); doReturn(getNegativeCD003C("CD003C")).when(dossierDataService).getMessageById(any(), anyBoolean()); Message message = reportService.getMessageByMRNAndOfficeRoleType(mrn, null, officeRoleType,VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE); assertNull(message); } @Test void testGetMessageByMRNAndOfficeRoleType_returnsNull() { String mrn = "22DKHMEAOZJLUULEJ2"; String officeRoleType = "DEPARTURE"; when(dossierDataService.findByCriteria(any(), any(), any(), any(), anyInt())).thenReturn(getListOfMovements()); when(dossierDataService.getMessagesOverview(any(), any(), anyBoolean())).thenReturn(getListOfMessageOverviews()); when(dossierDataService.getMessageById(any(), anyBoolean())).thenReturn(null); Message message = reportService.getMessageByMRNAndOfficeRoleType(mrn, null, officeRoleType,VALID_TAD_REPORT_MESSAGE_TYPES_PER_OFFICE_ROLE_TYPE); assertNull(message); } private List<Movement> getListOfMovements() { List<Movement> movements = new ArrayList<>(); Movement movement1 = Movement.builder() .id("movementId1") .officeRoleType("DEPARTURE") .officeId("OfficeId1") .mrn("22DKHMEAOZJLUULEJ2") .lrn("test") .build(); movements.add(movement1); Movement movement2 = Movement.builder() .id("movementId2") .officeRoleType("DEPARTURE") .officeId("OfficeId2") .mrn("22DKHMEAOZJLUULEJ9") .lrn("test2") .build(); movements.add(movement2); return movements; } private List<MessageOverview> getListOfMessageOverviews() { List<MessageOverview> messageOverviews = new ArrayList<>(); MessageOverview overview1 = MessageOverview.builder() .id("overviewId1") .messageIdentification("messageId1") .messageType("CC_029_C") .build(); messageOverviews.add(overview1); MessageOverview overview2 = MessageOverview.builder() .id("overviewId2") .messageIdentification("messageId2") .messageType("CC_029_C") .build(); messageOverviews.add(overview2); return messageOverviews; } private Message getMessage(String messageType){ Message message = Message.builder() .id("sampleMessageId") .messageType(messageType) .payload("<xml>...</xml>") .build(); return message; } private Message getPositiveCD003C(String messageType){ Message message = Message.builder() .id("sampleMessageId") .messageType(messageType) .payload("<CD003C xmlns:ns2=\"http://ncts.dgtaxud.ec\"><messageSender>NTA.DK</messageSender><messageRecipient>NTA.DK</messageRecipient><preparationDateAndTime>2022-09-29T02:24:13</preparationDateAndTime><messageIdentification>QIBYKV1GY89NFI</messageIdentification><messageType>CD003C</messageType><correlationIdentifier>68WSD33UTCLG0G</correlationIdentifier><TransitOperation><MRN>21DK86Z3AFTRPMWDL1</MRN><requestRejectionReasonCode></requestRejectionReasonCode></TransitOperation><CustomsOfficeOfDestinationActual><referenceNumber>DK005600</referenceNumber></CustomsOfficeOfDestinationActual></CD003C>") .build(); return message; } private Message getNegativeCD003C(String messageType){ Message message = Message.builder() .id("sampleMessageId") .messageType(messageType) .payload("<CD003C xmlns:ns2=\"http://ncts.dgtaxud.ec\"><messageSender>NTA.DK</messageSender><messageRecipient>NTA.DK</messageRecipient><preparationDateAndTime>2022-09-29T02:24:13</preparationDateAndTime><messageIdentification>QIBYKV1GY89NFI</messageIdentification><messageType>CD003C</messageType><correlationIdentifier>68WSD33UTCLG0G</correlationIdentifier><TransitOperation><MRN>21DK86Z3AFTRPMWDL1</MRN><requestRejectionReasonCode>1</requestRejectionReasonCode></TransitOperation><CustomsOfficeOfDestinationActual><referenceNumber>DK005600</referenceNumber></CustomsOfficeOfDestinationActual></CD003C>") .build(); return message; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.management.core.service; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.contracts.core.dto.declaration.common.RegimeEnum; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.management.core.port.inbound.RiskAssessmentMessageProcessingService; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.port.outbound.ProcessMessageCommandProducer; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.Movement; import com.jayway.jsonpath.JsonPath; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class RiskAssessmentMessageProcessingServiceImpl implements RiskAssessmentMessageProcessingService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private final ErmisLogger log; private final DossierDataService dossierDataService; private final ProcessMessageCommandProducer processMessageCommandProducer; private final GetCountryCodeService getCountryCodeService; private static final String RISK_ASSESSMENT_SOURCE = "RISK_ASSESSMENT"; private static final String RESPONSE_ID_JSON_PATH = "$.responseId"; @Override public void processMessage(String messageJson) { log.info("RiskAssessmentMessageProcessingServiceImpl - processMessage"); RiskAssessmentResponseEvent receivedEvent = JSON_CONVERTER.convertStringToObject(messageJson, RiskAssessmentResponseEvent.class); if (RegimeEnum.TRANSIT.getCode().equals(receivedEvent.getRegime())) { String movementId = receivedEvent.getCorrelationKey(); Message message = setUpMessage(messageJson); message = dossierDataService.persistMessage(message); dossierDataService.associateMessageWithMovement(message.getId(), movementId); Movement movement = dossierDataService.getMovementById(movementId, false); processMessageCommandProducer.publish(message.getId(), message.getMessageType(), movement); } else { log.info("Consumed non-Transit RiskAssessmentResponseEvent! Ignoring..."); } } protected Message setUpMessage(String messageJson) { return Message.builder() .messageIdentification(JsonPath.read(messageJson, RESPONSE_ID_JSON_PATH)) .messageType(RiskAssessmentResponseEvent.class.getSimpleName()) .source(RISK_ASSESSMENT_SOURCE) .destination(MessageTypeMapper.NTA.concat(getCountryCodeService.getCountryCode())) .payload(messageJson) .domain(MessageDomainTypeEnum.ERMIS.name()) .direction(DirectionEnum.RECEIVED.getDirection()) .build(); } }
package com.intrasoft.ermis.transit.management.core.service; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentRequestEvent; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.port.outbound.ProcessMessageCommandProducer; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.Movement; import com.intrasoft.ermis.transit.shared.testing.util.FileHelpers; import java.util.List; import lombok.SneakyThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class RiskAssessmentMessageProcessingServiceImplUT { @Mock private ErmisLogger ermisLogger; @Mock private DossierDataService dossierDataService; @Mock private ProcessMessageCommandProducer processMessageCommandProducer; @Mock private GetCountryCodeService getCountryCodeService; @InjectMocks private RiskAssessmentMessageProcessingServiceImpl riskAssessmentMessageProcessingService; @Captor ArgumentCaptor<Message> messageArgumentCaptor; @Captor private ArgumentCaptor<String> messageIdCaptor; @Captor private ArgumentCaptor<String> movementIdCaptor; @Captor private ArgumentCaptor<String> messageTypeCaptor; @Captor ArgumentCaptor<Movement> movementArgumentCaptor; private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID"; private static final String REQUEST_ID = "TEST_REQUEST_ID"; private static final String RESPONSE_ID = "TEST_RESPONSE_ID"; private static final String DESTINATION = "NTA.DE"; private static final String RISK_ASSESSMENT = "RISK_ASSESSMENT"; private static final String OFFICE_ID = "AA000001"; @Test @SneakyThrows void testProcessMessage_success() { // given String responseMessageJson = FileHelpers.readClasspathFile("data/RiskAssessmentResponseEvent.json"); String requestMessageJson = FileHelpers.readClasspathFile("data/RiskAssessmentRequestEvent.json"); // when Message requestMessage = mockRequestMessage(requestMessageJson); Movement movement = Movement.builder() .id(MOVEMENT_ID) .officeRoleType(OfficeRoleTypesEnum.DESTINATION.getValue()) .officeId("AA000001") .processingStatus(ProcessingStatusTypeEnum.OODEST_AAR_CREATED.getItemCode()) .build(); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(dossierDataService.getMovementById(MOVEMENT_ID, false)).thenReturn(movement); when(dossierDataService.persistMessage(any())).thenAnswer(argument -> { Message message = argument.getArgument(0); message.setId(RESPONSE_ID); return message; }); riskAssessmentMessageProcessingService.processMessage(responseMessageJson); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), movementArgumentCaptor.capture()); assertThat(messageIdCaptor.getValue()).isEqualTo(RESPONSE_ID); assertThat(movementIdCaptor.getValue()).isEqualTo(MOVEMENT_ID); assertThat(messageTypeCaptor.getValue()).isEqualTo(RiskAssessmentResponseEvent.class.getSimpleName()); List<Movement> publishedMovements = movementArgumentCaptor.getAllValues(); assertThat(publishedMovements.size()).isEqualTo(1); assertTrue(publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DESTINATION.getValue())) .allMatch(m -> m.getOfficeId().equals(OFFICE_ID))); } private Message mockRequestMessage(String requestMessageJson) { return Message.builder() .messageIdentification("TEST_REQUEST_ID") .messageType(RiskAssessmentRequestEvent.class.getSimpleName()) .source(DESTINATION) .destination(RISK_ASSESSMENT) .domain(MessageDomainTypeEnum.ERMIS.name()) .payload(requestMessageJson) .build(); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.management.core.service.lrn; import static com.intrasoft.ermis.transit.management.core.service.lrn.LRNVariablesEnum.*; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.util.RandomUtil; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; @Service public class LRNGeneratorSubService { public static final String VARIABLE_PLACEHOLDER_LEFT = "{"; public static final String VARIABLE_PLACEHOLDER_RIGHT = "}"; private static final Map<Character, Integer> equivalentNumericalValues = new HashMap<>(); static { equivalentNumericalValues.put('0', 0); equivalentNumericalValues.put('1', 1); equivalentNumericalValues.put('2', 2); equivalentNumericalValues.put('3', 3); equivalentNumericalValues.put('4', 4); equivalentNumericalValues.put('5', 5); equivalentNumericalValues.put('6', 6); equivalentNumericalValues.put('7', 7); equivalentNumericalValues.put('8', 8); equivalentNumericalValues.put('9', 9); equivalentNumericalValues.put('A', 10); equivalentNumericalValues.put('B', 12); equivalentNumericalValues.put('C', 13); equivalentNumericalValues.put('D', 14); equivalentNumericalValues.put('E', 15); equivalentNumericalValues.put('F', 16); equivalentNumericalValues.put('G', 17); equivalentNumericalValues.put('H', 18); equivalentNumericalValues.put('I', 19); equivalentNumericalValues.put('J', 20); equivalentNumericalValues.put('K', 21); equivalentNumericalValues.put('L', 23); equivalentNumericalValues.put('M', 24); equivalentNumericalValues.put('N', 25); equivalentNumericalValues.put('O', 26); equivalentNumericalValues.put('P', 27); equivalentNumericalValues.put('Q', 28); equivalentNumericalValues.put('R', 29); equivalentNumericalValues.put('S', 30); equivalentNumericalValues.put('T', 31); equivalentNumericalValues.put('U', 32); equivalentNumericalValues.put('V', 34); equivalentNumericalValues.put('W', 35); equivalentNumericalValues.put('X', 36); equivalentNumericalValues.put('Y', 37); equivalentNumericalValues.put('Z', 38); } private static final Pattern LRN_REGEXP = Pattern.compile("^.*\\(.*\\)$"); private final GetCountryCodeService getCountryCodeService; private final ErmisLogger ermisLogger; LRNGeneratorSubService(GetCountryCodeService getCountryCodeService, ErmisLogger ermisLogger) { this.getCountryCodeService = getCountryCodeService; this.ermisLogger = ermisLogger; } public String generateLrn(CC015CType cc015CType, String expression) { int uniqueIdLengthParameter = 6; String dateParameter = ""; String value; List<String> variablesWithParameters = extractVariablesFromExpression(expression); for (String variableWithParameters : variablesWithParameters) { // If expression item contains a parameter - exampleItem(exampleParameter): if (LRN_REGEXP.matcher(variableWithParameters).find()) { String expressionParameter = variableWithParameters.substring(variableWithParameters.indexOf('(') + 1, variableWithParameters.indexOf(')')); if (variableWithParameters.contains(UNIQUE_ID.getDescription()) && variableWithParameters.length() != UNIQUE_ID.getDescription().length()) { uniqueIdLengthParameter = Integer.parseInt(expressionParameter); } else if (variableWithParameters.contains(DATE_PREP.getDescription()) && variableWithParameters.length() != DATE_PREP.getDescription().length()) { dateParameter = expressionParameter; } } } value = evalExpression(cc015CType, uniqueIdLengthParameter, dateParameter, expression); ermisLogger.info("Generated LRN: ".concat(value)); return value; } protected String evalExpression(CC015CType cc015CType, int uniqueIdLength, String dateFormat, String expression) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat); Properties nameValueMap = new Properties(); extractVariablesWithoutParametersFromExpression(expression).forEach(variableName -> { LRNVariablesEnum variableEnum = LRNVariablesEnum.fromDescription(variableName); if (ObjectUtils.isNotEmpty(variableEnum)) { switch (variableEnum) { case DATE_PREP: nameValueMap.put(DATE_PREP.getDescription(), cc015CType.getPreparationDateAndTime().format(formatter)); break; case COUNTRY_CODE: nameValueMap.put(COUNTRY_CODE.getDescription(), getCountryCodeService.getCountryCode()); break; case OFFICE_OF_DEPARTURE: nameValueMap.put(OFFICE_OF_DEPARTURE.getDescription(), cc015CType.getCustomsOfficeOfDeparture().getReferenceNumber()); break; case UNIQUE_ID: nameValueMap.put(UNIQUE_ID.getDescription(), generateRandomAlphanumeric(uniqueIdLength)); break; case CHECK_DIGIT: nameValueMap.put(CHECK_DIGIT.getDescription(), encloseVarInPlaceHolders(CHECK_DIGIT.getDescription())); // Initial Value break; default: break; } } else { ermisLogger.warn("Item of expression: ".concat(variableName) .concat(" not found in ".concat(LRNVariablesEnum.class.getSimpleName()))); } }); return parseLrnExpression(expression, nameValueMap); } private static String encloseVarInPlaceHolders(String varName) { return VARIABLE_PLACEHOLDER_LEFT + varName + VARIABLE_PLACEHOLDER_RIGHT; } private String parseLrnExpression(String expresion, Properties nameValueMap) { AtomicReference<String> expressionWithPlaceHolders = new AtomicReference<>(removeEverythingInParentheses(expresion)); AtomicReference<String> parsedExpression = new AtomicReference<>(expressionWithPlaceHolders.get()); nameValueMap.forEach((varName, varValue) -> { if (!varName.equals(CHECK_DIGIT.getDescription())) { parsedExpression.set( StringUtils.replace(parsedExpression.get(), encloseVarInPlaceHolders((String) varName), (String) varValue)); } } ); if (nameValueMap.containsKey(CHECK_DIGIT.getDescription())) { String parsedExpressionWithCheckDigitPlaceHolder = parsedExpression.get(); String parsedExpressionWithoutCheckDigitPlaceHolder = StringUtils.remove(parsedExpressionWithCheckDigitPlaceHolder, encloseVarInPlaceHolders(CHECK_DIGIT.getDescription())); String checkDigit = calculateCheckDigit(parsedExpressionWithoutCheckDigitPlaceHolder); parsedExpression.set( StringUtils.replace(parsedExpressionWithCheckDigitPlaceHolder, encloseVarInPlaceHolders(CHECK_DIGIT.getDescription()), checkDigit)); } return parsedExpression.get(); } private String generateRandomAlphanumeric(int targetStringLength) { int leftLimit = 48; // Number '0'. int rightLimit = 122; // Letter 'z'. return RandomUtil.generateSecureRandomInts(leftLimit, rightLimit) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString().toUpperCase(); } public static List<String> extractVariablesFromExpression(String expression) { return Arrays.stream(StringUtils.substringsBetween(expression, VARIABLE_PLACEHOLDER_LEFT, VARIABLE_PLACEHOLDER_RIGHT)) .map(String::trim) .collect(Collectors.toList()); } public static String removeEverythingInParentheses(String expression) { return expression.replaceAll("\\s*\\([^\\)]*\\)\\s*", ""); } public static List<String> extractVariablesWithoutParametersFromExpression(String expression) { return extractVariablesFromExpression(removeEverythingInParentheses(expression)); } public static String calculateCheckDigit(String id) { double sum = 0.00; char[] ch = new char[id.length()]; for (int i = 0; i < id.length(); i++) { ch[i] = id.toUpperCase().charAt(i); } List<Integer> numbers = new ArrayList<>(); for (char c : ch) { if (equivalentNumericalValues.containsKey(c)) { Integer num = equivalentNumericalValues.get(c); numbers.add(num); } } for (int i = 0; i < numbers.size(); i++) { sum = sum + numbers.get(i) * Math.pow(2, i); } if (Math.floorMod((int) sum, 11) != 10) { return String.valueOf(Math.floorMod((int) sum, 11)); } else { return "0"; } } }
package com.intrasoft.ermis.transit.management.core.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.management.core.service.lrn.LRNGeneratorSubService; import com.intrasoft.ermis.transit.management.core.service.lrn.LRNVariablesEnum; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Stream; import javax.xml.bind.JAXBException; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class LRNGeneratorSubServiceUT { private static final String NEW_LINE = System.getProperty("line.separator"); @Mock private GetCountryCodeService getCountryCodeService; @Mock private ErmisLogger ermisLogger; @InjectMocks LRNGeneratorSubService lrnGeneratorSubService; @ParameterizedTest @MethodSource("provideLrnFormulas") void testAssignmentOfLrn(String formula, String expectedLrn, int uidLength, int expectedLength) { try { CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C"), CC015CType.class); if (formula.contains(LRNVariablesEnum.COUNTRY_CODE.getDescription())) when(getCountryCodeService.getCountryCode()).thenReturn("DK"); String lrn = lrnGeneratorSubService.generateLrn(cc015CType, formula); String uidRegex = "^([a-zA-Z0-9]){<LENGTH>}$"; assertEquals(expectedLength, lrn.length()); assertTrue(lrn.contains(expectedLrn.replace("<ID>", ""))); assertTrue(lrn.substring(lrn.length() - uidLength).matches(uidRegex.replace("<LENGTH>", uidLength + ""))); } catch (JAXBException e) { System.exit(-1); } } private String loadTextFile(String messageType) { String filePath = "data/" + messageType + ".xml"; InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath); if (inputStream == null) { throw new NotFoundException("XML file [" + filePath + "] does not exist"); } StringBuilder result = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { for (String line; (line = reader.readLine()) != null; ) { result.append(NEW_LINE); result.append(line); } } catch (IOException e) { return ""; } return result.toString().replaceFirst(NEW_LINE, ""); } public static Stream<Arguments> provideLrnFormulas() { return Stream.of( Arguments.of("{DatePrep(yyyyMMdd)}{OfficeOfDeparture}{UniqueId(6)}", "20210614AA000000<ID>", 6, 22), Arguments.of("{OfficeOfDeparture}{DatePrep(yyyyMMdd)}{UniqueId(6)}", "AA00000020210614<ID>", 6, 22), Arguments.of("{OfficeOfDeparture}{DatePrep(yyMMddHHmmss)}{UniqueId(2)}", "AA000000210614131816<ID>", 2, 22), Arguments.of("{CountryCode}{OfficeOfDeparture}{DatePrep(yyMMddHHmm)}{UniqueId(2)}", "DKAA0000002106141318<ID>", 2, 22), Arguments.of("{CountryCode}-{OfficeOfDeparture}_{DatePrep(yyMMdd)}-重-{UniqueId(2)}", "DK-AA000000_210614-重-<ID>", 2, 23) ); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofexitfortransit.core.service; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.ProcessDefinitionEnum; import java.util.Map; import java.util.Objects; import lombok.AllArgsConstructor; import org.apache.commons.collections.map.HashedMap; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @AllArgsConstructor(onConstructor_ = {@Autowired}) public class BpmnFlowServiceImpl implements BpmnFlowService { private final ErmisLogger log; private final BpmnEngine bpmnEngine; private final RuntimeService runtimeService; @Override public void terminateProcess(String businessKey, String processDefinitionKey, String reason) { log.info("terminateProcess() on processDefinitionKey: [{}] and businessKey: [{}]", processDefinitionKey, businessKey); ProcessInstance processInstance = runtimeService.createProcessInstanceQuery() .processInstanceBusinessKey(businessKey) .processDefinitionKey(processDefinitionKey) .singleResult(); if (Objects.isNull(processInstance) || processInstance.isEnded()) { log.warn("terminateProcess() with businessKey: [{}] --> NO ACTIVE PROCESS FOUND", businessKey); return; } runtimeService.deleteProcessInstanceIfExists(processInstance.getProcessInstanceId(), reason, false, false, false, false); } @Override public void correlateMessage(String businessKey, String messageName) { log.info("correlateMessage() on messageType: [{}] and businessKey: [{}]", messageName, businessKey); CorrelateBpmnMessageCommand correlateBpmnMessageCommand = CorrelateBpmnMessageCommand .builder() .messageName(messageName) .businessKey(businessKey) .build(); bpmnEngine.correlateMessage(correlateBpmnMessageCommand); } @Override public void startProcess(ProcessDefinitionEnum processDefinition, String businessKey, Map<String, Object> processVariables) { log.info("startProcess() on processDefinitionKey: [{}] and businessKey: [{}]", processDefinition.getProcessDefinitionKey(), businessKey); Map<String, Object> finalVars = new HashedMap(); finalVars.put(BpmnFlowVariablesEnum.PROCESS_BUSINESS_KEY.getValue(), businessKey); finalVars.putAll(processVariables); bpmnEngine.createProcessInstanceByProcessId(processDefinition.getProcessDefinitionKey(), finalVars); } @Override public void correlateMessageWithValues(String businessKey, String messageName, Map<String, Object> values) { log.info("correlateMessageWithValues() on messageType : [{}] and businessKey: [{}]", messageName, businessKey); CorrelateBpmnMessageCommand correlateBpmnMessageCommand = CorrelateBpmnMessageCommand .builder() .messageName(messageName) .businessKey(businessKey) .values(values) .build(); bpmnEngine.correlateMessage(correlateBpmnMessageCommand); } }
package com.intrasoft.ermis.transit.officeofexitfortransit.service; import static java.util.Map.entry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.BpmnFlowServiceImpl; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.ProcessDefinitionEnum; import java.util.Map; import java.util.UUID; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; import org.camunda.bpm.extension.mockito.CamundaMockito; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class BpmnFlowServiceUT { @Mock private ErmisLogger ermisLogger; @Mock private BpmnEngine bpmnEngine; @Mock private RuntimeService runtimeService; @InjectMocks private BpmnFlowServiceImpl bpmnFlowService; @Captor private ArgumentCaptor<CorrelateBpmnMessageCommand> correlateBpmnMessageCommandArgumentCaptor; @Test @DisplayName("Test - Correlate Message with values") void testCorrelateMessageWithValues() { String businessKey = UUID.randomUUID().toString(); String messageName = "TEST_NAME"; Map<String, Object> values = Map.ofEntries( entry("TEST_KEY_1", "TEST_VALUE"), entry("TEST_KEY_2", true) ); try { // Call BpmnFlowService method: bpmnFlowService.correlateMessageWithValues(businessKey, messageName, values); // Verification & Assertions: verify(bpmnEngine, times(1)).correlateMessage(correlateBpmnMessageCommandArgumentCaptor.capture()); assertEquals(businessKey, correlateBpmnMessageCommandArgumentCaptor.getValue().getBusinessKey()); assertEquals(messageName, correlateBpmnMessageCommandArgumentCaptor.getValue().getMessageName()); assertEquals(values.keySet(), correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().keySet()); assertEquals(values.get("TEST_KEY_1"), correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().get("TEST_KEY_1")); assertEquals(values.get("TEST_KEY_2"), correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().get("TEST_KEY_2")); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Cancel Process Instance - EXISTS") void testCancelProcessInstanceExists() { String businessKey = UUID.randomUUID().toString(); String reason = "TEST_REASON"; // Stubs: // (Use ExecutionEntity to be able to set ProcessInstanceID, valid object as ProcessInstance extends it.) ExecutionEntity processInstance = new ExecutionEntity(); processInstance.setProcessInstanceId(UUID.randomUUID().toString()); when(runtimeService.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); final ProcessInstanceQuery processInstanceQuery = CamundaMockito.mockProcessInstanceQuery(runtimeService) .singleResult(processInstance); doNothing().when(runtimeService) .deleteProcessInstanceIfExists(anyString(), eq(reason), eq(false), eq(false), eq(false), eq(false)); try { // Call BpmnFlowService method: bpmnFlowService.terminateProcess(businessKey, ProcessDefinitionEnum.OOEXIT_FOR_TRANSIT_MAIN_PROCESS.getProcessDefinitionKey(), reason); // Verifications: verify(runtimeService, times(1)).createProcessInstanceQuery(); verify(processInstanceQuery).singleResult(); verify(runtimeService, times(1)) .deleteProcessInstanceIfExists(anyString(), eq(reason), eq(false), eq(false), eq(false), eq(false)); } catch (Exception e) { fail(); } } @Test @DisplayName("Test - Cancel Process Instance - NOT EXISTS") void testCancelProcessInstanceNotExists() { String businessKey = UUID.randomUUID().toString(); String reason = "TEST_REASON"; // Stubs: when(runtimeService.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); final ProcessInstanceQuery processInstanceQuery = CamundaMockito.mockProcessInstanceQuery(runtimeService) .singleResult(null); try { // Call BpmnFlowService method: bpmnFlowService.terminateProcess(businessKey, ProcessDefinitionEnum.OOEXIT_FOR_TRANSIT_MAIN_PROCESS.getProcessDefinitionKey(), reason); // Verifications: verify(runtimeService, times(1)).createProcessInstanceQuery(); verify(processInstanceQuery).singleResult(); verify(runtimeService, times(0)) .deleteProcessInstanceIfExists(anyString(), eq(reason), eq(false), eq(false), eq(false), eq(false)); } catch (Exception e) { fail(); } } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.control.service; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import com.intrasoft.ermis.transit.contracts.core.enums.RiskAnalysisCodeEnum; import com.intrasoft.ermis.transit.control.domain.DomainBase; import com.intrasoft.ermis.transit.control.domain.ExternalSystemResponseProperty; import com.intrasoft.ermis.transit.control.domain.Message; import com.intrasoft.ermis.transit.control.domain.MessageOverview; import com.intrasoft.ermis.transit.control.domain.Movement; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @AllArgsConstructor(onConstructor_ = {@Autowired}) public class ControlServiceImpl implements ControlService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String CTL_AUTOMATIC_RELEASE_DELAY_TIMER_RS = "getControlAutomaticReleaseDelayTimerRS"; private static final String RISK_FACTOR_CONFIG_RS = "getRiskFactorConfigRS"; private static final String CONTROL_DECISION_NOTIFICATION_ENABLED_RS = "getControlDecisionNotificationEnabledRS"; private static final String SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS = "getSendControlDecisionNotificationAutomaticallyEnabledRS"; private static final String DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS = "getDependOnRiskResponseForNotifyingDeclarantEnabledRS"; private static final String VALUE_LITERAL = "value"; public static final String GET_MANUAL_NO_CONTROL_BUTTONS_ENABLED_CONFIG_RS = "getManualNoControlButtonsEnabledConfigRS"; private TimerDelayExecutor timerDelayExecutor; private CustomControlTimerService customControlTimerService; private final ErmisLogger log; private final DossierDataService dossierDataService; private final ErmisConfigurationService ermisConfigurationService; @Override public TimerInfo getAutomaticReleaseTimerDelayConfig(String movementId) throws Exception { Movement movement = dossierDataService.getMovementById(movementId); TimerInfo timerInfo = null; if (movement != null) { String cc015cId = getCC015CIdFromMovement(movement); List<ExternalSystemResponseProperty> externalSystemResponsePropertyList = new ArrayList<>(dossierDataService.getExternalSystemResponsePropertyListByMessageId(cc015cId)); if (!externalSystemResponsePropertyList.isEmpty()) { // Check if there was a Custom Control Timer provided by Authorization Validation: timerInfo = customControlTimerService.getCustomTimerDelay(LocalDateTime.now(ZoneOffset.UTC), externalSystemResponsePropertyList, false).orElseThrow(() -> new BaseException("Failed to setup timer!")); } else { // If not, retrieve the Control Timer via Configuration: timerInfo = timerDelayExecutor.getTimerDelayConfig(LocalDateTime.now(ZoneOffset.UTC), LocalDateTime.now(), CTL_AUTOMATIC_RELEASE_DELAY_TIMER_RS, false).orElseThrow(() -> new BaseException("Failed to setup timer!")); } } return timerInfo; } @Override public boolean setNoControl(String movementId) { log.info("Set No Control for message with ID: {}", movementId); // Return "No Control". return false; } @Override public int getRiskFactor() { // Default riskFactor value if configuration is not found: int riskFactor = 60; try { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(RISK_FACTOR_CONFIG_RS); riskFactor = Integer.parseInt(configuration.getEvaluationParams().get("configuredRiskFactor")); } catch (NotFoundException e) { log.warn(e.getMessage().concat(". Defaulting to 60.")); } return riskFactor; } @Override public boolean isControlDecisionNotificationEnabled() { return isControlDecisionNotificationSwitchEnabled(); } @Override public boolean shouldSendControlDecisionNotificationAutomatically() { return isSendControlDecisionNotificationAutomaticallySwitchEnabled(); } @Override public boolean shouldSendNotificationToDeclarant(String movementId) { if (isDependOnRiskForNotifyingDeclarantSwitchEnabled()) { return shouldNotifyDeclarant(movementId); } else { // If switch is off, then IE060 should always be sent. return true; } } @Override public boolean mustCreateManualNoControlDecisionTask(String riskAnalysisCode) { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateNameAndApplicableParameter(GET_MANUAL_NO_CONTROL_BUTTONS_ENABLED_CONFIG_RS, OfficeRoleTypesEnum.DEPARTURE.getValue(), "office"); return Boolean.parseBoolean(configuration.getEvaluationParams().get(VALUE_LITERAL)) && RiskAnalysisCodeEnum.Z.getCode().equals(riskAnalysisCode); } private String getCC015CIdFromMovement(Movement movement) { String id = ""; if (movement != null) { List<Message> messages = dossierDataService.getMessagesByCriteria(movement.getId()); if (!messages.isEmpty()) { Optional<Message> retrievedMessage = messages.stream() .filter(message -> MessageTypes.CC_015_C.value().equals(message.getMessageType())) .findFirst(); if (retrievedMessage.isPresent()) { return retrievedMessage.get().getId(); } else { throw new BaseException("No message CC015C was found!"); } } else { throw new BaseException("No messages found associated with movement:" + movement.getId()); } } return id; } /** * Method holding switch logic to enable/disable Control Decision Notification (IE060). * * @return TRUE/FALSE based on found configuration template. */ private boolean isControlDecisionNotificationSwitchEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(CONTROL_DECISION_NOTIFICATION_ENABLED_RS); return Boolean.parseBoolean(configuration.getEvaluationParams().get(VALUE_LITERAL)); } /** * Method holding switch logic to enable/disable sending Control Decision Notification automatically (IE060). * * @return TRUE/FALSE based on found configuration template. */ private boolean isSendControlDecisionNotificationAutomaticallySwitchEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS); return Boolean.parseBoolean(configuration.getEvaluationParams().get(VALUE_LITERAL)); } /** * Method holding switch logic to enable/disable notification suppression. * * @return TRUE/FALSE based on found configuration template. */ private boolean isDependOnRiskForNotifyingDeclarantSwitchEnabled() { Configuration configuration = ermisConfigurationService.getConfigurationByTemplateName(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS); return Boolean.parseBoolean(configuration.getEvaluationParams().get(VALUE_LITERAL)); } /** * Method holding decision logic to notify Declarant (IE060) * <br/> based on latest response data from Risk Assessment. * * @param movementId ID of movement to retrieve risk assessment response of. * @return TRUE/FALSE based on data found within risk assessment response. */ private boolean shouldNotifyDeclarant(String movementId) { List<MessageOverview> riskAssessmentResponseMessageOverviewList = dossierDataService.getMessagesOverview(movementId, RiskAssessmentResponseEvent.class.getSimpleName()); Comparator<MessageOverview> messageOverviewComparator = Comparator.comparing(DomainBase::getCreatedDateTime); if (!riskAssessmentResponseMessageOverviewList.isEmpty()) { // Sort and reverse riskAssessmentResponseMessageOverviewList so the latest is on index[0]: riskAssessmentResponseMessageOverviewList.sort(messageOverviewComparator); Collections.reverse(riskAssessmentResponseMessageOverviewList); try { Message riskAssessmentResponseMessage = dossierDataService.getMessageById(riskAssessmentResponseMessageOverviewList.get(0).getId()); RiskAssessmentResponseEvent riskAssessmentResponseEvent = JSON_CONVERTER.convertStringToObject(riskAssessmentResponseMessage.getPayload(), RiskAssessmentResponseEvent.class); // If at least one (1) control instruction has involvesNotifyingDeclarant == FALSE, then suppress notification: return riskAssessmentResponseEvent.getRiskAssessmentResults() .stream() .takeWhile(riskAssessmentResult -> riskAssessmentResult.getControlInstructions() .stream() .anyMatch(controlInstruction -> Boolean.FALSE.equals(controlInstruction.isInvolvesNotifyingDeclarant()))) .findAny() .isEmpty(); } catch (Exception e) { // Default TRUE if an Exception was thrown for provided movement ID (non-interrupting exception handling): log.warn("Failed to retrieve Risk Assessment Response data for movementId: " + movementId + ". Defaulting to TRUE."); return true; } } else { // Default TRUE if no Risk Assessment Response Event Messages were found for provided movement ID: log.warn("shouldNotifyDeclarant(): No Risk Assessment Response Event Messages found. Defaulting to TRUE."); return true; } } }
package com.intrasoft.ermis.transit.control.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.ControlInstruction; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResult; import com.intrasoft.ermis.platform.shared.client.configuration.core.domain.Configuration; import com.intrasoft.ermis.transit.common.config.services.ErmisConfigurationService; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.control.domain.Message; import com.intrasoft.ermis.transit.control.domain.MessageOverview; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ControlServiceUT { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String CONTROL_DECISION_NOTIFICATION_ENABLED_RS = "getControlDecisionNotificationEnabledRS"; private static final String SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS = "getSendControlDecisionNotificationAutomaticallyEnabledRS"; private static final String DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS = "getDependOnRiskResponseForNotifyingDeclarantEnabledRS"; private static final String MOVEMENT_ID = UUID.randomUUID().toString(); private static final String LATEST_MESSAGE_ID = "MESSAGE_ID_0"; private static final int NUMBER_OF_MESSAGE_OVERVIEWS = 3; private static final int NUMBER_OF_RISK_ASSESSMENT_RESULTS = 2; private static final int NUMBER_OF_CONTROL_INSTRUCTIONS = 4; @Mock private ErmisLogger ermisLogger; @Mock private TimerDelayExecutor timerDelayExecutor; @Mock private CustomControlTimerService customControlTimerService; @Mock private DossierDataService dossierDataService; @Mock private ErmisConfigurationService ermisConfigurationService; @InjectMocks private ControlServiceImpl controlService; @ParameterizedTest @DisplayName("Test - Is Control Decision Notification Enabled") @ValueSource(strings = {"true", "false", "invalidParameter"}) void testIsControlDecisionNotificationEnabled(String valueParameter) { // Stubs: when(ermisConfigurationService.getConfigurationByTemplateName(CONTROL_DECISION_NOTIFICATION_ENABLED_RS)) .thenReturn(buildConfiguration(CONTROL_DECISION_NOTIFICATION_ENABLED_RS, valueParameter)); // Call tested service method: boolean returnedValue = controlService.isControlDecisionNotificationEnabled(); // Verifications & Assertions: verify(ermisConfigurationService, times(1)).getConfigurationByTemplateName(CONTROL_DECISION_NOTIFICATION_ENABLED_RS); if ("invalidParameter".equals(valueParameter)) { assertFalse(returnedValue); } else { assertEquals(Boolean.parseBoolean(valueParameter), returnedValue); } } @ParameterizedTest @DisplayName("Test - Should Send Control Decision Notification Automatically") @ValueSource(strings = {"true", "false", "invalidParameter"}) void testShouldSendControlDecisionNotificationAutomatically(String valueParameter) { // Stubs: when(ermisConfigurationService.getConfigurationByTemplateName(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS)) .thenReturn(buildConfiguration(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS, valueParameter)); // Call tested service method: boolean returnedValue = controlService.shouldSendControlDecisionNotificationAutomatically(); // Verifications & Assertions: verify(ermisConfigurationService, times(1)) .getConfigurationByTemplateName(SEND_CONTROL_DECISION_NOTIFICATION_AUTOMATICALLY_ENABLED_RS); if ("invalidParameter".equals(valueParameter)) { assertFalse(returnedValue); } else { assertEquals(Boolean.parseBoolean(valueParameter), returnedValue); } } @ParameterizedTest @DisplayName("Test - Should Send Notification To Declarant") @CsvSource({"true,true", "true,false", "false,true", "false,false",}) void testShouldSendNotificationToDeclarant(boolean switchEnabled, boolean suppressNotification) { // Stubs: when(ermisConfigurationService.getConfigurationByTemplateName(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS)) .thenReturn(buildConfiguration(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS, String.valueOf(switchEnabled))); if (switchEnabled) { when(dossierDataService.getMessagesOverview(MOVEMENT_ID, RiskAssessmentResponseEvent.class.getSimpleName())) .thenReturn(buildMessageOverviewList()); when(dossierDataService.getMessageById(LATEST_MESSAGE_ID)) .thenReturn(buildMessage(suppressNotification)); } // Call tested service method: boolean returnedValue = controlService.shouldSendNotificationToDeclarant(MOVEMENT_ID); // Verifications & Assertions: verify(ermisConfigurationService, times(1)).getConfigurationByTemplateName(DEPEND_ON_RISK_RESPONSE_FOR_NOTIFYING_DECLARANT_ENABLED_RS); if (switchEnabled) { // If switch is enabled, further REST calls should be made: verify(dossierDataService, times(1)).getMessagesOverview(MOVEMENT_ID, RiskAssessmentResponseEvent.class.getSimpleName()); verify(dossierDataService, times(1)).getMessageById(LATEST_MESSAGE_ID); // If at least one involvesNotifyingDeclarant within control instructions is found FALSE, suppress notification: if (suppressNotification) { assertFalse(returnedValue); } else { assertTrue(returnedValue); } } else { // If switch is disabled, no further REST calls should be made and should notify declarant: verify(dossierDataService, times(0)).getMessagesOverview(MOVEMENT_ID, RiskAssessmentResponseEvent.class.getSimpleName()); verify(dossierDataService, times(0)).getMessageById(LATEST_MESSAGE_ID); assertTrue(returnedValue); } } private Configuration buildConfiguration(String ruleTemplate, String value) { return new Configuration( ruleTemplate, "ruleCode", new HashMap<>(), Map.of("value", value), "errorCode", LocalDateTime.now(ZoneOffset.UTC), LocalDateTime.now(ZoneOffset.UTC).minusDays(60), LocalDateTime.now(ZoneOffset.UTC).plusDays(60)); } private List<MessageOverview> buildMessageOverviewList() { List<MessageOverview> messageOverviewList = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_MESSAGE_OVERVIEWS; i++) { MessageOverview messageOverview = MessageOverview.builder() .id("MESSAGE_ID_" + i) .messageType(RiskAssessmentResponseEvent.class.getSimpleName()) .createdDateTime(LocalDateTime.now(ZoneOffset.UTC).minusDays(i)) .build(); messageOverviewList.add(messageOverview); } return messageOverviewList; } private Message buildMessage(boolean suppressNotification) { Message message = new Message(); RiskAssessmentResponseEvent riskAssessmentResponseEvent = new RiskAssessmentResponseEvent(); riskAssessmentResponseEvent.setRiskAssessmentResults(new ArrayList<>()); riskAssessmentResponseEvent.getRiskAssessmentResults().addAll(buildRiskAssessmentResultList(suppressNotification)); message.setMessageIdentification(LATEST_MESSAGE_ID); message.setMessageType(RiskAssessmentResponseEvent.class.getSimpleName()); message.setPayload(JSON_CONVERTER.convertToJsonString(riskAssessmentResponseEvent)); return message; } private List<RiskAssessmentResult> buildRiskAssessmentResultList(boolean suppressNotification) { List<RiskAssessmentResult> riskAssessmentResultList = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_RISK_ASSESSMENT_RESULTS; i++) { RiskAssessmentResult riskAssessmentResult = new RiskAssessmentResult(); for (int j = 0; j < NUMBER_OF_CONTROL_INSTRUCTIONS; j++) { ControlInstruction controlInstruction = new ControlInstruction(); controlInstruction.setInvolvesNotifyingDeclarant(true); riskAssessmentResult.getControlInstructions().add(controlInstruction); } riskAssessmentResultList.add(riskAssessmentResult); } if (suppressNotification) { riskAssessmentResultList.get(0).getControlInstructions().get(0).setInvolvesNotifyingDeclarant(false); } return riskAssessmentResultList; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofexitfortransit.core.service; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.contracts.core.dto.declaration.common.CustomsDataPayloadContentTypeEnum; import com.intrasoft.ermis.contracts.core.dto.declaration.common.RegimeEnum; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentRequestEvent; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.ddntav5152.messages.RiskAnalysisIdentificationType; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.common.mappers.RiskAnalysisMapper; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.common.util.RandomUtil; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import com.intrasoft.ermis.transit.contracts.core.enums.RiskAnalysisCodeEnum; import com.intrasoft.ermis.transit.officeofexitfortransit.core.configuration.OfficeOfExitForTransitDDNTASpecificationConfigurationProperties; import com.intrasoft.ermis.transit.officeofexitfortransit.core.outbound.RiskAssessmentRequestEventProducer; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.CustomsDataDomain; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Movement; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.RiskResult; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.events.RiskAssessmentRequestDomainEvent; import java.math.BigInteger; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class RiskAssessmentServiceImpl implements RiskAssessmentService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String NOT_AVAILABLE = "NOT_AVAILABLE"; private static final String RISK_ASSESSMENT_DESTINATION = "RISK_ASSESSMENT"; private static final String RANDOM_RISK_ASSESSMENT = "RANDOM_RISK_ASSESSMENT"; private static final String OOEXIT_FOR_TRANSIT_RISK_ANALYSIS_DELAY_TIMER_RS = "getOoExitForTransitRiskAnalysisDelayTimerRS"; private static final int MIN_RISK = 1; private static final int MAX_RISK = 100; private final ErmisLogger log; private final BpmnFlowService bpmnFlowService; private final DossierDataService dossierDataService; private final RiskAssessmentRequestEventProducer riskAssessmentRequestEventProducer; private final RiskAnalysisMapper riskAnalysisMapper; private final TimerDelayExecutor timerDelayExecutor; private final OfficeOfExitForTransitDDNTASpecificationConfigurationProperties specificationConfigurationProperties; private final GetCountryCodeService getCountryCodeService; @Override public void sendRiskAssessmentRequest(String processBusinessKey, String movementId, String... messageIds) { log.info("ENTER sendRiskAssessmentRequest()"); if (Objects.isNull(messageIds)) { throw new BaseException("No messageIds provided for Risk Assessment!"); } // Risk Assessment was either triggered by IE160 OR IE165. The trigger-message will have an ID of !NOT_AVAILABLE. List<Message> messageList = Arrays.stream(messageIds) .filter(messageId -> !(NOT_AVAILABLE.equals(messageId))) .map(messageId -> Objects.requireNonNull(dossierDataService.getMessageById(messageId))) .collect(Collectors.toList()); if (!messageList.isEmpty()) { // Retrieve Movement: Movement movement = dossierDataService.getMovementById(movementId); // Use a stream index for each customsDataDomainMessage sequenceNumber: List<CustomsDataDomain> customsDataDomainList = IntStream.range(0, messageList.size()) .mapToObj(index -> createCustomsDataDomainMessage(messageList.get(index), BigInteger.valueOf(++index))) .collect(Collectors.toList()); // Add movementId to CustomsData: customsDataDomainList.add(createMovementIdCustomsDataRecord(movementId, BigInteger.valueOf(customsDataDomainList.size() + 1L))); // Add acceptanceDateTime to CustomsData: customsDataDomainList.add(createAcceptanceDateTimeCustomsDataRecord(movement.getAcceptanceDateTime(), BigInteger.valueOf(customsDataDomainList.size() + 1L))); String mrn = movement.getMrn(); RiskAssessmentRequestDomainEvent requestDomainEvent = RiskAssessmentRequestDomainEvent .builder() .requestId(MessageUtil.generateMessageIdentification()) .requestDateTime(LocalDateTime.now(ZoneOffset.UTC)) .regime(RegimeEnum.TRANSIT.getCode()) .processKey(mrn) .processVersion("1") .correlationKey(movementId) // correlationKey will match processBusinessKey == movementId .customsData(new HashSet<>(customsDataDomainList)) .build(); persistRiskAssessmentRequestMessage(movementId, requestDomainEvent, messageList.get(0).getDestination()); riskAssessmentRequestEventProducer.publish(requestDomainEvent); log.info("EXIT sendRiskAssessmentRequest()"); } else { throw new BaseException("No Messages were found for provided IDs!"); } } @Override public void onRiskAssessmentResponseReceived(String movementId, String messageId) { log.info("ENTER onRiskAssessmentResponseReceived()"); Message message = dossierDataService.getMessageById(messageId); // Create processVariables map. Map<String, Object> processVariables = new HashMap<>(); processVariables.put(BpmnFlowVariablesEnum.RISK_ASSESSMENT_RESPONSE_ID.getValue(), messageId); if (message != null) { bpmnFlowService.correlateMessageWithValues(movementId, BpmnFlowMessagesEnum.RISK_ASSESSMENT_RESPONSE_MESSAGE.getValue(), processVariables); } else { throw new BaseException("Could not find Risk Assessment Message!"); } log.info("EXIT onRiskAssessmentResponseReceived()"); } @Override public RiskResult assignRiskFactor(String movementId, String riskAssessmentResponseId) { log.info("ENTER assignRiskFactor()"); Message riskResponseMessage = dossierDataService.getMessageById(riskAssessmentResponseId); RiskAssessmentResponseEvent riskAssessmentResponseEvent = JSON_CONVERTER.convertStringToObject(riskResponseMessage.getPayload(), RiskAssessmentResponseEvent.class); RiskResult riskResult = RiskResult.builder() .movementId(movementId) .overallRiskResult(riskAssessmentResponseEvent.getTotalScore().intValue()) .riskAnalysis(JSON_CONVERTER.convertToJsonString( riskAnalysisMapper.toRiskAnalysisIdentification(riskAssessmentResponseEvent))) .build(); dossierDataService.saveRiskResult(riskResult); log.info("EXIT assignRiskFactor()"); return riskResult; } @Override public TimerInfo getRiskAnalysisTimerDelayConfig() { return timerDelayExecutor.getTimerDelayConfig(LocalDateTime.now(ZoneOffset.UTC), LocalDateTime.now(ZoneOffset.UTC), OOEXIT_FOR_TRANSIT_RISK_ANALYSIS_DELAY_TIMER_RS, false).orElseThrow(() -> new BaseException("Failed to setup risk analysis timer!")); } @Override public RiskResult assignRandomRiskFactor(String movementId) { Movement movement = dossierDataService.getMovementById(movementId); log.info("ENTER assignRandomRiskFactor()"); RiskResult riskResult = RiskResult.builder() .movementId(movementId) .overallRiskResult(generateRandomRiskFactor()) .riskAnalysis(JSON_CONVERTER.convertToJsonString(assignRandomRiskCode())) .build(); dossierDataService.saveRiskResult(riskResult); handleRandomRiskResultActions(riskResult.getOverallRiskResult(), movement); log.info("EXIT assignRandomRiskFactor()"); return riskResult; } @Override public void forwardMessageToRiskAnalysisSystem(String movementId, String messageId) { log.info("ENTER forwardMessageToRiskAnalysisSystem()"); // Verify the Message exists: Message message = dossierDataService.getMessageById(messageId); if (message != null) { // Retrieve Movement: Movement movement = dossierDataService.getMovementById(movementId); Set<CustomsDataDomain> customsDataDomainSet = new HashSet<>(); // Only IE181 will be included in the request, so sequenceNumber == 1. customsDataDomainSet.add(createCustomsDataDomainMessage(message, BigInteger.ONE)); // Add movementId to CustomsData: customsDataDomainSet.add(createMovementIdCustomsDataRecord(movementId, BigInteger.valueOf(customsDataDomainSet.size() + 1L))); // Add acceptanceDateTime to CustomsData: customsDataDomainSet.add(createAcceptanceDateTimeCustomsDataRecord(movement.getAcceptanceDateTime(), BigInteger.valueOf(customsDataDomainSet.size() + 1L))); String mrn = movement.getMrn(); RiskAssessmentRequestDomainEvent requestDomainEvent = RiskAssessmentRequestDomainEvent .builder() .requestId(MessageUtil.generateMessageIdentification()) .requestDateTime(LocalDateTime.now(ZoneOffset.UTC)) .regime(RegimeEnum.TRANSIT.getCode()) .processKey(mrn) .processVersion("1") .customsData(customsDataDomainSet) .correlationKey(movementId) .build(); persistRiskAssessmentRequestMessage(movementId, requestDomainEvent, message.getDestination()); riskAssessmentRequestEventProducer.publish(requestDomainEvent); log.info("EXIT forwardMessageToRiskAnalysisSystem()"); } else { throw new BaseException("No Messages were found for provided ID!"); } } private CustomsDataDomain createCustomsDataDomainMessage(Message message, BigInteger sequenceNumber) { return CustomsDataDomain.builder() .sequenceNumber(sequenceNumber) .type(message.getMessageType()) .payload(message.getPayload()) .payloadType(CustomsDataPayloadContentTypeEnum.XML.name()) .payloadSpec(specificationConfigurationProperties.getDDNTASpecification()) .build(); } private CustomsDataDomain createMovementIdCustomsDataRecord(String movementId, BigInteger sequenceNumber) { return CustomsDataDomain.builder() .sequenceNumber(sequenceNumber) .type("MOVEMENT_ID") .payload(movementId) .payloadType(CustomsDataPayloadContentTypeEnum.STRING.name()) .build(); } private CustomsDataDomain createAcceptanceDateTimeCustomsDataRecord(LocalDateTime acceptanceDateTime, BigInteger sequenceNumber) { return CustomsDataDomain.builder() .sequenceNumber(sequenceNumber) .type("ACCEPTANCE_DATE_TIME") .payload(JSON_CONVERTER.convertToJsonString(acceptanceDateTime)) .payloadType(CustomsDataPayloadContentTypeEnum.JSON.name()) .build(); } private void persistRiskAssessmentRequestMessage(String movementId, RiskAssessmentRequestDomainEvent requestDomainEvent, String source) { Message message = Message.builder() .messageIdentification(requestDomainEvent.getRequestId()) .messageType(RiskAssessmentRequestEvent.class.getSimpleName()) .source(source) .destination(RISK_ASSESSMENT_DESTINATION) .domain(MessageDomainTypeEnum.ERMIS.name()) .payload(JSON_CONVERTER.convertToJsonString(requestDomainEvent)) .direction(DirectionEnum.SENT.getDirection()) .build(); Message savedMessage = dossierDataService.saveMessage(message); dossierDataService.associateMessageWithMovement(savedMessage.getId(), movementId); } private Integer generateRandomRiskFactor() { return RandomUtil.generateSecureRandomInt(MIN_RISK, MAX_RISK); } private RiskAnalysisIdentificationType assignRandomRiskCode() { RiskAnalysisIdentificationType riskAnalysisIdentificationType = new RiskAnalysisIdentificationType(); riskAnalysisIdentificationType.setCode(RiskAnalysisCodeEnum.Z.getCode()); return riskAnalysisIdentificationType; } /** * Creates, persists and associates a RiskAssessmentResponseEvent for Random Risk. * * @param riskResultScore Total Score to be used in RiskAssessmentResponseEvent. * @param movement Movement to associate with and retrieve MRN from. */ private void handleRandomRiskResultActions(Integer riskResultScore, Movement movement) { // Create RiskAssessmentResponseEvent for Random Risk: RiskAssessmentResponseEvent riskAssessmentResponseEvent = new RiskAssessmentResponseEvent(); riskAssessmentResponseEvent.setCode(RiskAnalysisCodeEnum.Z.getCode()); riskAssessmentResponseEvent.setTotalScore(BigInteger.valueOf(riskResultScore)); riskAssessmentResponseEvent.setRegime(RegimeEnum.TRANSIT.getCode()); // Redundant - identifying data fields: riskAssessmentResponseEvent.setProcessKey(movement.getMrn()); riskAssessmentResponseEvent.setProcessVersion(String.valueOf(BigInteger.ONE)); riskAssessmentResponseEvent.setRiskAssessmentResults(new ArrayList<>()); // Create Message: Message message = Message.builder() .messageIdentification(MessageUtil.generateMessageIdentification()) .messageType(RiskAssessmentResponseEvent.class.getSimpleName()) .source(RANDOM_RISK_ASSESSMENT) .destination(MessageTypeMapper.NTA + getCountryCodeService.getCountryCode()) .domain(MessageDomainTypeEnum.ERMIS.name()) .payload(JSON_CONVERTER.convertToJsonString(riskAssessmentResponseEvent)) .direction(DirectionEnum.RECEIVED.getDirection()) .build(); // Persist and Associate: Message savedMessage = dossierDataService.saveMessage(message); dossierDataService.associateMessageWithMovement(savedMessage.getId(), movement.getId()); } }
package com.intrasoft.ermis.transit.officeofexitfortransit.service; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createIE160Message; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createIE165Message; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createIE181Message; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createRiskAssessmentResponseEvent; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.generateRandomMRN; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.Stubs.stubSaveMessage; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.contracts.core.dto.declaration.common.CustomsDataPayloadContentTypeEnum; import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent; import com.intrasoft.ermis.ddntav5152.messages.CD160CType; import com.intrasoft.ermis.ddntav5152.messages.CD165CType; import com.intrasoft.ermis.ddntav5152.messages.CD181CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.mappers.RiskAnalysisMapper; import com.intrasoft.ermis.transit.common.mappers.RiskAnalysisMapperImpl; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import com.intrasoft.ermis.transit.officeofexitfortransit.core.configuration.OfficeOfExitForTransitDDNTASpecificationConfigurationProperties; import com.intrasoft.ermis.transit.officeofexitfortransit.core.outbound.RiskAssessmentRequestEventProducer; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.BpmnFlowService; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.DossierDataService; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.RiskAssessmentServiceImpl; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.CustomsDataDomain; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Movement; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.RiskResult; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.events.RiskAssessmentRequestDomainEvent; import java.math.BigInteger; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Map; import java.util.Optional; import java.util.UUID; import org.apache.commons.lang3.Range; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class RiskAssessmentServiceUT { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private static final String NOT_AVAILABLE = "NOT_AVAILABLE"; private static final String OOEXIT_FOR_TRANSIT_RISK_ANALYSIS_DELAY_TIMER_RS = "getOoExitForTransitRiskAnalysisDelayTimerRS"; private static final int MIN_RISK = 1; private static final int MAX_RISK = 100; private final String MOVEMENT_ID = UUID.randomUUID().toString(); private final String MRN = generateRandomMRN(); @Mock private ErmisLogger ermisLogger; @Mock private DossierDataService dossierDataService; @Mock private TimerDelayExecutor timerDelayExecutor; @Mock private BpmnFlowService bpmnFlowService; @Mock private RiskAssessmentRequestEventProducer riskAssessmentRequestEventProducer; @Mock private GetCountryCodeService getCountryCodeService; @Spy private OfficeOfExitForTransitDDNTASpecificationConfigurationProperties properties; @Spy private RiskAnalysisMapper riskAnalysisMapper = new RiskAnalysisMapperImpl(); @Spy @InjectMocks private RiskAssessmentServiceImpl riskAssessmentService; @Captor private ArgumentCaptor<String> businessKeyArgumentCaptor; @Captor private ArgumentCaptor<String> messageNameArgumentCaptor; @Captor private ArgumentCaptor<Map<String, Object>> valueMapArgumentCaptor; @Captor private ArgumentCaptor<RiskAssessmentRequestDomainEvent> riskAssessmentRequestDomainEventArgumentCaptor; @ParameterizedTest @ValueSource(strings = {"CD160C", "CD165C"}) @DisplayName("Test - Send Risk Assessment Request") void testSendRiskAssessmentRequest(String messageType) { System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); // Test data: Movement mockMovement = createMovement(); // Mocks: Message message = createMessage(messageType, MRN); CustomsDataDomain customsDataDomain = createCustomsDataDomainMessage(message); CustomsDataDomain movementIdCustomsDataDomain = createCustomsDataMovementId(MOVEMENT_ID); CustomsDataDomain acceptanceDateTimeCustomsDataDomain = createCustomsDataAcceptanceDateTime(mockMovement.getAcceptanceDateTime()); when(dossierDataService.getMessageById(messageType)).thenReturn(message); when(dossierDataService.saveMessage(any())).thenAnswer(stubSaveMessage()); when(dossierDataService.getMovementById(any())).thenReturn(mockMovement); doNothing().when(dossierDataService).associateMessageWithMovement(anyString(), eq(MOVEMENT_ID)); // Call Risk Assessment Service method: riskAssessmentService.sendRiskAssessmentRequest(MOVEMENT_ID, MOVEMENT_ID, NOT_AVAILABLE, messageType); // Verification & Assertions: verify(riskAssessmentRequestEventProducer, times(1)).publish(riskAssessmentRequestDomainEventArgumentCaptor.capture()); assertEquals(MRN, riskAssessmentRequestDomainEventArgumentCaptor.getValue().getProcessKey()); assertEquals(3, riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().size()); assertTrue(riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().contains(customsDataDomain)); assertTrue(riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().contains(movementIdCustomsDataDomain)); assertTrue(riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().contains(acceptanceDateTimeCustomsDataDomain)); } @Test @DisplayName("Test - On Risk Assessment Received") void testOnRiskAssessmentReceived() { System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); String messageType = RiskAssessmentResponseEvent.class.getSimpleName(); // Mocks: Message message = createMessage(messageType, null); when(dossierDataService.getMessageById(messageType)).thenReturn(message); // Call Risk Assessment Service method: riskAssessmentService.onRiskAssessmentResponseReceived(MOVEMENT_ID, messageType); // Verifications & Assertions: verify(bpmnFlowService, times(1)).correlateMessageWithValues( businessKeyArgumentCaptor.capture(), messageNameArgumentCaptor.capture(), valueMapArgumentCaptor.capture()); assertEquals(MOVEMENT_ID, businessKeyArgumentCaptor.getValue()); assertEquals(BpmnFlowMessagesEnum.RISK_ASSESSMENT_RESPONSE_MESSAGE.getValue(), messageNameArgumentCaptor.getValue()); assertEquals(1, valueMapArgumentCaptor.getValue().size()); assertEquals(messageType, valueMapArgumentCaptor.getValue().get(BpmnFlowVariablesEnum.RISK_ASSESSMENT_RESPONSE_ID.getValue())); } @Test @DisplayName("Test - Assign Risk Factor") void testAssignRiskFactor() { System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); String messageType = RiskAssessmentResponseEvent.class.getSimpleName(); // Mocks: Message message = createMessage(messageType, null); when(dossierDataService.getMessageById(messageType)).thenReturn(message); doNothing().when(dossierDataService).saveRiskResult(any()); // Call Risk Assessment Service method: RiskResult riskResult = riskAssessmentService.assignRiskFactor(MOVEMENT_ID, messageType); // Assertions: assertEquals(BigInteger.valueOf(65), BigInteger.valueOf(riskResult.getOverallRiskResult())); } @Test @DisplayName("Test - Get Risk Analysis Timer Delay Config") void testGetRiskAnalysisTimerDelayConfig() { // Mock: when(timerDelayExecutor.getTimerDelayConfig(any(), any(), eq(OOEXIT_FOR_TRANSIT_RISK_ANALYSIS_DELAY_TIMER_RS), anyBoolean())) .thenReturn(Optional.of(new TimerInfo())); // Call Risk Assessment Service method: riskAssessmentService.getRiskAnalysisTimerDelayConfig(); // Assertions: verify(timerDelayExecutor, times(1)).getTimerDelayConfig(any(), any(), eq(OOEXIT_FOR_TRANSIT_RISK_ANALYSIS_DELAY_TIMER_RS), anyBoolean()); } @Test @DisplayName("Test - Assign Random Risk Factor") void testAssignRandomRiskFactor() { Range<Integer> riskFactorRange = Range.between(MIN_RISK, MAX_RISK); Movement mockMovement = createMovement(); // Mocks: when(dossierDataService.getMovementById(any())).thenReturn(mockMovement); doNothing().when(dossierDataService).saveRiskResult(any()); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(dossierDataService.saveMessage(any())).thenAnswer(stubSaveMessage()); doNothing().when(dossierDataService).associateMessageWithMovement(anyString(), eq(MOVEMENT_ID)); // Call Risk Assessment Service method: RiskResult riskResult = riskAssessmentService.assignRandomRiskFactor(MOVEMENT_ID); // Assertions: assertTrue(riskFactorRange.contains(riskResult.getOverallRiskResult())); } @Test @DisplayName("Test - Forward Message To Risk Analysis System") void testForwardMessageToRiskAnalysisSystem() { System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); // Test data: String messageType = MessageTypes.CD_181_C.value(); Movement mockMovement = createMovement(); // Mocks: Message message = createMessage(messageType, MRN); CustomsDataDomain customsDataDomain = createCustomsDataDomainMessage(message); CustomsDataDomain movementIdCustomsDataDomain = createCustomsDataMovementId(MOVEMENT_ID); CustomsDataDomain acceptanceDateTimeCustomsDataDomain = createCustomsDataAcceptanceDateTime(mockMovement.getAcceptanceDateTime()); when(dossierDataService.getMessageById(messageType)).thenReturn(message); when(dossierDataService.saveMessage(any())).thenAnswer(stubSaveMessage()); when(dossierDataService.getMovementById(any())).thenReturn(mockMovement); doNothing().when(dossierDataService).associateMessageWithMovement(anyString(), eq(MOVEMENT_ID)); // Call Risk Assessment Service method: riskAssessmentService.forwardMessageToRiskAnalysisSystem(MOVEMENT_ID, messageType); // Verification & Assertions: verify(riskAssessmentRequestEventProducer, times(1)).publish(riskAssessmentRequestDomainEventArgumentCaptor.capture()); assertEquals(MRN, riskAssessmentRequestDomainEventArgumentCaptor.getValue().getProcessKey()); assertEquals(3, riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().size()); assertTrue(riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().contains(customsDataDomain)); assertTrue(riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().contains(movementIdCustomsDataDomain)); assertTrue(riskAssessmentRequestDomainEventArgumentCaptor.getValue().getCustomsData().contains(acceptanceDateTimeCustomsDataDomain)); } private Message createMessage(String messageType, String mrn) { Message message = new Message(); if (MessageTypes.CD_160_C.value().equals(messageType)) { CD160CType cd160TypeMessage = createIE160Message(mrn); message.setPayload(XmlConverter.marshal(cd160TypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CD_160_C.value())); } else if (MessageTypes.CD_165_C.value().equals(messageType)) { CD165CType cd165TypeMessage = createIE165Message(mrn); message.setPayload(XmlConverter.marshal(cd165TypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CD_165_C.value())); } else if (RiskAssessmentResponseEvent.class.getSimpleName().equals(messageType)) { RiskAssessmentResponseEvent responseEvent = createRiskAssessmentResponseEvent(); message.setPayload(JSON_CONVERTER.convertToJsonString(responseEvent)); } else if (MessageTypes.CD_181_C.value().equals(messageType)) { CD181CType cd181TypeMessage = createIE181Message(); message.setPayload(XmlConverter.marshal(cd181TypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CD_181_C.value())); } else { throw new BaseException("Incorrect messageType provided in test!"); } return message; } private CustomsDataDomain createCustomsDataDomainMessage(Message message) { return CustomsDataDomain.builder() .sequenceNumber(BigInteger.ONE) .type(message.getMessageType()) .payload(message.getPayload()) .payloadType("XML") .build(); } private CustomsDataDomain createCustomsDataMovementId(String movementId) { return CustomsDataDomain.builder() .sequenceNumber(BigInteger.valueOf(2)) .type("MOVEMENT_ID") .payload(movementId) .payloadType(CustomsDataPayloadContentTypeEnum.STRING.name()) .build(); } private CustomsDataDomain createCustomsDataAcceptanceDateTime(LocalDateTime acceptanceDateTime) { return CustomsDataDomain.builder() .sequenceNumber(BigInteger.valueOf(3)) .type("ACCEPTANCE_DATE_TIME") .payload(JSON_CONVERTER.convertToJsonString(acceptanceDateTime)) .payloadType(CustomsDataPayloadContentTypeEnum.JSON.name()) .build(); } private Movement createMovement() { return Movement.builder().id(MOVEMENT_ID).acceptanceDateTime(LocalDateTime.now(ZoneOffset.UTC)).mrn(MRN).build(); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import java.time.LocalDateTime; import java.time.ZoneOffset; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class TimerSetupServiceImpl implements TimerSetupService { private static final String CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS = "getCargoAutomaticAcceptanceTimerDelayRS"; private static final String CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS = "getCargoArrivalPresentationTimerDelayRS"; private final DossierDataService dossierDataService; private final TimerDelayExecutor timerDelayExecutor; @Override public String getAutomaticAcceptanceTimerDelaySetupString(String movementId) throws BaseException { try { Movement movement = dossierDataService.getMovementById(movementId); return getTimerInfo(movement.getCreatedDateTime(), CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS).getTimerSetupString(); } catch (NotFoundException exception) { throw new BaseException("Failed to retrieve Movement with ID: " + movementId); } } @Override public String getArrivalPresentationTimerDelaySetupString(String movementId) throws BaseException { try { Movement movement = dossierDataService.getMovementById(movementId); return getTimerInfo(movement.getCreatedDateTime(), CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS).getTimerSetupString(); } catch (NotFoundException exception) { throw new BaseException("Failed to retrieve Movement with ID: " + movementId); } } private TimerInfo getTimerInfo(LocalDateTime date, String ruleSet) throws BaseException { return timerDelayExecutor.getTimerDelayConfig(date, LocalDateTime.now(ZoneOffset.UTC), ruleSet, false) .orElseThrow(() -> new BaseException("Failed to set up timer from ruleset: " + ruleSet)); } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.TimerSetupServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.test.util.TestDataUtilities; import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor; import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo; import com.intrasoft.ermis.transit.contracts.core.enums.TimeUnitEnum; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class TimerSetupServiceUT { private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID"; private static final String CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS = "getCargoAutomaticAcceptanceTimerDelayRS"; private static final String CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS = "getCargoArrivalPresentationTimerDelayRS"; @Mock private DossierDataService dossierDataService; @Mock private TimerDelayExecutor timerDelayExecutor; @InjectMocks private TimerSetupServiceImpl timerSetupService; @ParameterizedTest @DisplayName("Test - Get Automatic Acceptance Timer Delay Setup String") @ValueSource(strings = {"seconds", "minutes", "hours", "days"}) void testGetAutomaticAcceptanceTimerDelaySetupString(String delayUnit) { TimerInfo testTimerInfo = createTimerInfo(CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS, delayUnit); // Stubs/mocks: when(dossierDataService.getMovementById(MOVEMENT_ID)).thenReturn(TestDataUtilities.createMovement(MOVEMENT_ID)); when(timerDelayExecutor.getTimerDelayConfig(any(), any(), eq(CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS), anyBoolean())).thenReturn(Optional.of(testTimerInfo)); // Call TimerSetupService method: String returnedValue = timerSetupService.getAutomaticAcceptanceTimerDelaySetupString(MOVEMENT_ID); // Verifications & Assertions: verify(dossierDataService).getMovementById(MOVEMENT_ID); verify(timerDelayExecutor).getTimerDelayConfig(any(), any(), eq(CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS), anyBoolean()); assertEquals(testTimerInfo.getTimerSetupString(), returnedValue); switch (delayUnit) { case "seconds": assertEquals("PT5S", returnedValue); break; case "minutes": assertEquals("PT5M", returnedValue); break; case "hours": assertEquals("PT5H", returnedValue); break; case "days": assertEquals("P5D", returnedValue); break; } } @ParameterizedTest @DisplayName("Test - Get Arrival Presentation Timer Delay Setup String") @ValueSource(strings = {"seconds", "minutes", "hours", "days"}) void testGetArrivalPresentationTimerDelaySetupString(String delayUnit) { TimerInfo testTimerInfo = createTimerInfo(CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS, delayUnit); // Stubs/mocks: when(dossierDataService.getMovementById(MOVEMENT_ID)).thenReturn(TestDataUtilities.createMovement(MOVEMENT_ID)); when(timerDelayExecutor.getTimerDelayConfig(any(), any(), eq(CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS), anyBoolean())).thenReturn(Optional.of(testTimerInfo)); // Call TimerSetupService method: String returnedValue = timerSetupService.getArrivalPresentationTimerDelaySetupString(MOVEMENT_ID); // Verifications & Assertions: verify(dossierDataService).getMovementById(MOVEMENT_ID); verify(timerDelayExecutor).getTimerDelayConfig(any(), any(), eq(CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS), anyBoolean()); assertEquals(testTimerInfo.getTimerSetupString(), returnedValue); switch (delayUnit) { case "seconds": assertEquals("PT5S", returnedValue); break; case "minutes": assertEquals("PT5M", returnedValue); break; case "hours": assertEquals("PT5H", returnedValue); break; case "days": assertEquals("P5D", returnedValue); break; } } private TimerInfo createTimerInfo(String ruleSet, String delayUnit) { TimerInfo testTimerInfo = new TimerInfo(); testTimerInfo.setRuleInstance(ruleSet); testTimerInfo.setErrorCode("TEST_CODE"); testTimerInfo.setDelay(5); switch (delayUnit) { case "seconds": testTimerInfo.setUnit(TimeUnitEnum.SECONDS); break; case "minutes": testTimerInfo.setUnit(TimeUnitEnum.MINUTES); break; case "hours": testTimerInfo.setUnit(TimeUnitEnum.HOURS); break; case "days": testTimerInfo.setUnit(TimeUnitEnum.DAYS); break; } return testTimerInfo; } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.config.services.MRNFormulaConfigurationService; import com.intrasoft.ermis.transit.common.config.services.MRNGenerationService; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import java.time.LocalDateTime; import java.time.ZoneOffset; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class MRNAllocationServiceImpl implements MRNAllocationService { private final ErmisLogger logger; private final DossierDataService dossierDataService; private final GetCountryCodeService getCountryCodeService; private final MRNFormulaConfigurationService mrnFormulaConfigurationService; private final MRNGenerationService mrnGenerationService; @Override public String allocateMRN(String movementId) { Movement movement; String mrn; String countryCode = getCountryCodeService.getCountryCode(); try { movement = dossierDataService.getMovementById(movementId); String expression = mrnFormulaConfigurationService.retrieveTransitMrnFormula(); mrn = mrnGenerationService.generateMrnJexl(movement.getCreatedDateTime(), movement.getOfficeOfDeparture(), "", countryCode, expression); assignMrn(movement, countryCode, mrn, expression); movement.setAcceptanceDateTime(LocalDateTime.now(ZoneOffset.UTC)); dossierDataService.updateMovement(movement); } catch (Exception e) { throw new BaseException("Error retrieving movement with ID: " + movementId, e); } logger.info("Allocated MRN: " + movement.getMrn() + " and acceptanceDateTime: " + movement.getAcceptanceDateTime() + " on Movement with ID: " + movementId); return movement.getMrn(); } private void assignMrn(Movement movement, String countryCode, String mrn, String expression) { if (dossierDataService.mrnExists(mrn)) { logger.info("The MRN that was created exists, a new one will be created."); String newMRN = mrnGenerationService.generateMrnJexl(movement.getCreatedDateTime(), movement.getOfficeOfDeparture(), movement.getSecurity(), countryCode, expression); assignMrn(movement, countryCode, newMRN, expression); } else { movement.setMrn(mrn); } } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.MRNAllocationServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.config.services.MRNFormulaConfigurationService; import com.intrasoft.ermis.transit.common.config.services.MRNGenerationService; import java.time.LocalDateTime; import java.time.ZoneOffset; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MRNAllocationServiceUT { private static final String MOVEMENT_ID = "MOCK_MOVEMENT_ID"; private static final String OFFICE_OF_DEPARTURE_ID = "MOCK_OFFICE_OF_DEPARTURE_ID"; private static final String COUNTRY_CODE = "MOCK_COUNTRY"; private static final String FORMULA = "MOCK_FORMULA"; private static final String MRN = "MOCK_MRN"; @Mock private ErmisLogger logger; @Mock private DossierDataService dossierDataService; @Mock private GetCountryCodeService getCountryCodeService; @Mock private MRNFormulaConfigurationService mrnFormulaConfigurationService; @Mock private MRNGenerationService mrnGenerationService; @InjectMocks private MRNAllocationServiceImpl mrnAllocationService; @Captor private ArgumentCaptor<Movement> movementArgumentCaptor; @Test @DisplayName("Test - Allocate MRN") void testAllocateMRN() { // Test data: Movement mockMovement = Movement.builder() .id(MOVEMENT_ID) .createdDateTime(LocalDateTime.now(ZoneOffset.UTC)) .officeOfDeparture(OFFICE_OF_DEPARTURE_ID) .build(); // Stubs: when(getCountryCodeService.getCountryCode()).thenReturn(COUNTRY_CODE); when(dossierDataService.getMovementById(MOVEMENT_ID)).thenReturn(mockMovement); when(mrnFormulaConfigurationService.retrieveTransitMrnFormula()).thenReturn(FORMULA); when(mrnGenerationService.generateMrnJexl(any(LocalDateTime.class), eq(OFFICE_OF_DEPARTURE_ID), eq(""), eq(COUNTRY_CODE), eq(FORMULA))) .thenReturn(MRN); when(dossierDataService.mrnExists(MRN)).thenReturn(false); // Call tested service method: mrnAllocationService.allocateMRN(MOVEMENT_ID); // Verifications & Assertions: verify(mrnGenerationService, times(1)).generateMrnJexl(any(LocalDateTime.class), any(), any(), any(), any()); verify(dossierDataService, times(1)).updateMovement(movementArgumentCaptor.capture()); assertEquals(MRN, movementArgumentCaptor.getValue().getMrn()); assertNotNull(movementArgumentCaptor.getValue().getAcceptanceDateTime()); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.outbound.ValidationRequestEventProducer; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationRequestedDomainEvent; import com.intrasoft.ermis.transit.contracts.validation.enums.ValidationTypeEnum; import java.util.ArrayList; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class ValidationRequestServiceImpl implements ValidationRequestService { private final ValidationRequestEventProducer validationRequestedEventProducer; private final DossierDataService dossierDataService; private final ErmisLogger logger; @Override public void publishValidationRequest(String messageId, String movementId) { logger.error("ENTER publishValidationRequest() " + messageId); List<String> validationTypes = new ArrayList<>(); Message message = dossierDataService.getMessageById(messageId); if (MessageTypes.TB_015_C.value().equals(message.getMessageType())) { validationTypes.addAll(List.of( ValidationTypeEnum.SEMANTIC_VALIDATION.getType(), ValidationTypeEnum.XSD_VALIDATION.getType())); } else if (MessageTypes.TB_007_C.value().equals(message.getMessageType())) { // TODO: Refine validation types for TB007. validationTypes.addAll(List.of( ValidationTypeEnum.SEMANTIC_VALIDATION.getType(), ValidationTypeEnum.XSD_VALIDATION.getType())); } validationRequestedEventProducer.publish(createValidationRequestedDomainEvent(messageId, movementId, validationTypes)); logger.info("EXIT publishValidationRequest() " + messageId); } private ValidationRequestedDomainEvent createValidationRequestedDomainEvent(String messageId, String movementId, List<String> validationTypes) { return ValidationRequestedDomainEvent.builder() .messageId(messageId) .movementId(movementId) .requestedValidationTypeList(validationTypes) .build(); } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.outbound.ValidationRequestEventProducer; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ValidationRequestServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationRequestedDomainEvent; import com.intrasoft.ermis.transit.contracts.validation.enums.ValidationTypeEnum; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ExtendWith(MockitoExtension.class) class ValidationRequestServiceImplUT { private static final String MESSAGE_ID = UUID.randomUUID().toString(); private static final String MOVEMENT_ID = UUID.randomUUID().toString(); private static final List<String> MESSAGE_TYPES = List.of( MessageTypes.TB_015_C.value(), MessageTypes.TB_007_C.value() ); @Captor private ArgumentCaptor<ValidationRequestedDomainEvent> validationRequestedDomainEventArgumentCaptor; @Mock private ValidationRequestEventProducer validationRequestedEventProducer; @Mock private DossierDataService dossierDataService; @Mock private ErmisLogger ermisLogger; @InjectMocks private ValidationRequestServiceImpl validationRequestService; @ParameterizedTest @MethodSource("arguments") @DisplayName("Test that a ValidationRequestedDomainEvent is created and passed to the producer") void test_creationAndPublishOfValidationRequestedEvent(String messageType) { when(dossierDataService.getMessageById(MESSAGE_ID)).thenReturn(createMessage(messageType)); doNothing().when(validationRequestedEventProducer).publish(any(ValidationRequestedDomainEvent.class)); validationRequestService.publishValidationRequest(MESSAGE_ID, MOVEMENT_ID); verify(validationRequestedEventProducer, times(1)).publish(validationRequestedDomainEventArgumentCaptor.capture()); assertEquals(MESSAGE_ID, validationRequestedDomainEventArgumentCaptor.getValue().getMessageId()); assertEquals(MOVEMENT_ID, validationRequestedDomainEventArgumentCaptor.getValue().getMovementId()); assertNotNull(validationRequestedDomainEventArgumentCaptor.getValue().getRequestedValidationTypeList()); List<String> requestedValidationTypeList = validationRequestedDomainEventArgumentCaptor.getValue().getRequestedValidationTypeList(); if (MessageTypes.TB_015_C.value().equals(messageType)) { assertEquals(2, requestedValidationTypeList.size()); assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.XSD_VALIDATION.getType())); assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.SEMANTIC_VALIDATION.getType())); } else if (MessageTypes.TB_007_C.value().equals(messageType)) { // TODO: Refine validation types for TB007. assertEquals(2, requestedValidationTypeList.size()); assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.XSD_VALIDATION.getType())); assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.SEMANTIC_VALIDATION.getType())); } } private static Stream<Arguments> arguments() { List<Arguments> argumentsList = new ArrayList<>(); for (String expectedMessageType : MESSAGE_TYPES) { argumentsList.add(Arguments.of(expectedMessageType)); } return argumentsList.stream(); } private Message createMessage(String messageType) { return Message.builder() .id(MESSAGE_ID) .messageType(messageType) .build(); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.port.ValidationCompletedEventHandlerService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationCompletedDomainEvent; import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class ValidationCompletedEventHandlerServiceImpl implements ValidationCompletedEventHandlerService { private final BpmnEngine bpmnEngine; private final DossierDataService dossierDataService; @Override public void onValidationCompletedEvent(ValidationCompletedDomainEvent validationCompletedDomainEvent, String messageType, String mrn) throws NotFoundException { CorrelateBpmnMessageCommand correlateBpmnMessageCommand = null; if (MessageTypes.TB_015_C.value().equals(messageType)) { correlateBpmnMessageCommand = CorrelateBpmnMessageCommand .builder() .businessKey(validationCompletedDomainEvent.getMovementId()) .messageName(BpmnGlobalMessageNamesEnum.TB015_VALIDATION_RESULTS_MESSAGE.getValue()) .value(BpmnFlowVariablesEnum.TB015_VALIDATION_ERRORS_FOUND.getValue(), validationCompletedDomainEvent.isRejecting()) .build(); } else if (MessageTypes.TB_007_C.value().equals(messageType)) { correlateBpmnMessageCommand = CorrelateBpmnMessageCommand .builder() .businessKey(validationCompletedDomainEvent.getMovementId()) .messageName(BpmnGlobalMessageNamesEnum.TB007_VALIDATION_RESULTS_MESSAGE.getValue()) .value(BpmnFlowVariablesEnum.TB007_VALIDATION_ERRORS_FOUND.getValue(), validationCompletedDomainEvent.isRejecting()) .build(); } if (correlateBpmnMessageCommand != null) { updateMessageStatus(validationCompletedDomainEvent); bpmnEngine.correlateMessage(correlateBpmnMessageCommand); } } private void updateMessageStatus(ValidationCompletedDomainEvent validationCompletedDomainEvent) throws NotFoundException { Message message = dossierDataService.getMessageById(validationCompletedDomainEvent.getMessageId()); if (message != null) { dossierDataService.updateMessageStatus(message.getId(), validationCompletedDomainEvent.isRejecting() ? MessageStatusEnum.REJECTED.name() : MessageStatusEnum.ACCEPTED.name()); } else { throw new NotFoundException("No message found with id: " + validationCompletedDomainEvent.getMessageId()); } } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service.ValidationCompletedEventHandlerServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationCompletedDomainEvent; import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ValidationCompletedEventHandlerServiceUT { private static final String MOVEMENT_ID = "MOCK_MOVEMENT_ID"; private static final String MESSAGE_ID = "MOCK_MESSAGE_ID"; private static final String MRN = "MOCK_MRN"; @Mock private BpmnEngine bpmnEngine; @Mock private DossierDataService dossierDataService; @InjectMocks private ValidationCompletedEventHandlerServiceImpl validationCompletedEventHandlerService; @Captor private ArgumentCaptor<CorrelateBpmnMessageCommand> commandArgumentCaptor; @ParameterizedTest @DisplayName("Test - On Validation Completed Event") @ValueSource(strings = {"TB007C", "TB015C", "UNEXPECTED"}) void testOnValidationCompletedEvent(String messageType) { // Test data: Message mockMessage = Message.builder() .id(MESSAGE_ID) .messageType(messageType) .build(); ValidationCompletedDomainEvent mockValidationCompletedDomainEvent = ValidationCompletedDomainEvent.builder() .movementId(MOVEMENT_ID) .messageId(MESSAGE_ID) .rejecting(false) .build(); // Stubs: if (!"UNEXPECTED".equals(messageType)) { when(dossierDataService.getMessageById(MESSAGE_ID)).thenReturn(mockMessage); } // Call tested method: validationCompletedEventHandlerService.onValidationCompletedEvent(mockValidationCompletedDomainEvent, messageType, MRN); // Verifications & Assertions: if ("UNEXPECTED".equals(messageType)) { verify(dossierDataService, times(0)).getMessageById(anyString()); verify(dossierDataService, times(0)).updateMessageStatus(anyString(), anyString()); verify(bpmnEngine, times(0)).correlateMessage(any(CorrelateBpmnMessageCommand.class)); } else { verify(dossierDataService, times(1)).getMessageById(MESSAGE_ID); verify(dossierDataService, times(1)).updateMessageStatus(MESSAGE_ID, MessageStatusEnum.ACCEPTED.name()); verify(bpmnEngine, times(1)).correlateMessage(commandArgumentCaptor.capture()); assertEquals(MOVEMENT_ID, commandArgumentCaptor.getValue().getBusinessKey()); if ("TB007C".equals(messageType)) { assertEquals(BpmnGlobalMessageNamesEnum.TB007_VALIDATION_RESULTS_MESSAGE.getValue(), commandArgumentCaptor.getValue().getMessageName()); assertNotNull(commandArgumentCaptor.getValue().getValues()); assertEquals(false, commandArgumentCaptor.getValue().getValues().get(BpmnFlowVariablesEnum.TB007_VALIDATION_ERRORS_FOUND.getValue())); } else if ("TB015C".equals(messageType)) { assertEquals(BpmnGlobalMessageNamesEnum.TB015_VALIDATION_RESULTS_MESSAGE.getValue(), commandArgumentCaptor.getValue().getMessageName()); assertNotNull(commandArgumentCaptor.getValue().getValues()); assertEquals(false, commandArgumentCaptor.getValue().getValues().get(BpmnFlowVariablesEnum.TB015_VALIDATION_ERRORS_FOUND.getValue())); } } } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.officeofdeparture.service; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC013CType; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.ConsignmentItemType09; import com.intrasoft.ermis.ddntav5152.messages.HouseConsignmentType10; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.contracts.core.enums.PreviousDocumentTypeEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.Declaration; import com.intrasoft.ermis.transit.officeofdeparture.domain.DomainBase; import com.intrasoft.ermis.transit.officeofdeparture.domain.Message; import com.intrasoft.ermis.transit.officeofdeparture.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement; import com.intrasoft.ermis.transit.officeofdeparture.domain.MovementAttribute; import com.intrasoft.ermis.transit.officeofdeparture.domain.WorkTask; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.MovementAttributesEnum; import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.ProcessDefinitionEnum; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class TransitAfterAESServiceImpl implements TransitAfterAESService { private static final String CANCELLATION_REASON = "Amendment invalidated. Invalidation cause: new Amendment received"; private final ErmisLogger log; private final DossierDataService dossierDataService; private final BpmnEngine bpmnEngine; private final BpmnFlowService bpmnFlowService; private final TimerService timerService; private final TransitionPeriodService transitionPeriodService; private final WorkTaskManagerDataService workTaskManagerDataService; @Override public boolean isTransitSAfterAES(String movementId) throws JAXBException { Declaration declaration = dossierDataService.getLatestDeclarationByMovementId(movementId); CC015CType cc015cTypeMessage = XmlConverter.buildMessageFromXML(declaration.getPayload(), CC015CType.class); return doIsTransitSAfterAES(cc015cTypeMessage); } @Override @SneakyThrows public boolean isTransitSAfterAESAndIsAESNCTSEnabled(String movementId) { return isTransitSAfterAES(movementId) && isAESNCTSEnabled(movementId); } @Override public boolean isAESNCTSEnabled(String movementId) { MovementAttribute movementAttribute = dossierDataService.findMovementAttributeByMovementIdAndAttrKey(movementId, MovementAttributesEnum.AES_COMMUNICATION_ENABLED.getValue()); if (movementAttribute != null) { return Boolean.parseBoolean(movementAttribute.getAttrValue()); } //default should be false return false; } @Override public void cancelAllOpenWorkTasks(String movementId) { // Find any OPEN work tasks in database and change their status to 'CANCELLED'. List<WorkTask> openWorkTaskList = new ArrayList<>(workTaskManagerDataService.findOpenWorkTasksByMovementId(movementId)); openWorkTaskList.forEach(workTask -> workTaskManagerDataService.autoUpdateWorkTask(workTask.getWorkTaskId())); } @Override public boolean arePreviousDocumentMRNsSame(String movementId) throws JAXBException { List<String> refNumbersFrom015 = getListWithPreviousDocumentMRNsOf015(movementId); List<String> refNumbersFrom013 = getListWithPreviousDocumentMRNsOf013(movementId); if (refNumbersFrom015.size() != refNumbersFrom013.size()) { return false; } else { return refNumbersFrom015.equals(refNumbersFrom013); } } private List<String> getListWithPreviousDocumentMRNsOf015(String movementId) throws JAXBException { List<String> previousDocumentMRNs = new ArrayList<>(); Declaration cc015c = dossierDataService.getLatestDeclarationByMovementId(movementId); if (cc015c != null && cc015c.getPayload() != null) { CC015CType cc015CType = XmlConverter.buildMessageFromXML(cc015c.getPayload(), CC015CType.class); //CI lvl cc015CType.getConsignment().getHouseConsignment() .forEach(houseConsignmentType10 -> houseConsignmentType10.getConsignmentItem() .forEach(consignmentItemType09 -> consignmentItemType09.getPreviousDocument() .stream() .filter(previousDocumentType08 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType08.getType())) .forEach( previousDocumentType08 -> previousDocumentMRNs.add( previousDocumentType08.getReferenceNumber())))); //HC lvl cc015CType.getConsignment() .getHouseConsignment() .forEach(houseConsignmentType10 -> houseConsignmentType10.getPreviousDocument() .stream() .filter(previousDocumentType10 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType10.getType())) .forEach(previousDocumentType10 -> previousDocumentMRNs.add( previousDocumentType10.getReferenceNumber()))); //HC lvl cc015CType.getConsignment().getPreviousDocument().stream() .filter(previousDocumentType09 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType09.getType())) .forEach(previousDocumentType09 -> previousDocumentMRNs.add(previousDocumentType09.getReferenceNumber())); } Collections.sort(previousDocumentMRNs); return previousDocumentMRNs; } private List<String> getListWithPreviousDocumentMRNsOf013(String movementId) throws JAXBException { List<String> previousDocumentMRNs = new ArrayList<>(); List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverview(movementId, MessageTypes.CC_013_C.value()); if (!messageOverviewList.isEmpty()) { messageOverviewList.sort(Comparator.comparing(DomainBase::getCreatedDateTime)); MessageOverview messageOverview = messageOverviewList.get(messageOverviewList.size() - 1); String messageId = messageOverview.getId(); Message cc013cMessage = dossierDataService.getMessageById(messageId); if (cc013cMessage != null) { CC013CType cc013CType = XmlConverter.buildMessageFromXML(cc013cMessage.getPayload(), CC013CType.class); //CI lvl cc013CType.getConsignment().getHouseConsignment() .forEach(houseConsignmentType10 -> houseConsignmentType10.getConsignmentItem() .forEach(consignmentItemType09 -> consignmentItemType09.getPreviousDocument() .stream() .filter(previousDocumentType08 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType08.getType())) .forEach( previousDocumentType08 -> previousDocumentMRNs.add( previousDocumentType08.getReferenceNumber())))); //HC lvl cc013CType.getConsignment() .getHouseConsignment() .forEach(houseConsignmentType10 -> houseConsignmentType10.getPreviousDocument() .stream() .filter(previousDocumentType10 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType10.getType())) .forEach(previousDocumentType10 -> previousDocumentMRNs.add( previousDocumentType10.getReferenceNumber()))); //HC lvl cc013CType.getConsignment().getPreviousDocument().stream() .filter(previousDocumentType09 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType09.getType())) .forEach(previousDocumentType09 -> previousDocumentMRNs.add(previousDocumentType09.getReferenceNumber())); } } Collections.sort(previousDocumentMRNs); return previousDocumentMRNs; } private boolean doIsTransitSAfterAES(CC015CType cc015CType) { boolean b = cc015CType.getConsignment() .getHouseConsignment() .stream() .map(HouseConsignmentType10::getPreviousDocument) .flatMap(List::stream) .anyMatch(x -> x.getType().equals(PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue())); // Check in HS -> CI -> previous document lvl ONLY if we are in TP if (transitionPeriodService.isNowNCTSTransitionPeriod()) { return b || cc015CType.getConsignment() .getHouseConsignment() .stream() .map(HouseConsignmentType10::getConsignmentItem) .flatMap(List::stream) .map(ConsignmentItemType09::getPreviousDocument) .flatMap(List::stream) .anyMatch(x -> x.getType().equals(PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue())); } return b; } @Override public boolean isCC13CTransitSAfterAES(String messageId, String movementId) throws JAXBException { Message cc013cMessage = dossierDataService.getMessageById(messageId); boolean isTransitSAfterAES = false; if (cc013cMessage != null) { CC013CType cc013CType = XmlConverter.buildMessageFromXML(cc013cMessage.getPayload(), CC013CType.class); if (cc013CType.getConsignment() != null && !CollectionUtils.isEmpty(cc013CType.getConsignment().getHouseConsignment())) { isTransitSAfterAES = cc013CType.getConsignment() .getHouseConsignment() .stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getPreviousDocument() .stream()) .anyMatch(previousDocumentType04 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType04.getType())) || cc013CType.getConsignment() .getHouseConsignment() .stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getConsignmentItem().stream()) .flatMap(consignmentItemType09 -> consignmentItemType09.getPreviousDocument() .stream()) .anyMatch(previousDocumentType08 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue() .equals(previousDocumentType08.getType())); log.info("isTransitSAfterAES {}", isTransitSAfterAES); } } return isTransitSAfterAES; } @Override public boolean isCC013CTransitAfterAes(String movementId) throws JAXBException { boolean cc013cIsTransitAfterAes = false; List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverview(movementId, MessageTypes.CC_013_C.value()); if (!messageOverviewList.isEmpty()) { messageOverviewList.sort(Comparator.comparing(DomainBase::getCreatedDateTime)); MessageOverview messageOverview = messageOverviewList.get(messageOverviewList.size() - 1); String messageId = messageOverview.getId(); cc013cIsTransitAfterAes = isCC13CTransitSAfterAES(messageId, movementId); } return cc013cIsTransitAfterAes; } @Override public void initNegativeIE191Flow(String movementId, String messageId) { final CorrelateBpmnMessageCommand correlateBpmnMessageCommand = CorrelateBpmnMessageCommand .builder() .businessKey(movementId) .messageName(BpmnFlowMessagesEnum.INIT_FLOW_FOR_NEGATIVE_IE191.getTypeValue()) .value(BpmnFlowVariablesEnum.PROCESS_BUSINESS_KEY.getTypeValue(), movementId) .value(BpmnFlowVariablesEnum.WAITING_AMENDMENT_TIMER_DELAY.getTypeValue(), timerService.getAmendmentExpirationTimerDelayConfig().getTimerSetupString()) .value(BpmnFlowVariablesEnum.MOVEMENT_ID.getTypeValue(), movementId) .build(); bpmnEngine.correlateMessage(correlateBpmnMessageCommand); } @Override public void cancelPreviousAmendmentProcess(String movementId) { List<MessageOverview> messageOverview = dossierDataService.getMessagesOverview(movementId, MessageTypes.CC_013_C.value()); //get all 013s if (!messageOverview.isEmpty()) { Movement movement = dossierDataService.getMovementById(movementId); messageOverview.sort(Comparator.comparing(DomainBase::getCreatedDateTime)); if (movement == null) { throw new NotFoundException("No movement found for movement id".concat(movementId)); } MessageOverview previousO13Message = messageOverview.get(messageOverview.size() - 2); final String cancellationReason = createCancellationReason(); bpmnFlowService.cancelProcessInstanceIfExists(movementId.concat("-").concat(previousO13Message.getId()), ProcessDefinitionEnum.OODEPARTURE_HANDLE_AMENDMENT_REQUEST_PROCESS.getProcessDefinitionKey(), cancellationReason); } } private String createCancellationReason() { return CANCELLATION_REASON; } }
package com.intrasoft.ermis.trs.officeofdeparture.service; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.ddntav5152.messages.PreviousDocumentType10; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.contracts.core.enums.PreviousDocumentTypeEnum; import com.intrasoft.ermis.trs.officeofdeparture.util.GeneratorHelper; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.xml.bind.JAXBException; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class TransitAfterAESServiceUT extends GeneratorHelper { private static final String FILENAME = "CC015C_AES"; @Mock private TransitionPeriodService transitionPeriodService; private CC015CType cc015CType; @Test void testCommunicationWithAESNeeded() throws JAXBException { when(dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID)).thenReturn(createDeclaration(MessageTypes.CC_015_C.value(), FILENAME)); boolean communicationWithAESNeeded = !transitAfterAESService.arePreviousDocumentMRNsSame(MOVEMENT_ID); assertTrue(communicationWithAESNeeded); } @ParameterizedTest @MethodSource("namedArguments") void test_IsTransitAfterAESDuringTP(String previousDocumentLevel) { try { cc015CType = XmlConverter.buildMessageFromXML(loadTextFile(FILENAME), CC015CType.class); if ("houseConsignment".equals(previousDocumentLevel)) { alterMessagePreviousDocumentLevel(cc015CType); } when(dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID)).thenReturn(createDeclaration(MessageTypes.CC_015_C.value(), FILENAME)); Mockito.when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(true); boolean result = transitAfterAESService.isTransitSAfterAES(MOVEMENT_ID); assertTrue(result); if ("houseConsignment".equals(previousDocumentLevel)) { assertionsForPreviousDocumentInHC(); } else { assertionsForPreviousDocumentInCI(); } } catch (JAXBException e) { fail(); } } @Test void test_IsTransitAfterAESAfterTP() { try { cc015CType = XmlConverter.buildMessageFromXML(loadTextFile(FILENAME), CC015CType.class); alterMessagePreviousDocumentLevel(cc015CType); when(dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID)).thenReturn(createDeclaration(cc015CType)); Mockito.when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(false); boolean result = transitAfterAESService.isTransitSAfterAES(MOVEMENT_ID); assertTrue(result); assertionsForPreviousDocumentInHC(); } catch (JAXBException e) { fail(); } } @Test void test_IsNotTransitAfterAESDuringTP() { try { cc015CType = XmlConverter.buildMessageFromXML(loadTextFile(FILENAME), CC015CType.class); removePreviousDocumentsFromCI(cc015CType); when(dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID)).thenReturn(createDeclaration(cc015CType)); Mockito.when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(true); boolean result = transitAfterAESService.isTransitSAfterAES(MOVEMENT_ID); assertFalse(result); assertionsForNoPreviousDocument(); } catch (JAXBException e) { fail(); } } @ParameterizedTest @MethodSource("namedArguments2") void test_IsNotTransitAfterAESAfterTP(String previousDocumentLevel) { try { cc015CType = XmlConverter.buildMessageFromXML(loadTextFile(FILENAME), CC015CType.class); if ("none".equals(previousDocumentLevel)) { removePreviousDocumentsFromCI(cc015CType); } when(dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID)).thenReturn(createDeclaration(cc015CType)); Mockito.when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(false); boolean result = transitAfterAESService.isTransitSAfterAES(MOVEMENT_ID); assertFalse(result); if ("consignmentItem".equals(previousDocumentLevel)) { assertionsForPreviousDocumentInCI(); } else { assertionsForNoPreviousDocument(); } } catch (JAXBException e) { fail(); } } static Stream<Arguments> namedArguments() { return Stream.of( Arguments.of(Named.of(" previousDocument in HC", "houseConsignment")), Arguments.of(Named.of(" previousDocument in CI", "consignmentItem")) ); } static Stream<Arguments> namedArguments2() { return Stream.of( Arguments.of(Named.of(" no previousDocument in any level", "none")), Arguments.of(Named.of(" previousDocument in CI", "consignmentItem")) ); } private void alterMessagePreviousDocumentLevel(CC015CType cc015CType) { removePreviousDocumentsFromCI(cc015CType); addPreviousDocumentInHC(cc015CType); } private void removePreviousDocumentsFromCI(CC015CType cc015CType) { cc015CType.getConsignment() .getHouseConsignment() .stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getConsignmentItem().stream()) .forEach(consignmentItemType09 -> consignmentItemType09.getPreviousDocument().clear()); } private void addPreviousDocumentInHC(CC015CType cc015CType) { PreviousDocumentType10 previousDocumentType10 = new PreviousDocumentType10(); previousDocumentType10.setType("N830"); previousDocumentType10.setSequenceNumber("1"); previousDocumentType10.setReferenceNumber("23DK11111111111111"); cc015CType.getConsignment().getHouseConsignment().get(0).getPreviousDocument().add(previousDocumentType10); } private void assertionsForNoPreviousDocument() { assertTrue(cc015CType.getConsignment().getHouseConsignment().stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getPreviousDocument().stream()) .noneMatch(previousDocumentType10 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue().equals(previousDocumentType10.getType()))); assertTrue(cc015CType.getConsignment().getHouseConsignment().stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getConsignmentItem().stream()) .flatMap(consignmentItemType09 -> consignmentItemType09.getPreviousDocument().stream()) .toList() .stream() .noneMatch(previousDocumentType08 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue().equals(previousDocumentType08.getType()))); } private void assertionsForPreviousDocumentInCI() { assertTrue(cc015CType.getConsignment().getHouseConsignment().stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getPreviousDocument().stream()) .noneMatch(previousDocumentType10 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue().equals(previousDocumentType10.getType()))); assertTrue(cc015CType.getConsignment().getHouseConsignment().stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getConsignmentItem().stream()) .flatMap(consignmentItemType09 -> consignmentItemType09.getPreviousDocument().stream()) .toList() .stream() .anyMatch(previousDocumentType08 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue().equals(previousDocumentType08.getType()))); } private void assertionsForPreviousDocumentInHC() { assertTrue(cc015CType.getConsignment().getHouseConsignment().stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getPreviousDocument().stream()) .anyMatch(previousDocumentType10 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue().equals(previousDocumentType10.getType()))); assertTrue(cc015CType.getConsignment().getHouseConsignment().stream() .flatMap(houseConsignmentType10 -> houseConsignmentType10.getConsignmentItem().stream()) .flatMap(consignmentItemType09 -> consignmentItemType09.getPreviousDocument().stream()) .toList() .stream() .noneMatch(previousDocumentType08 -> PreviousDocumentTypeEnum.GOODS_EXPORTATION_DECLARATION.getValue().equals(previousDocumentType08.getType()))); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.management.core.service; import com.intrasoft.ermis.common.json.parsing.JsonConverter; import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.contracts.management.dto.action.data.StatusRequestEvent; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.port.outbound.StatusRequestProducer; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.shared.security.service.UserDetailsService; import java.util.UUID; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class StatusRequestServiceImpl implements StatusRequestService { private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter(); private final StatusRequestProducer statusRequestProducer; private final UserDetailsService userDetailsService; private final GetCountryCodeService getCountryCodeService; private final DossierDataService dossierDataService; // TODO: Should be refactored to use action system @Override public void handleStatusRequest(StatusRequestEvent statusRequestEvent) { statusRequestEvent.setRequestId(UUID.randomUUID().toString()); Message message = Message.builder() .messageIdentification(MessageUtil.generateMessageIdentification()) .messageType(StatusRequestEvent.class.getSimpleName()) .source(userDetailsService.getUsername()) .destination("NTA." + getCountryCodeService.getCountryCode()) .payload(JSON_CONVERTER.convertToJsonString(statusRequestEvent)) .domain(MessageDomainTypeEnum.ERMIS.name()) .direction(DirectionEnum.RECEIVED.getDirection()) .build(); message = dossierDataService.persistMessage(message); dossierDataService.associateMessageWithMovement(message.getId(), statusRequestEvent.getMovementId()); statusRequestProducer.publish(statusRequestEvent); } }
package com.intrasoft.ermis.transit.officeofexitfortransit.service; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createIE094Message; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createIE168Message; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.generateRandomMRN; import static com.intrasoft.ermis.transit.officeofexitfortransit.util.Stubs.stubSaveMessage; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CD094CType; import com.intrasoft.ermis.ddntav5152.messages.CD168CType; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.officeofexitfortransit.core.outbound.DDNTAMessageProducer; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.DossierDataService; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.GenerateMessageService; import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.StatusRequestServiceImpl; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.MessageOverview; import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Movement; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class StatusRequestServiceUT { private final String MOVEMENT_ID = UUID.randomUUID().toString(); private final String MRN = generateRandomMRN(); private static final String IE094_MESSAGE_ID = "IE094_MESSAGE_ID"; private static final String IE168_MESSAGE_ID = "IE168_MESSAGE_ID"; @Mock private DossierDataService dossierDataService; @Mock private GenerateMessageService generateMessageService; @Mock private DDNTAMessageProducer ddntaMessageProducer; @InjectMocks private StatusRequestServiceImpl statusReportRequestService; @Captor private ArgumentCaptor<String> xmlArgumentCaptor; @Test @DisplayName("Test - Handle IE094 Status Report Request") void testHandleIE094StatusRequest() { System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); // Stubs: Movement movement = createMovement(MOVEMENT_ID); CD094CType cd094cTypeMessage = createIE094Message(MRN); CD168CType cd168cTypeMessage = createIE168Message(MRN); List<MessageOverview> messageOverviewList = createMessageOverviewList(); try { // Mocks: when(dossierDataService.getMovementByCriteria(MRN, OfficeRoleTypesEnum.EXIT.getValue(), "IE094_EXIT_OFFICE_REF_NUM")).thenReturn(movement); doNothing().when(generateMessageService).generateIE095(eq(MOVEMENT_ID), any(), any()); when(dossierDataService.getMessageById(IE094_MESSAGE_ID)) .thenReturn(getMessage(MessageTypes.CD_094_C.value(), XmlConverter.marshal(cd094cTypeMessage))); when(dossierDataService.getMessageById(IE168_MESSAGE_ID)) .thenReturn(getMessage(MessageTypes.CD_168_C.value(), XmlConverter.marshal(cd168cTypeMessage))); when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CD_168_C.value())).thenReturn(messageOverviewList); when(dossierDataService.saveMessage(any())).thenAnswer(stubSaveMessage()); doNothing().when(dossierDataService).associateMessageWithMovement(any(), eq(MOVEMENT_ID)); // Call StatusRequestService method: statusReportRequestService.handleIE094StatusRequest(MRN, IE094_MESSAGE_ID, "IE094_EXIT_OFFICE_REF_NUM"); // Verifications & Assertions: verify(ddntaMessageProducer, times(1)).publish(xmlArgumentCaptor.capture(), eq(MOVEMENT_ID), eq(MessageTypes.CD_168_C.value())); CD168CType cd168cTypeMessageOut = XmlConverter.buildMessageFromXML(xmlArgumentCaptor.getValue(), CD168CType.class); verify(dossierDataService, times(1)).getMovementByCriteria(MRN, OfficeRoleTypesEnum.EXIT.getValue(), "IE094_EXIT_OFFICE_REF_NUM"); verify(dossierDataService, times(1)).getMessageById(IE094_MESSAGE_ID); verify(dossierDataService, times(1)).getMessageById(IE168_MESSAGE_ID); verify(dossierDataService, times(1)).getMessagesOverview(MOVEMENT_ID, MessageTypes.CD_168_C.value()); verify(dossierDataService, times(1)).saveMessage(any()); verify(dossierDataService, times(1)).associateMessageWithMovement(any(), eq(MOVEMENT_ID)); assertEquals(cd168cTypeMessage.getMessageSender(), cd168cTypeMessageOut.getMessageSender()); assertEquals(cd168cTypeMessage.getMessageRecipient(), cd168cTypeMessageOut.getMessageRecipient()); assertEquals(cd168cTypeMessage.getTransitOperation().getMRN(), cd168cTypeMessageOut.getTransitOperation().getMRN()); assertNotEquals(cd168cTypeMessage.getMessageIdentification(), cd168cTypeMessageOut.getMessageIdentification()); assertNotEquals(cd168cTypeMessage.getPreparationDateAndTime(), cd168cTypeMessageOut.getPreparationDateAndTime()); } catch (Exception e) { fail(); } } private Movement createMovement(String movementId) { return Movement.builder() .id(movementId) .mrn(MRN) .processingStatus(ProcessingStatusTypeEnum.OOTRXS_MOVEMENT_LEFT_EUROPEAN_CUSTOMS_SECURITY_AREA.getItemCode()) .officeRoleType(OfficeRoleTypesEnum.EXIT.getValue()) .officeId("DK_TEST_OFFICE_ID") .build(); } private List<MessageOverview> createMessageOverviewList() { List<MessageOverview> messageOverviewList = new ArrayList<>(); MessageOverview ie168MessageOverview = new MessageOverview(); ie168MessageOverview.setMessageType(MessageTypes.CD_168_C.value()); ie168MessageOverview.setId(IE168_MESSAGE_ID); messageOverviewList.add(ie168MessageOverview); return messageOverviewList; } private Message getMessage(String messageType, String payload) { return Message.builder() .id(UUID.randomUUID().toString()) .messageIdentification(UUID.randomUUID().toString()) .messageType(messageType) .source("DEPARTURE") .destination("EXIT") .domain("COMMON") .createdDateTime(LocalDateTime.now(ZoneOffset.UTC)) .payload(payload) .build(); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import lombok.RequiredArgsConstructor; import org.camunda.bpm.engine.MismatchingMessageCorrelationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) public class ArrivalNotificationServiceImpl implements ArrivalNotificationService { private static final String ERROR_MESSAGE_PREFIX = "Failed to correlate {" + BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue() + "} BPMN message for Movement with ID: "; private static final String ERROR_MESSAGE_SUFFIX = ". The main process is either past the related await point, is finished or does not exist."; private final BpmnEngine bpmnEngine; @Override public void continueMainProcess(String movementId) throws BaseException { CorrelateBpmnMessageCommand command = CorrelateBpmnMessageCommand.builder() .messageName(BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue()) .businessKey(movementId) .build(); try { bpmnEngine.correlateMessage(command); } catch (MismatchingMessageCorrelationException exception) { throw new BaseException(ERROR_MESSAGE_PREFIX + movementId + ERROR_MESSAGE_SUFFIX); } } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.intrasoft.ermis.common.bpmn.core.BpmnEngine; import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ArrivalNotificationServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import org.camunda.bpm.engine.MismatchingMessageCorrelationException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ArrivalNotificationServiceUT { private static final String ERROR_MESSAGE_PREFIX = "Failed to correlate {" + BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue() + "} BPMN message for Movement with ID: "; private static final String ERROR_MESSAGE_SUFFIX = ". The main process is either past the related await point, is finished or does not exist."; private static final String MOVEMENT_ID = "MOCK_MOVEMENT_ID"; @Mock private BpmnEngine bpmnEngine; @InjectMocks private ArrivalNotificationServiceImpl arrivalNotificationService; @Captor private ArgumentCaptor<CorrelateBpmnMessageCommand> commandArgumentCaptor; @ParameterizedTest @DisplayName("Test - Continue Main Process") @ValueSource(booleans = {true, false}) void testContinueMainProcess(boolean successfulCorrelation) { if (successfulCorrelation) { // Stub: doNothing().when(bpmnEngine).correlateMessage(any()); // Call tested service method: arrivalNotificationService.continueMainProcess(MOVEMENT_ID); // Verification & Assertions: verify(bpmnEngine, times(1)).correlateMessage(commandArgumentCaptor.capture()); assertEquals(BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue(), commandArgumentCaptor.getValue().getMessageName()); assertEquals(MOVEMENT_ID, commandArgumentCaptor.getValue().getBusinessKey()); } else { // Stub: doThrow(new MismatchingMessageCorrelationException("ERROR")).when(bpmnEngine).correlateMessage(any()); // Call tested service method: Throwable exception = assertThrows(BaseException.class, () -> arrivalNotificationService.continueMainProcess(MOVEMENT_ID)); // Assertion: assertEquals(ERROR_MESSAGE_PREFIX + MOVEMENT_ID + ERROR_MESSAGE_SUFFIX, exception.getMessage()); } } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.management.core.service; import static com.intrasoft.ermis.transit.common.util.MessageUtil.SKIP_MOVEMENT_EXISTENCE_LIST; import static com.intrasoft.ermis.transit.common.util.MessageUtil.extractMRNCountryCode; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.intrasoft.ermis.common.event.ErmisEvent; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.enums.NamespacesEnum; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.AddressType07; import com.intrasoft.ermis.ddntav5152.messages.CC015CType; import com.intrasoft.ermis.ddntav5152.messages.CC056CType; import com.intrasoft.ermis.ddntav5152.messages.CC057CType; import com.intrasoft.ermis.ddntav5152.messages.CC906CType; import com.intrasoft.ermis.ddntav5152.messages.CC917CType; import com.intrasoft.ermis.ddntav5152.messages.CD027CType; import com.intrasoft.ermis.ddntav5152.messages.CD038CType; import com.intrasoft.ermis.ddntav5152.messages.CD906CType; import com.intrasoft.ermis.ddntav5152.messages.CustomsOfficeOfDepartureType03; import com.intrasoft.ermis.ddntav5152.messages.CustomsOfficeOfDestinationActualType03; import com.intrasoft.ermis.ddntav5152.messages.FunctionalErrorType04; import com.intrasoft.ermis.ddntav5152.messages.HolderOfTheTransitProcedureType08; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.ddntav5152.messages.RepresentativeType01; import com.intrasoft.ermis.ddntav5152.messages.TraderAtDestinationType03; import com.intrasoft.ermis.ddntav5152.messages.TransitOperationType20; import com.intrasoft.ermis.ddntav5152.messages.TransitOperationType21; import com.intrasoft.ermis.ddntav5152.messages.TransitOperationType32; import com.intrasoft.ermis.documentsv1.messages.CCE46AType; import com.intrasoft.ermis.documentsv1.messages.MessageERMISTypes; import com.intrasoft.ermis.documentsv1.validator.DocumentsXmlValidator; import com.intrasoft.ermis.platform.contracts.dossier.enums.StatisticsSystemEnum; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.CcnReportTypeEnum; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.DomainEnum; import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum; import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypeStatuses; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.BaseException; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.common.exceptions.RetryableException; import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.common.util.IE906Generator; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.common.util.Pair; import com.intrasoft.ermis.transit.contracts.core.enums.AarRejectionReasonEnum; import com.intrasoft.ermis.transit.contracts.core.enums.MessageXPathsEnum; import com.intrasoft.ermis.transit.contracts.management.enums.MessageAttributeKeysEnum; import com.intrasoft.ermis.transit.contracts.management.enums.MovementAttributeKeysEnum; import com.intrasoft.ermis.transit.management.core.configuration.ManagementRetryConfigurationProperties; import com.intrasoft.ermis.transit.management.core.exception.BadRequestException; import com.intrasoft.ermis.transit.management.core.port.inbound.DDNTAMessageProcessingService; import com.intrasoft.ermis.transit.management.core.port.outbound.DDNTAMessageProducer; import com.intrasoft.ermis.transit.management.core.port.outbound.DocumentResponseProducer; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.port.outbound.ProcessMessageCommandProducer; import com.intrasoft.ermis.transit.management.core.port.outbound.ValidationService; import com.intrasoft.ermis.transit.management.core.util.MessageValidationUtils; import com.intrasoft.ermis.transit.management.core.util.ViolationUtils; import com.intrasoft.ermis.transit.management.domain.CcnReport; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.MessageAttribute; import com.intrasoft.ermis.transit.management.domain.MessageOverview; import com.intrasoft.ermis.transit.management.domain.Movement; import com.intrasoft.ermis.transit.management.domain.MovementAttribute; import com.intrasoft.ermis.transit.management.domain.MovementQuery; import com.intrasoft.ermis.transit.management.domain.MovementsOrViolations; import com.intrasoft.ermis.transit.management.domain.ProcessingStatus; import com.intrasoft.ermis.transit.management.domain.RejectedMessage; import com.intrasoft.ermis.transit.management.domain.StatisticalMessage; import com.intrasoft.ermis.transit.management.domain.Violation; import com.intrasoft.ermis.transit.shared.security.service.UserDetailsService; import java.io.IOException; import java.io.StringReader; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.xml.bind.JAXBException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.springframework.beans.factory.annotation.Value; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; //TODO Class (and corresponding interface) name should be changed to be compatible with a broader variety of message types @Service @RequiredArgsConstructor @SuppressWarnings("findsecbugs:XPATH_INJECTION") public class DDNTAMessageProcessingServiceImpl implements DDNTAMessageProcessingService { private static final List<String> retryList = Arrays.asList(MessageTypes.CD_018_C.value(), MessageTypes.CD_152_C.value()); public static final String CC = "CC"; private static final String TB = "TB"; private static final String NECA = "NECA."; private static final XPath XPATH = XPathFactory.newInstance().newXPath(); private static final String IDENTIFICATION_NUMBER = "//HolderOfTheTransitProcedure/identificationNumber"; private static final String TIR_IDENTIFICATION_NUMBER = "//HolderOfTheTransitProcedure/TIRHolderIdentificationNumber"; private static final String NAME = "//HolderOfTheTransitProcedure/name"; private static final String ADDRESS = "//HolderOfTheTransitProcedure/Address"; private static final String STREETANDNUMBER = "//HolderOfTheTransitProcedure/Address/streetAndNumber"; private static final String POSTCODE = "//HolderOfTheTransitProcedure/Address/postcode"; private static final String CITY = "//HolderOfTheTransitProcedure/Address/city"; private static final String COUNTRY = "//HolderOfTheTransitProcedure/Address/country"; private static final String REPRESENTATIVE = "//Representative"; private static final String STATUS = "//Representative/status"; private static final String IDENTIFICATION_NUMBER_REPRESENTATIVE = "//Representative/identificationNumber"; private static final String IDENTIFICATION_NUMBER_TRADER_AT_DEST = "//TraderAtDestination/identificationNumber"; private static final String SIMPLIFIED_AUTHORISATION = "C521"; private static final String DECLARATION_TYPE = "//TransitOperation/declarationType"; private static final Set<String> OODEST_SKIP_OFFICE_ID_VALIDATION_MESSAGE_TYPES = Set.of(MessageTypes.CD_150_C.value(), MessageTypes.CC_007_C.value()); private static final int E1115_MAX_LENGTH = 140; private static final String XSD_ERROR_REASON = "XSD"; private static final List<String> INCOMING_REJECTION_MESSAGES_LIST = Arrays.asList(MessageTypes.CC_906_C.value(), MessageTypes.CC_917_C.value(), MessageTypes.CD_906_C.value(), MessageTypes.CD_917_C.value()); private final ErmisLogger log; private final DossierDataService dossierDataService; private final ValidationService validationService; private final ProcessMessageCommandProducer processMessageCommandProducer; private final DDNTAMessageProducer ddntaMessageProducer; private final GetCountryCodeService getCountryCodeService; private final MessageTypeMapper messageTypeMapper; private final TransitionPeriodService transitionPeriodService; private final CargoMessageService cargoMessageService; private final ObjectMapper objectMapper; private final ConfigurationSwitchService configurationSwitchService; private final UserDetailsService userDetailsService; private final MessageValidationService messageValidationService; private final GenerateMessageService generateMessageService; // NOTE: Following bean is used in @Retryable SpEL expressions. do not delete private final ManagementRetryConfigurationProperties managementRetryConfigurationProperties; @Value("${trs.management.external-messages-xsd-validation}") private boolean isExternalMessagesXsdValidationEnabled; private final DDNTAMessageCustomValidationServiceImpl ddntaMessageCustomValidationService; private final DocumentResponseProducer documentResponseProducer; private final DocumentsXmlValidator documentsXmlValidator = new DocumentsXmlValidator(); private static final Map<String, String> MESSAGE_TO_OFFICE = Map.of( MessageTypes.CD_142_C.value(), OfficeRoleTypesEnum.DESTINATION.getValue(), MessageTypes.CD_144_C.value(), OfficeRoleTypesEnum.DESTINATION.getValue(), MessageTypes.CD_002_C.value(), OfficeRoleTypesEnum.DEPARTURE.getValue(), MessageTypes.CD_114_C.value(), OfficeRoleTypesEnum.DEPARTURE.getValue(), MessageTypes.CD_164_C.value(), OfficeRoleTypesEnum.DEPARTURE.getValue() ); // List of Message types that need not undergo R&C Validation: private static final List<String> SKIP_RC_VALIDATION_LIST = List.of( MessageTypes.CC_015_C.value(), com.intrasoft.ermis.cargov1.messages.MessageTypes.TB_015_C.value() ); // List of Message types that need to undergo Authorization Validation: // (All CC0015C validations are deferred to OoDep) private static final List<String> AUTHORIZATION_VALIDATION_LIST = List.of( MessageTypes.CC_007_C.value() ); // List of Message Types that need special handling to determine their target office private static final List<String> CUSTOM_TARGET_LIST = List.of( MessageTypes.CD_094_C.value(), MessageTypes.CD_150_C.value(), MessageTypes.CD_152_C.value() ); @Override @Retryable(value = {RetryableException.class}, maxAttemptsExpression = "#{@managementRetryConfigurationProperties.getMaxAttempts()}", backoff = @Backoff(delayExpression = "#{@managementRetryConfigurationProperties.getDelay()}", multiplierExpression = "#{@managementRetryConfigurationProperties.getMultiplier()}")) public void processMessage(String messageXml) throws RetryableException, XPathExpressionException, BadRequestException { Message message = setUpMessage(messageXml, false, DirectionEnum.RECEIVED); //implemented due to PSD-5641 for IE006,IE018 and IE063,IE152 messages pairs. if (retryList.contains(message.getMessageType())) { checkWhetherRelatedMessageIsUnderProcess(message); } continueProcessMessage(message); } @Recover public void recoverProcessMessage(String messageXml, RetryableException exception) throws BadRequestException, XPathExpressionException { log.debug("Recovering processMessage method for: " + exception); Message message = setUpMessage(messageXml, false, DirectionEnum.RECEIVED); continueProcessMessage(message); } private void continueProcessMessage(Message message) throws BadRequestException, XPathExpressionException { // persist Message persistedMessage = dossierDataService.persistMessage(message); log.info(":=> processMessage() : Received and persisted new Message -> id: [{}], type: [{}], MRN: [{}]", message.getMessageIdentification(), message.getMessageType(), message.getMrn()); // validate and create required movements MovementsOrViolations movementsOrViolations = validateMessage(persistedMessage); if (!movementsOrViolations.getViolations().isEmpty()) { dossierDataService.updateMessage(persistedMessage.getId(), MessageStatusEnum.REJECTED.name()); movementsOrViolations.getViolations() .forEach(violation -> log.warn( ":=> processMessage() : {} Violation(s) found on Message Type [{}]. violationInfo:{}. Will send error message and return", movementsOrViolations.getViolations().size(), message.getMessageType(), violation.toString())); handleViolations(movementsOrViolations, persistedMessage, false); } else { dossierDataService.updateMessage(persistedMessage.getId(), MessageStatusEnum.ACCEPTED.name()); handleMovements(movementsOrViolations, persistedMessage); } handleIncomingRejectionMessage(persistedMessage, movementsOrViolations); } private void checkWhetherRelatedMessageIsUnderProcess(Message message) throws RetryableException { List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverviewByMrnAndMessageTypes(message.getMrn(), MessageTypes.CD_018_C.value().equals(message.getMessageType()) ? List.of(MessageTypes.CD_006_C) : List.of(MessageTypes.CD_152_C)); if (!messageOverviewList.isEmpty()) { List<MessageAttribute> messageAttributeList = dossierDataService.findMessageAttributesByMessageId(messageOverviewList.get(0).getId()); if (messageAttributeList.isEmpty() || messageAttributeList.stream().noneMatch(messageAttribute -> messageAttribute.getAttrKey().equals(MessageTypes.CD_006_C.value().equals(messageOverviewList.get(0).getMessageType()) ? MessageAttributeKeysEnum.CD006C_MESSAGE_PROCESSED.getValue() : MessageAttributeKeysEnum.CD063C_MESSAGE_PROCESSED.getValue()) )) { log.error("Retry processing of message with identification: {} and type: {}", message.getMessageIdentification(), message.getMessageType()); throw new RetryableException("Message is Under Process!"); } } } @SneakyThrows private void handleIncomingCD906C(Message message, MovementsOrViolations movements) { CD906CType cd906CType = XmlConverter.buildMessageFromXML(message.getPayload(), CD906CType.class); createAndPersistRejectedMessageInfo(cd906CType, message.getId(), DirectionEnum.RECEIVED, movements.getMovements()); } private void handleIncomingRejectionMessage(Message message, MovementsOrViolations movements) { if (INCOMING_REJECTION_MESSAGES_LIST.contains(message.getMessageType())) { //if 906 or 917 message arrives, the corresponding rejected message must be marked as rejected List<MessageOverview> messageOverviewList = dossierDataService.getMessagesOverview(null, null, getCorrelationIdentifier(message.getPayload()), null, null, null, 0, 20); if (!messageOverviewList.isEmpty()) { Message rejectedMessage = dossierDataService.getMessageById(messageOverviewList.get(0).getId(), false); dossierDataService.updateMessage(rejectedMessage.getId(), MessageStatusEnum.REJECTED.name()); } // CD906 should also create a new entry in the rejectMessage table if (MessageTypes.CD_906_C.value().equals(message.getMessageType())) { handleIncomingCD906C(message, movements); } } } @Override public void processManualMessage(String messageXml) throws BadRequestException, XPathExpressionException { log.info("DDNTAMessageProcessingServiceImpl - processManualMessage"); // persist Message message = dossierDataService.persistMessage(setUpMessage(messageXml, true, DirectionEnum.RECEIVED)); log.info(":=> processManualMessage() : Received and persisted new DDNTA Message -> id: [{}], type: [{}], MRN: [{}]", message.getMessageIdentification(), message.getMessageType(), message.getMrn()); // Create userId message attribute, to be used my Movement History: createSubmissionUserIdMessageAttribute(message.getId()); // validate and create required movements MovementsOrViolations mov = validateMessage(message); if (!mov.getViolations().isEmpty()) { log.warn(":=> processManualMessage() : {} Violation(s) found on Message Type [{}]. Will send error message and return", mov.getViolations().size(), message.getMessageType()); dossierDataService.updateMessage(message.getId(), MessageStatusEnum.REJECTED.name()); handleViolations(mov, message, true); } else { dossierDataService.updateMessage(message.getId(), MessageStatusEnum.ACCEPTED.name()); handleMovements(mov, message); } } @Override @SneakyThrows public void processMessage903(String messageXml) { // persist Message message = dossierDataService.persistMessage(setUpMessage(messageXml, false, DirectionEnum.RECEIVED)); log.info(":=> processMessage903() : Received and persisted new DDNTA Message -> id: [{}], type: [{}], MRN: [{}]", message.getMessageIdentification(), message.getMessageType(), message.getMrn()); String system = message.getDestination().substring(0, message.getDestination().indexOf('.')); StatisticsSystemEnum statisticsSystemEnum = StatisticsSystemEnum.fromMessageSenderPrefix(system); List<Violation> violations = new ArrayList<>(); if (statisticsSystemEnum == null) { violations.add(Violation.builder().reason("System " + system + " is not valid.").rejectedValue(message.getDestination()).build()); } else if (!dossierDataService.isExistStatisticalMessageByMessageId(message.getMessageIdentification())) { dossierDataService.saveStatisticalMessage( createStatisticalMessage903(message.getMessageIdentification(), message.getPayload(), statisticsSystemEnum.getMessageSenderPrefix())); } else { log.warn("Ignoring saving 903 message to statistical message table with message ID {} because it has been already saved.", message.getMessageIdentification()); } violations = validationService.validateMovementMessage(message.getId()); if (!CollectionUtils.isEmpty(violations)) { MovementsOrViolations mov = MovementsOrViolations.of(Collections.emptyList(), violations); log.warn(":=> processMessage903() : {} Violation(s) found on Message Type [{}]. Will send error message and return", violations.size(), message.getMessageType()); handleViolations(mov, message, false); } } public void handle027(String messageXml) throws BadRequestException { try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); String mrn = XPATH.evaluate(MessageXPathsEnum.MESSAGE_MRN.getValue(), root); if (dossierDataService.existsMovementByMrn(mrn)) { processMessage(messageXml); } else { generateIE038ForUnknownMovement(messageXml); } } catch (XPathExpressionException | JAXBException e) { log.error("ERROR in handle027()", e); } catch (BadRequestException e) { throw new BadRequestException(e.getViolationList()); } } public void handle038(String messageXml) throws BadRequestException { try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); String mrn = XPATH.evaluate(MessageXPathsEnum.MESSAGE_MRN.getValue(), root); processMessage(messageXml); String officeOfRequest = XPATH.evaluate(MessageXPathsEnum.DESTINATION_OFFICE_OF_REQUEST_OFFICE_ID.getValue(), root); handleMovementQueryGlobalResponse(mrn, messageXml, officeOfRequest); } catch (XPathExpressionException e) { log.error("ERROR in handle038()", e); } catch (BadRequestException e) { throw new BadRequestException(e.getViolationList()); } } @SneakyThrows @Override public void processCcnReport(ErmisEvent ermisEvent) { CcnReportTypeEnum ccnReportTypeEnum = CcnReportTypeEnum.fromValue(ermisEvent.getEventType()); if (ccnReportTypeEnum == null) throw new IllegalArgumentException(String.format("Not a valid CCN Report Message ErmisEvent type: [%s]", ermisEvent.getEventType())); CcnReport ccnReport = CcnReport.builder() .ccnReportTypeEnum(ccnReportTypeEnum) .mrn(ermisEvent.getProperties().get("declarationId")) .originalMessageId(ermisEvent.getProperties().get("originalMessageId")) .build(); List<Message> originalMessages = dossierDataService.getMessagesByCriteria(ccnReport.getOriginalMessageId()) .stream() .filter(message -> Objects.equals(message.getDirection(), DirectionEnum.SENT.getDirection())) //.filter(message -> Objects.equals(message.getStatus(),MessageStatusEnum.ACCEPTED.name())) .collect(Collectors.toList()); if (!originalMessages.isEmpty()) { ccnReport.setOriginalMessageType(originalMessages.get(0).getMessageType()); } Message reportMessage = dossierDataService.persistMessage( setupCcnReportMessage(ccnReport, originalMessages.isEmpty() ? MessageStatusEnum.REJECTED : MessageStatusEnum.ACCEPTED)); log.info(":=> processCcnReport() : Received and persisted new CCN Report Message -> id: [{}], type: [{}], MRN: [{}] for Original Message Id: [{}]", reportMessage.getId(), reportMessage.getMessageType(), reportMessage.getMrn(), ccnReport.getOriginalMessageId()); if (originalMessages.isEmpty()) { log.error("processCcnReport() ERROR: Original Message NOT FOUND for CcnReport.originalMessageId: [{}]", ccnReport.getOriginalMessageId()); } else { List<Movement> existingMovements = dossierDataService.findAssociatedMovements(ccnReport.getOriginalMessageId(), DirectionEnum.SENT.getDirection()); handleMessageMovementAssociation(existingMovements, reportMessage); } } @Override public void processCCE46A(String messageXml) { try { documentsXmlValidator.validateXmlPayload(messageXml, MessageERMISTypes.CCE_46_A.value()); CCE46AType cce46AType = XmlConverter.buildMessageFromXML(messageXml, CCE46AType.class); Message savedMessage = dossierDataService.persistMessage(setupCCE46AMessage(cce46AType, messageXml)); Optional<MessageOverview> optionalMessage = dossierDataService.getMessagesOverview(null, MessageERMISTypes.CCE_60_A.value(), cce46AType.getCorrelationIdentifier(), null, null, null, 0, 20).stream() .findFirst(); MessageOverview message = optionalMessage.orElseThrow(() -> new NotFoundException("Couldn't find any message for correlationIdentifier of cce46A: " + cce46AType.getCorrelationIdentifier())); List<Movement> existingMovements = dossierDataService.findAssociatedMovements(message.getMessageIdentification(), DirectionEnum.SENT.getDirection()); if (CollectionUtils.isEmpty(existingMovements)) { throw new NotFoundException("Couldn't find any related movements for mrn " + cce46AType.getTransitOperation().getMRN() + " and lrn " + cce46AType.getTransitOperation().getLRN()); } dossierDataService.associateMessageWithMovement(savedMessage.getId(), existingMovements.get(0).getId()); documentResponseProducer.publish(cce46AType, existingMovements.get(0).getId()); } catch (SAXParseException exception) { log.error("CCE46A payload is not valid:"); log.error(exception.getMessage()); throw new BaseException("CCE46A payload is not valid", exception); } catch (JAXBException exception) { throw new BaseException("Error building class type from string xml", exception); } catch (IOException | SAXException exception) { throw new RuntimeException("Error during XSD validation", exception); } } private Message setupCCE46AMessage(CCE46AType cce46AType, String messageXml) { return Message.builder() .payload(messageXml) .messageIdentification(cce46AType.getMessageIdentification()) .messageType(cce46AType.getMessageType().value()) .mrn(cce46AType.getTransitOperation().getMRN()) .source(cce46AType.getMessageSender()) .destination(cce46AType.getMessageRecipient()) .domain(MessageDomainTypeEnum.EXTERNAL.name()) .direction(DirectionEnum.RECEIVED.getDirection()) .manualInserted(false) .status("") .build(); } private Message setupCcnReportMessage(CcnReport ccnReport, MessageStatusEnum messageStatusEnum) throws JsonProcessingException { return Message.builder() .messageIdentification(MessageUtil.generateMessageIdentification()) .messageType(ccnReport.getCcnReportTypeEnum().name()) .source("CCN") .destination("ERMIS") .payload(objectMapper.writeValueAsString(ccnReport)) .domain(MessageDomainTypeEnum.COMMON.name()) .mrn(ccnReport.getMrn()) .direction(DirectionEnum.RECEIVED.getDirection()) .status(messageStatusEnum.name()) .manualInserted(false) .build(); } public void generateIE038ForUnknownMovement(String messageXml) throws JAXBException, XPathExpressionException { Message message = dossierDataService.persistMessage(setUpMessage(messageXml, false, DirectionEnum.RECEIVED)); validateMovementMessage(message.getId()); //Gather data CD027CType cd027CType = XmlConverter.buildMessageFromXML(messageXml, CD027CType.class); //Compose message CD038CType cd038CType = composeCD038CMessage(cd027CType); dossierDataService.persistMessage( setUpMessage(XmlConverter.marshal(cd038CType, NamespacesEnum.NTA.getValue(), MessageTypes.CD_038_C.value()), false, DirectionEnum.SENT)); ddntaMessageProducer.publish(cd038CType, determineErmisEventBusinessKey(null, ObjectUtils.isNotEmpty(cd038CType.getTransitOperation()) ? cd038CType.getTransitOperation().getMRN() : null)); } private CD038CType composeCD038CMessage(CD027CType cd027CType) { CD038CType messageOut = messageTypeMapper.fromCD027CtoCD38C(cd027CType); messageOut.setMessageType(MessageTypes.CD_038_C); messageOut.setPreparationDateAndTime(LocalDateTime.now()); messageOut.setMessageIdentification(MessageUtil.generateMessageIdentification()); messageOut.setCorrelationIdentifier(cd027CType.getMessageIdentification()); log.debug("Handling 038 composition for missing MRN"); messageOut.setConsignment(null); messageOut.setTransitOperation(new TransitOperationType32()); messageOut.getTransitOperation().setRequestRejectionReasonCode(AarRejectionReasonEnum.MRN_UNKNOWN.getValue()); messageOut.getTransitOperation().setMRN(cd027CType.getTransitOperation().getMRN()); messageOut.setCustomsOfficeOfDeparture(null); messageOut.setHolderOfTheTransitProcedure(null); messageOut.setCustomsOfficeOfDestinationDeclared(null); messageOut.getCustomsOfficeOfExitForTransitDeclared().clear(); messageOut.getCustomsOfficeOfTransitDeclared().clear(); messageOut.setControlResult(null); messageOut.setMessageSender(constructMessageSender()); messageOut.setMessageRecipient(cd027CType.getMessageSender()); return messageOut; } public String constructMessageSender() { return MessageTypeMapper.NTA.concat(getCountryCodeService.getCountryCode()); } /** * In case Ermis Transit is the one who asked (sent the IE027) then we also need to update our movement query entry Otherwise Ermis Transit is answering * (with IE038) someone else's question (IE027) * * @param mrn * @param messageXml * @param officeOfRequest */ public void handleMovementQueryGlobalResponse(String mrn, String messageXml, String officeOfRequest) { log.info("handleMovementQueryGlobalResponse() start"); try { MovementQuery movementQuery = dossierDataService.findMovementQueriesByCriteria(mrn); movementQuery.setResponsePayload(messageXml); movementQuery.setRespondent(officeOfRequest); dossierDataService.updateMovementQuery(movementQuery); } catch (NotFoundException notFoundException) { log.info("Movement Query does not exist in our system, skip it"); } catch (BaseException exception) { log.error("Found more than one Movement Query"); } log.info("handleMovementQueryGlobalResponse() end"); } @SneakyThrows(BadRequestException.class) private void validateMovementMessage(String messageId) { List<Violation> violations = validationService.validateMovementMessage(messageId); if (!CollectionUtils.isEmpty(violations)) throw new BadRequestException(violations); } private MovementsOrViolations validateMessage(Message message) { MovementsOrViolations movementOrViolations = MovementsOrViolations.of(null, null); // get valid office roles & statuses List<OfficeRoleTypeStatuses> validStates = MessageValidationUtils.getValidStates(message.getMessageType()); // get existing movements List<Movement> existingMovements = getExistingMovements(message, validStates); // create dummy movements for office roles that have no existing movement List<Movement> movementsToCreate = createMovements(existingMovements, message, validStates); if (isExternalMessagesXsdValidationEnabled && MessageUtil.isExternalMessage(message.getMessageType()) && !message.isManualInserted()) { movementOrViolations = MovementsOrViolations.of(null, validationService.validateXsd(message.getId())); } // If no XSD violations exist (for external messages) or if it's a common domain message, proceed with state validation if (movementOrViolations.getViolations().isEmpty()) { if (existingMovements.isEmpty() && MessageUtil.isErrorMessageType(message.getMessageType())) { log.warn("validateMessage(): Could not correlate incoming rejection message of type {}. Ignoring... -> id=[{}], messageId=[{}], MRN=[{}]", message.getMessageType(), message.getId(), message.getMessageIdentification(), Optional.ofNullable(message.getMrn()).orElse("-")); return MovementsOrViolations.of(existingMovements, List.of()); } } /** * Special case of IE170 when MRN Communication is enabled. * SOS ! This validation needs to be executed BEFORE the {@link #getExistingMovements} call -> Modified due to bug ERMIS-40312 */ List<Violation> violationsIE170Mrn = ddntaMessageCustomValidationService.validateIE170MrnIfMrnCommunicationIsEnabled(message); if(!violationsIE170Mrn.isEmpty()) { return MovementsOrViolations.of(existingMovements, violationsIE170Mrn); } if (existingMovements.isEmpty() && MessageUtil.isErrorMessageType(message.getMessageType())) { log.warn("validateMessage(): Could not correlate incoming rejection message of type {}. Ignoring... -> id=[{}], messageId=[{}], MRN=[{}]", message.getMessageType(), message.getId(), message.getMessageIdentification(), Optional.ofNullable(message.getMrn()).orElse("-")); return MovementsOrViolations.of(existingMovements, List.of()); } List<Movement> allMovements = Stream.concat(existingMovements.stream(), movementsToCreate.stream()).collect(Collectors.toList()); movementOrViolations = messageValidationService.performStateValidation(message, allMovements); // If no state violations exist, do R&C validation (if required) if (movementOrViolations.getViolations().isEmpty() && isRCValidationNeeded(message)) { movementOrViolations = MovementsOrViolations.of(movementOrViolations.getMovements(), // Manually submitted messages need to also pass XSD validation (CCN does it normally) message.isManualInserted() ? validationService.validateMovementMessageAllValidations(message.getId()) : validationService.validateMovementMessage(message.getId())); } // If no R&C violations exist, do Authorization validation (if required) if (movementOrViolations.getViolations().isEmpty() && isAuthorizationValidationNeeded(message)) { movementOrViolations = MovementsOrViolations.of(movementOrViolations.getMovements(), validationService.validateSimplifiedProcedureMessage(message.getId())); } if (!movementOrViolations.getViolations().isEmpty()) { movementOrViolations = MovementsOrViolations.of( determineWhichMovementsToUseForAssociation(movementOrViolations.getViolations(), existingMovements, movementsToCreate, message), movementOrViolations.getViolations()); } return movementOrViolations; } private boolean isRCValidationNeeded(Message message) { return MessageUtil.isNotErrorMessageType(message.getMessageType()) && (!SKIP_RC_VALIDATION_LIST.contains(message.getMessageType()) || message.isManualInserted()); } private boolean isAuthorizationValidationNeeded(Message message) { return MessageUtil.isNotErrorMessageType(message.getMessageType()) && AUTHORIZATION_VALIDATION_LIST.contains(message.getMessageType()); } private List<Movement> getExistingMovements(Message message, List<OfficeRoleTypeStatuses> validOfficeRoleTypes) { List<Movement> existingMovements = new ArrayList<>(); Set<String> validOfficeRoleTypesSet = validOfficeRoleTypes.stream() .map(officeRoleTypeStatuses -> officeRoleTypeStatuses.getOfficeRoleType().getValue()) .collect(Collectors.toSet()); if (MessageUtil.isErrorMessageType(message.getMessageType())) { String correlationIdentifier = getCorrelationIdentifier(message.getPayload()); existingMovements = dossierDataService.findAssociatedMovements(correlationIdentifier, DirectionEnum.SENT.getDirection()); } else if (CUSTOM_TARGET_LIST.contains(message.getMessageType())) { // Get the proper movement for message types that need special handling existingMovements = getTargetMovements(message); } else if (!StringUtils.isBlank(message.getMrn())) { existingMovements = dossierDataService.findByCriteria(message.getMrn(), null, null, null, 50); } else if (!StringUtils.isBlank(message.getLrn()) && !MessageTypes.CC_015_C.value().equals(message.getMessageType()) && !com.intrasoft.ermis.cargov1.messages.MessageTypes.TB_015_C.value().equals(message.getMessageType())) { List<String> validDuplicateLrnStates = configurationSwitchService.getValidStatesForDuplicateLRN(); validDuplicateLrnStates.add(ProcessingStatusTypeEnum.OODEP_NONE.getDescription()); existingMovements = dossierDataService.findByCriteria(null, message.getLrn(), null, null, 99, configurationSwitchService.reuseLrnEnabled() ? getActiveMovementStates(validDuplicateLrnStates) : null ); } return existingMovements.stream() .filter(movement -> validOfficeRoleTypesSet.contains(movement.getOfficeRoleType())) .collect(Collectors.toList()); } @NotNull private List<String> getActiveMovementStates(List<String> validDuplicateLrnStates) { return Arrays.stream(ProcessingStatusTypeEnum.values()).filter(processingStatusTypeEnum -> (!validDuplicateLrnStates.contains(processingStatusTypeEnum.getDescription())) ).map(ProcessingStatusTypeEnum::getItemCode).collect(Collectors.toList()); } private void handleMovements(MovementsOrViolations mov, Message message) { mov.getMovements().forEach(movement -> { boolean isNewMovement = movement.getId() == null; Movement savedMovement = isNewMovement ? dossierDataService.createMovement(movement) : movement; if (isNewMovement) { saveTransportId(message.getPayload(), savedMovement.getId()); } dossierDataService.associateMessageWithMovement(message.getId(), savedMovement.getId()); if (MessageUtil.isErrorMessageType(message.getMessageType())) { // Error messages are not handled by office flows so there's no need for a PMC return; } processMessageCommandProducer.publish(message.getId(), message.getMessageType(), savedMovement); }); if (mov.getMovements().isEmpty()) { if (SKIP_MOVEMENT_EXISTENCE_LIST.contains(message.getMessageType())) { if (MessageTypes.CD_094_C.value().equals(message.getMessageType())) { String targetOfficeRole = decideOfficeRoleType(message); processMessageCommandProducer.publish(message.getId(), message.getMessageType(), targetOfficeRole); } else { processMessageCommandProducer.publish(message.getId(), message.getMessageType(), MESSAGE_TO_OFFICE.get(message.getMessageType())); } } else { log.warn("No associated movement found for messageId={} and messageType={}, but it is not marked to skip movement existence check", message.getId(), message.getMessageType()); } } } private String decideOfficeRoleType(Message message) { String targetOfficeRole = null; try (StringReader stringReader = new StringReader(message.getPayload())) { InputSource xml = new InputSource(stringReader); XPath xpath = XPathFactory.newInstance().newXPath(); Node root = (Node) xpath.evaluate("/", xml, XPathConstants.NODE); if (MessageTypes.CD_094_C.value().equals(message.getMessageType())) { if (!xpath.evaluate(MessageXPathsEnum.DESTINATION_OFFICE_ID.getValue(), root).isBlank()) { targetOfficeRole = OfficeRoleTypesEnum.DESTINATION.getValue(); } else if (!xpath.evaluate(MessageXPathsEnum.TRANSIT_OFFICE_ID.getValue(), root).isBlank()) { targetOfficeRole = OfficeRoleTypesEnum.TRANSIT.getValue(); } else if (!xpath.evaluate(MessageXPathsEnum.EXIT_FOR_TRANSIT_OFFICE_ID.getValue(), root).isBlank()) { targetOfficeRole = OfficeRoleTypesEnum.EXIT.getValue(); } else { // If no Office is found within the IE094, it should default to Destination role. targetOfficeRole = OfficeRoleTypesEnum.DESTINATION.getValue(); } } } catch (Exception e) { log.error("ERROR: Could not retrieve XML payload from Message."); } return targetOfficeRole; } private void handleViolations(MovementsOrViolations mov, Message message, boolean manuallySubmitted) throws BadRequestException, XPathExpressionException { if (manuallySubmitted) { sendBadRequest(mov.getViolations()); } else if (XSD_ERROR_REASON.equals(mov.getViolations().get(0).getReason())) { List<Movement> savedMovements = handleMessageMovementAssociation(mov.getMovements(), message); if (MessageTypes.CC_015_C.value().equals(message.getMessageType())) { dossierDataService.saveProcessingStatus(ProcessingStatus.builder() .status(ProcessingStatusTypeEnum.OODEP_REJECTED.getItemCode()) .movementId(savedMovements.get(0).getId()) .build()); } sendXsdErrorMessage(message.getPayload(), MovementsOrViolations.of(savedMovements, mov.getViolations())); } else { if (MessageUtil.isCargoMessage(message.getMessageType())) { sendCargoErrorMessage(message.getPayload(), message.getMessageType(), mov); } else { handleMessageMovementAssociation(mov.getMovements(), message); sendErrorMessage(message.getPayload(), message.getMessageType(), mov); } } } private List<Movement> handleMessageMovementAssociation(List<Movement> movements, Message message) { final List<Movement> savedMovements = new ArrayList<>(); movements.forEach(movement -> { Movement savedMovement = movement.getId() != null ? movement : dossierDataService.createMovement(movement); savedMovements.add(savedMovement); dossierDataService.associateMessageWithMovement(message.getId(), savedMovement.getId()); }); return savedMovements; } private void sendBadRequest(List<Violation> violations) throws BadRequestException { throw new BadRequestException(violations); } private void sendErrorMessage(String messageXml, String messageType, MovementsOrViolations mov) throws XPathExpressionException { if (MessageTypes.CC_007_C.value().equals(messageType) || MessageTypes.CC_044_C.value().equals(messageType)) { CC057CType cc057 = createCC057CMessage(messageXml, mov.getViolations()); Message message = dossierDataService.persistMessage( setUpMessage(XmlConverter.marshal(cc057, NamespacesEnum.NTA.getValue(), MessageTypes.CC_057_C.value()), false, DirectionEnum.SENT)); handleMessageMovementAssociation(mov.getMovements(), message); ddntaMessageProducer.publish(cc057, determineErmisEventBusinessKey(ObjectUtils.isNotEmpty(mov.getMovements()) ? mov.getMovements().get(0) : null, ObjectUtils.isNotEmpty(cc057.getTransitOperation()) ? cc057.getTransitOperation().getMRN() : null)); } else if (MessageTypes.CC_013_C.value().equals(messageType) || MessageTypes.CC_014_C.value().equals(messageType) || MessageTypes.CC_170_C.value().equals(messageType) || MessageTypes.CC_141_C.value().equals(messageType) || MessageTypes.CC_015_C.value().equals(messageType)) { // Only in case of custom Validations. No movement will be created CC056CType cc056 = createCC056CMessage(messageXml, mov); Message message = dossierDataService.persistMessage( setUpMessage(XmlConverter.marshal(cc056, NamespacesEnum.NTA.getValue(), MessageTypes.CC_056_C.value()), false, DirectionEnum.SENT)); handleMessageMovementAssociation(mov.getMovements(), message); ddntaMessageProducer.publish(cc056, determineErmisEventBusinessKey(ObjectUtils.isNotEmpty(mov.getMovements()) ? mov.getMovements().get(0) : null, ObjectUtils.isNotEmpty(cc056.getTransitOperation()) ? cc056.getTransitOperation().getMRN() : null)); } else if (messageType.startsWith(CC)) { CC906CType cc906 = createCCM906CMessage(messageXml, mov.getViolations()); cc906.setMessageSender(constructMessageSender()); String namespace = decideNamespaceForCC906C(cc906); Message message = dossierDataService.persistMessage( setUpMessage(XmlConverter.marshal(cc906, namespace, MessageTypes.CC_906_C.value()), false, DirectionEnum.SENT)); handleMessageMovementAssociation(mov.getMovements(), message); ddntaMessageProducer.publish(cc906, messageType, namespace, determineErmisEventBusinessKey(ObjectUtils.isNotEmpty(mov.getMovements()) ? mov.getMovements().get(0) : null, ObjectUtils.isNotEmpty(cc906.getHeader()) ? cc906.getHeader().getMRN() : null)); } else { CD906CType cd906 = createCDM906CMessage(messageXml, mov.getViolations()); cd906.setMessageSender(constructMessageSender()); Message message = dossierDataService.persistMessage( setUpMessage(XmlConverter.marshal(cd906, NamespacesEnum.NTA.getValue(), MessageTypes.CD_906_C.value()), false, DirectionEnum.SENT)); handleMessageMovementAssociation(mov.getMovements(), message); ddntaMessageProducer.publish(cd906, determineErmisEventBusinessKey(ObjectUtils.isNotEmpty(mov.getMovements()) ? mov.getMovements().get(0) : null, ObjectUtils.isNotEmpty(cd906.getHeader()) ? cd906.getHeader().getMRN() : null)); createAndPersistRejectedMessageInfo(cd906, message.getId(), DirectionEnum.SENT, mov.getMovements()); } } @SneakyThrows private void sendXsdErrorMessage(String messageXml, MovementsOrViolations mov) { CC917CType cc917CType = generateMessageService.generateCC917C(messageXml, mov.getViolations()); Message message = dossierDataService.persistMessage( setUpMessage(XmlConverter.marshal(cc917CType, NamespacesEnum.NTA.getValue(), MessageTypes.CC_917_C.value()), false, DirectionEnum.SENT)); handleMessageMovementAssociation(mov.getMovements(), message); ddntaMessageProducer.publish(cc917CType, determineErmisEventBusinessKey(ObjectUtils.isNotEmpty(mov.getMovements()) ? mov.getMovements().get(0) : null, ObjectUtils.isNotEmpty(cc917CType.getHeader()) ? cc917CType.getHeader().getMRN() : null)); } private String decideNamespaceForCC906C(CC906CType cc906CTypeMessage) { String recipient = cc906CTypeMessage.getMessageRecipient(); if (recipient != null && recipient.startsWith(NECA)) { return NamespacesEnum.AES.getValue(); } else { return NamespacesEnum.NTA.getValue(); } } private void sendCargoErrorMessage(String messageXml, String messageType, MovementsOrViolations mov) throws XPathExpressionException { if (com.intrasoft.ermis.cargov1.messages.MessageTypes.TB_007_C.value().equals(messageType)) { com.intrasoft.ermis.cargov1.messages.CC057CType cc057cTypeMessage = cargoMessageService.createCargoCC057CMessage(messageXml, mov.getViolations()); Message message = dossierDataService.persistMessage( setUpMessage(XmlConverter.marshal(cc057cTypeMessage, NamespacesEnum.NTA.getValue(), com.intrasoft.ermis.cargov1.messages.MessageTypes.CC_057_C.value()), false, DirectionEnum.SENT)); handleMessageMovementAssociation(mov.getMovements(), message); ddntaMessageProducer.cargoPublish(cc057cTypeMessage, determineErmisEventBusinessKey(ObjectUtils.isNotEmpty(mov.getMovements()) ? mov.getMovements().get(0) : null, ObjectUtils.isNotEmpty(cc057cTypeMessage.getTransitOperation()) ? cc057cTypeMessage.getTransitOperation().getMRN() : null) ); } } private void createAndPersistRejectedMessageInfo(CD906CType cd906CType, String rejectionMessageId, DirectionEnum direction, List<Movement> movements) { List<Message> correlatedMessages = dossierDataService.getMessagesByCriteria(cd906CType.getCorrelationIdentifier()); if (!correlatedMessages.isEmpty()) { RejectedMessage rejectedMessage = RejectedMessage.builder() .mrn(cd906CType.getHeader().getMRN()) .amendmentSent(false) .destination(cd906CType.getMessageRecipient()) .source(cd906CType.getMessageSender()) .direction(direction.getDirection()) .domain(DomainEnum.NCTS.getValue()) .rejectionMessageId(rejectionMessageId) .referencedMessageId(correlatedMessages.get(0).getId()) .referencedMessageType(correlatedMessages.get(0).getMessageType()) .build(); if (movements.isEmpty()) { dossierDataService.saveRejectedMessage(rejectedMessage); } else { movements.forEach(movement -> { rejectedMessage.setMovementId(movement.getId()); rejectedMessage.setOfficeId(movement.getOfficeId()); dossierDataService.saveRejectedMessage(rejectedMessage); }); } } else { throw new NotFoundException("Couldn't find correlated message"); } } private List<Movement> createMovements(List<Movement> existingMovements, Message message, List<OfficeRoleTypeStatuses> validStates) { List<Movement> createdMovements = new ArrayList<>(); if (MessageUtil.isErrorMessageType(message.getMessageType())) { return createdMovements; } List<String> officeRoleTypesWithoutExistingMovements = getOfficeRoleTypesWithoutExistingMovements(validStates, existingMovements); if (MessageTypes.CC_015_C.value().equals(message.getMessageType())) { officeRoleTypesWithoutExistingMovements = getAppropriateOfficeRoleType(message.getPayload(), officeRoleTypesWithoutExistingMovements); } if (officeRoleTypesWithoutExistingMovements.isEmpty()) { return createdMovements; } String operatingCountryCode = getCountryCodeService.getCountryCode(); for (String officeRoleType : officeRoleTypesWithoutExistingMovements) { if (shouldCreateMovement(officeRoleType, message, operatingCountryCode, existingMovements)) { List<String> officeIds = getOfficeIds(message.getPayload(), officeRoleType); for (String officeId : officeIds) { if (isOfficeIdValid(message, officeRoleType, officeId, operatingCountryCode)) { createdMovements.add(setUpMovement(message, officeRoleType, officeId)); } else { log.warn( "createMovements(): OfficeId: [{}] for MRN: [{}], MessageType: [{}], and OfficeRoleType: [{}] is not Valid. Will Not create NEW Movement", officeId, message.getMrn(), message.getMessageType(), officeRoleType); } } } } return createdMovements; } private List<String> getOfficeRoleTypesWithoutExistingMovements(List<OfficeRoleTypeStatuses> validOfficeRoleTypeStatusesList, List<Movement> existingMovements) { if (existingMovements.isEmpty()) { return validOfficeRoleTypeStatusesList.stream() .filter(officeRoleTypeStatuses -> officeRoleTypeStatuses.getStatuses().isEmpty() || MessageValidationUtils.noneStatusAllowed(officeRoleTypeStatuses.getOfficeRoleType(), officeRoleTypeStatuses.getStatuses())) .map(officeRoleTypeStatuses -> officeRoleTypeStatuses.getOfficeRoleType().getValue()) .collect(Collectors.toList()); } List<String> officeRoleTypesWithoutExistingMovement = new ArrayList<>(); for (OfficeRoleTypeStatuses officeRoleType : validOfficeRoleTypeStatusesList) { if (officeRoleTypeNotInMovement(existingMovements, officeRoleType)) { officeRoleTypesWithoutExistingMovement.add(officeRoleType.getOfficeRoleType().getValue()); } } return officeRoleTypesWithoutExistingMovement; } private boolean officeRoleTypeNotInMovement(List<Movement> existingMovements, OfficeRoleTypeStatuses officeRoleType) { return existingMovements.stream() .noneMatch(existingMovement -> existingMovement.getOfficeRoleType() .equals(officeRoleType.getOfficeRoleType() .getValue())); } private String getCorrelationIdentifier(String messageXml) { String correlationIdentifier = null; try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); correlationIdentifier = XPATH.evaluate(MessageXPathsEnum.CORRELATION_IDENTIFIER.getValue(), root); } catch (XPathExpressionException ex) { log.error("Exception while setting the office Id", ex); } return correlationIdentifier; } private List<Movement> getTargetMovements(Message message) { List<Movement> movementList = new ArrayList<>(); MessageTypes messageType = MessageTypes.fromValue(message.getMessageType()); List<Pair<String, Movement>> pairs; switch (messageType) { case CD_094_C: pairs = getCD094CTargets(message); break; case CD_150_C: pairs = getCD150CTargets(message); break; case CD_152_C: pairs = getCD152Targets(message); break; default: pairs = List.of(); } movementList.addAll(pairs.stream() .map(Pair::getE2) .collect(Collectors.toList())); return movementList; } private List<Pair<String, Movement>> getCD094CTargets(Message message) { try (StringReader sr = new StringReader(message.getPayload())) { InputSource xml = new InputSource(sr); XPath xpath = XPathFactory.newInstance().newXPath(); Node root = (Node) xpath.evaluate("/", xml, XPathConstants.NODE); String targetOfficeId = null; Movement targetMovement; if (!xpath.evaluate(MessageXPathsEnum.TRANSIT_OFFICE_ID.getValue(), root).isBlank()) { targetOfficeId = xpath.evaluate(MessageXPathsEnum.TRANSIT_OFFICE_ID.getValue(), root); targetMovement = dossierDataService.findSingleMovementByCriteria(message.getMrn(), OfficeRoleTypesEnum.TRANSIT.getValue(), targetOfficeId, null); } else if (!xpath.evaluate(MessageXPathsEnum.EXIT_FOR_TRANSIT_OFFICE_ID.getValue(), root).isBlank()) { targetOfficeId = xpath.evaluate(MessageXPathsEnum.EXIT_FOR_TRANSIT_OFFICE_ID.getValue(), root); targetMovement = dossierDataService.findSingleMovementByCriteria(message.getMrn(), OfficeRoleTypesEnum.EXIT.getValue(), targetOfficeId, null); } else { // If Destination OR no Office is found within the IE094 , it should default to Destination role Movement. targetMovement = dossierDataService.findSingleMovementByCriteria(message.getMrn(), OfficeRoleTypesEnum.DESTINATION.getValue(), null, null); if (ObjectUtils.isNotEmpty(targetMovement)) { targetOfficeId = targetMovement.getOfficeId(); } } if (targetOfficeId != null && targetMovement != null) { return List.of(Pair.of(targetOfficeId, targetMovement)); } } catch (Exception e) { log.warn("Could not find target movement for incoming IE094 message [id={}, messageId={}]", message.getId(), message.getMessageIdentification()); } return List.of(); } private List<Pair<String, Movement>> getCD150CTargets(Message message) { try (StringReader sr = new StringReader(message.getPayload())) { InputSource xml = new InputSource(sr); XPath xpath = XPathFactory.newInstance().newXPath(); Node root = (Node) xpath.evaluate("/", xml, XPathConstants.NODE); Movement targetMovement; String customsOfficeOfRecoveryRequested = xpath.evaluate(MessageXPathsEnum.RECOVERY_REQUESTED_OFFICE_ID.getValue(), root); String mrn = xpath.evaluate(MessageXPathsEnum.MESSAGE_MRN.getValue(), root); // We don't use officeIDs as for some countries only a single office can handle the recovery request, while for other countries this is not the case List<Movement> movementList = dossierDataService.findByCriteria(mrn, null, null, null, 99); targetMovement = findTargetMovementForIncomingIE150(mrn, movementList, getCountryCodeService.getCountryCode()); if (targetMovement != null) { return List.of(Pair.of(customsOfficeOfRecoveryRequested, targetMovement)); } } catch (Exception e) { throw new BaseException(String.format("ERROR on finding target movement for incoming IE150 message [id=%s, messageId=%s]", message.getId(), message.getMessageIdentification()), e); } return List.of(); } private List<Pair<String, Movement>> getCD152Targets(Message message) { try { InputSource xml = new InputSource(new StringReader(message.getPayload())); XPath xpath = XPathFactory.newInstance().newXPath(); Node root = (Node) xpath.evaluate("/", xml, XPathConstants.NODE); String messageSender = xpath.evaluate(MessageXPathsEnum.MESSAGE_SENDER.getValue(), root); String messageSource = messageSender.substring(messageSender.lastIndexOf(".") + 1); String mrn = xpath.evaluate(MessageXPathsEnum.MESSAGE_MRN.getValue(), root); List<Movement> currentMovementList = dossierDataService.findByCriteria(mrn, null, null, null, 99); List<Movement> targetMovements = findTargetMovementForIncomingIE152(mrn, messageSource, currentMovementList); if (!targetMovements.isEmpty()) { List<Pair<String, Movement>> listOfMovements = new ArrayList<>(); for (Movement m : targetMovements) { listOfMovements.add(Pair.of("", m)); } return listOfMovements; } } catch (XPathExpressionException e) { throw new BaseException(String.format("ERROR while reading incoming IE152 messageXML [id=%s, messageId=%s]", message.getId(), message.getMessageIdentification()), e); } return List.of(); } private List<String> getAppropriateOfficeRoleType(String messageXml, List<String> officeRoleTypesWithoutExistingMovements) { List<String> officeRoleTypes = new ArrayList<>(); try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); String declarationType = XPATH.evaluate(DECLARATION_TYPE, root); if (isDeclarationTypeOfficeOfLodgment(declarationType)) { // office role should be that of LODGEMENT officeRoleTypes = officeRoleTypesWithoutExistingMovements.stream().filter(office -> office.equals(OfficeRoleTypesEnum.LODGEMENT.getValue())) .collect(Collectors.toList()); } else { officeRoleTypes = officeRoleTypesWithoutExistingMovements.stream().filter(office -> office.equals(OfficeRoleTypesEnum.DEPARTURE.getValue())) .collect(Collectors.toList()); } } catch (XPathExpressionException ex) { log.error("Exception while setting the officeRoleTypes for incoming CC015C", ex); } log.info("getAppropriateOfficeRoleType() for OfficeRoleTypes: [{}]. Will return: {}", officeRoleTypesWithoutExistingMovements, officeRoleTypes); return officeRoleTypes; } private boolean isDeclarationTypeOfficeOfLodgment(String declarationType) { return "EXIT".equals(declarationType) || "ENTRY".equals(declarationType); } private List<String> getOfficeIds(String messageXml, String officeRoleType) { List<String> officeIds = new ArrayList<>(); try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); if (officeRoleType.equals(OfficeRoleTypesEnum.DEPARTURE.getValue()) || officeRoleType.equals(OfficeRoleTypesEnum.LODGEMENT.getValue())) { String officeOfDepartureId = XPATH.evaluate(MessageXPathsEnum.DEPARTURE_OFFICE_ID.getValue(), root); officeIds.add(officeOfDepartureId); } else if (officeRoleType.equals(OfficeRoleTypesEnum.DESTINATION.getValue()) || officeRoleType.equals(OfficeRoleTypesEnum.CARGO_DESTINATION.getValue())) { String officeOfDestinationId = getDestinationOfficeId(XPATH, root); if (StringUtils.isNotEmpty(officeOfDestinationId)) { officeIds.add(officeOfDestinationId); } } else if (officeRoleType.equals(OfficeRoleTypesEnum.TRANSIT.getValue())) { addTransitIds(XPATH, root, officeIds); } else if (officeRoleType.equals(OfficeRoleTypesEnum.INCIDENT.getValue())) { addOfficeIncidentIds(XPATH, root, officeIds); } else if (officeRoleType.equals(OfficeRoleTypesEnum.EXIT.getValue())) { addExitForTransitIds(XPATH, root, officeIds); } addCommonOfficeIds(XPATH, root, officeIds); } catch (XPathExpressionException ex) { log.error("Exception while setting the office Id", ex); } log.info("getOfficeIds() for OfficeRoleType: [{}]. Will return: {}", officeRoleType, officeIds); return officeIds; } private String getDestinationOfficeId(XPath xpath, Node root) { String destinationOfficeId = null; try { if (!xpath.evaluate(MessageXPathsEnum.DESTINATION_DECLARED_OFFICE_ID.getValue(), root).isBlank()) { destinationOfficeId = xpath.evaluate(MessageXPathsEnum.DESTINATION_DECLARED_OFFICE_ID.getValue(), root); } else if (!xpath.evaluate(MessageXPathsEnum.DESTINATION_ACTUAL_OFFICE_ID.getValue(), root).isBlank()) { destinationOfficeId = xpath.evaluate(MessageXPathsEnum.DESTINATION_ACTUAL_OFFICE_ID.getValue(), root); } else if (!xpath.evaluate(MessageXPathsEnum.DESTINATION_OFFICE_OF_REQUEST_OFFICE_ID.getValue(), root) .isBlank()) { // covers destinationId office for IE142 destinationOfficeId = xpath.evaluate(MessageXPathsEnum.DESTINATION_OFFICE_OF_REQUEST_OFFICE_ID.getValue(), root); } } catch (XPathExpressionException ex) { log.error("Exception while getting the destination office Id", ex); } return destinationOfficeId; } private void addTransitIds(XPath xpath, Node root, List<String> officeIds) throws XPathExpressionException { NodeList officeOfTransitIdList = (NodeList) xpath.evaluate(MessageXPathsEnum.TRANSIT_DECLARED_OFFICE_ID.getValue(), root, XPathConstants.NODESET); if (officeOfTransitIdList.getLength() > 0) { for (int i = 0; i < officeOfTransitIdList.getLength(); i++) { officeIds.add(officeOfTransitIdList.item(i).getNodeValue()); } } else { NodeList officeOfTransitActualIdList = (NodeList) xpath.evaluate(MessageXPathsEnum.TRANSIT_ACTUAL_OFFICE_ID.getValue(), root, XPathConstants.NODESET); for (int i = 0; i < officeOfTransitActualIdList.getLength(); i++) { officeIds.add(officeOfTransitActualIdList.item(i).getNodeValue()); } } } private void addOfficeIncidentIds(XPath xpath, Node root, List<String> officeIds) throws XPathExpressionException { NodeList officeOfIncidentIdList = (NodeList) xpath.evaluate(MessageXPathsEnum.INCIDENT_DECLARED_OFFICE_ID.getValue(), root, XPathConstants.NODESET); if (officeOfIncidentIdList.getLength() > 0) { for (int i = 0; i < officeOfIncidentIdList.getLength(); i++) { officeIds.add(officeOfIncidentIdList.item(i).getNodeValue()); } } } private void addExitForTransitIds(XPath xpath, Node root, List<String> officeIds) throws XPathExpressionException { NodeList officeOfExitForTransitIdList = (NodeList) xpath.evaluate(MessageXPathsEnum.EXIT_FOR_TRANSIT_DECLARED_OFFICE_ID.getValue(), root, XPathConstants.NODESET); if (officeOfExitForTransitIdList.getLength() > 0) { for (int i = 0; i < officeOfExitForTransitIdList.getLength(); i++) { officeIds.add(officeOfExitForTransitIdList.item(i).getNodeValue()); } } } private void addCommonOfficeIds(XPath xpath, Node root, List<String> officeIds) { try { if (!xpath.evaluate(MessageXPathsEnum.RECOVERY_REQUESTED_OFFICE_ID.getValue(), root).isBlank()) { String recoveryOfficeId = xpath.evaluate(MessageXPathsEnum.RECOVERY_REQUESTED_OFFICE_ID.getValue(), root); if (!officeIds.contains(recoveryOfficeId)) { officeIds.add(recoveryOfficeId); } } } catch (XPathExpressionException ex) { log.warn("Could not find a recovery requested office Id", ex); } } private Movement setUpMovement(Message message, String officeRoleType, String officeId) { return Movement.builder() .officeRoleType(officeRoleType) .officeId(officeId) .mrn(message.getMrn()) .lrn(message.getLrn()) .simplified(isMovementSimplified(message.getPayload())) .build(); } private boolean isMovementSimplified(String payload) { Document message = XmlConverter.convertStringToXMLDocument(payload); boolean isMovementSimplified = false; try { NodeList authorisationTypeNodeList = (NodeList) XPATH.compile("//Authorisation/type").evaluate(message, XPathConstants.NODESET); for (int i = 0; i < authorisationTypeNodeList.getLength(); i++) { if (SIMPLIFIED_AUTHORISATION.equals(authorisationTypeNodeList.item(i).getTextContent())) { isMovementSimplified = true; break; } } } catch (XPathExpressionException e) { log.error("Error getting XPath ", e); } return isMovementSimplified; } @Override public Message setUpMessage(String messageXml, boolean manualInserted, DirectionEnum direction) throws XPathExpressionException { Message message; try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); final String messageType = XPATH.evaluate(MessageXPathsEnum.MESSAGE_TYPE.getValue(), root); message = Message.builder() .messageIdentification(XPATH.evaluate(MessageXPathsEnum.MESSAGE_IDENTIFICATION.getValue(), root)) .messageType(messageType) .source(XPATH.evaluate(MessageXPathsEnum.MESSAGE_SENDER.getValue(), root)) .destination(XPATH.evaluate(MessageXPathsEnum.MESSAGE_RECIPIENT.getValue(), root)) .payload(messageXml) .domain(messageType.startsWith(CC) || messageType.startsWith(TB) ? MessageDomainTypeEnum.EXTERNAL.name() : MessageDomainTypeEnum.COMMON.name()) .lrn(XPATH.evaluate(MessageXPathsEnum.MESSAGE_LRN.getValue(), root)) .mrn(getMrnFromXpath(root, messageType)) .manualInserted(manualInserted) .direction(direction.getDirection()) .build(); log.debug("Message assembled: {}", message.toString()); } catch (XPathExpressionException ex) { log.error("Exception while setting up the message for dossier ", ex); throw new XPathExpressionException("XPathExpressionException while processing incoming message. " + ex.getCause().getMessage()); } return message; } @Nullable private String getMrnFromXpath(Node root, String messageType) throws XPathExpressionException { if (MessageTypes.CD_974_C.value().equals(messageType)) return XPATH.evaluate(MessageXPathsEnum.CD974C_MESSAGE_MRN.getValue(), root).isBlank() ? null : XPATH.evaluate(MessageXPathsEnum.CD974C_MESSAGE_MRN.getValue(), root); return XPATH.evaluate(MessageXPathsEnum.MESSAGE_MRN.getValue(), root).isBlank() ? null : XPATH.evaluate(MessageXPathsEnum.MESSAGE_MRN.getValue(), root); } protected CD906CType createCDM906CMessage(String messageXml, List<Violation> violations) { List<Violation> reportedViolations; if (transitionPeriodService.isNowNCTSTransitionPeriod()) { reportedViolations = trimRejectedValues(violations); } else { reportedViolations = violations; } CD906CType cd906cType = IE906Generator.generateCD906CFromInvalidDDNTAMessage(messageXml, ViolationUtils.toIE906ViolationList(reportedViolations)); cd906cType.setMessageSender(constructMessageSender()); return cd906cType; } protected CC906CType createCCM906CMessage(String messageXml, List<Violation> violations) { CC906CType cc906cType = IE906Generator.generateCC906CFromInvalidDDNTAMessage(messageXml, ViolationUtils.toIE906ViolationList(violations)); cc906cType.setMessageSender(constructMessageSender()); return cc906cType; } protected CC056CType createCC056CMessage(String messageXml, MovementsOrViolations mov) { CC056CType messageOut = new CC056CType(); try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); messageOut.setMessageSender(constructMessageSender()); messageOut.setMessageRecipient(XPATH.evaluate(MessageXPathsEnum.MESSAGE_SENDER.getValue(), root)); messageOut.setPreparationDateAndTime(LocalDateTime.now(ZoneOffset.UTC)); messageOut.setMessageIdentification(MessageUtil.generateMessageIdentification()); messageOut.setMessageType(MessageTypes.CC_056_C); messageOut.setCorrelationIdentifier(XPATH.evaluate(MessageXPathsEnum.MESSAGE_IDENTIFICATION.getValue(), root)); TransitOperationType20 transitOperationType20 = new TransitOperationType20(); transitOperationType20.setLRN(checkIfXpathIsEmptyString(MessageXPathsEnum.MESSAGE_LRN.getValue(), root)); transitOperationType20.setMRN(checkIfXpathIsEmptyString(MessageXPathsEnum.MESSAGE_MRN.getValue(), root)); transitOperationType20.setBusinessRejectionType(XPATH.evaluate(MessageXPathsEnum.MESSAGE_TYPE.getValue(), root).substring(2, 5)); transitOperationType20.setRejectionDateAndTime(LocalDateTime.now(ZoneOffset.UTC)); transitOperationType20.setRejectionCode("12"); transitOperationType20.setRejectionReason(null); messageOut.setTransitOperation(transitOperationType20); CustomsOfficeOfDepartureType03 customsOfficeOfDepartureType03 = createCustomsOfficeOfDeparture(root, mov.getMovements()); messageOut.setCustomsOfficeOfDeparture(customsOfficeOfDepartureType03); HolderOfTheTransitProcedureType08 holderOfTheTransitProcedureType08 = new HolderOfTheTransitProcedureType08(); holderOfTheTransitProcedureType08.setIdentificationNumber(checkIfXpathIsEmptyString(IDENTIFICATION_NUMBER, root)); holderOfTheTransitProcedureType08.setTIRHolderIdentificationNumber(checkIfXpathIsEmptyString(TIR_IDENTIFICATION_NUMBER, root)); holderOfTheTransitProcedureType08.setName(checkIfXpathIsEmptyString(NAME, root)); holderOfTheTransitProcedureType08.setAddress(createAddress(root)); messageOut.setHolderOfTheTransitProcedure(holderOfTheTransitProcedureType08); messageOut.setRepresentative(createRepresentative(root)); for (Violation violation : mov.getViolations()) { messageOut.getFunctionalError().add(getCCFunctionalErrorType04(violation)); } } catch (XPathExpressionException e) { log.error(e.getLocalizedMessage()); } return messageOut; } protected CC057CType createCC057CMessage(String messageXml, List<Violation> violations) { CC057CType messageOut = new CC057CType(); try (StringReader sr = new StringReader(messageXml)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); messageOut.setMessageSender(constructMessageSender()); messageOut.setMessageRecipient(XPATH.evaluate(MessageXPathsEnum.MESSAGE_SENDER.getValue(), root)); messageOut.setPreparationDateAndTime(LocalDateTime.now(ZoneOffset.UTC)); messageOut.setMessageIdentification(MessageUtil.generateMessageIdentification()); messageOut.setMessageType(MessageTypes.CC_057_C); messageOut.setCorrelationIdentifier(XPATH.evaluate(MessageXPathsEnum.MESSAGE_IDENTIFICATION.getValue(), root)); TransitOperationType21 transitOperationType21 = new TransitOperationType21(); transitOperationType21.setMRN(XPATH.evaluate(MessageXPathsEnum.MESSAGE_MRN.getValue(), root)); transitOperationType21.setBusinessRejectionType(XPATH.evaluate(MessageXPathsEnum.MESSAGE_TYPE.getValue(), root).substring(2, 5)); transitOperationType21.setRejectionDateAndTime(LocalDateTime.now(ZoneOffset.UTC)); transitOperationType21.setRejectionCode("12"); transitOperationType21.setRejectionReason(null); messageOut.setTransitOperation(transitOperationType21); CustomsOfficeOfDestinationActualType03 customsOfficeOfDestinationActualType03 = new CustomsOfficeOfDestinationActualType03(); customsOfficeOfDestinationActualType03.setReferenceNumber(XPATH.evaluate(MessageXPathsEnum.DESTINATION_ACTUAL_OFFICE_ID.getValue(), root)); messageOut.setCustomsOfficeOfDestinationActual(customsOfficeOfDestinationActualType03); TraderAtDestinationType03 traderAtDestinationType03 = new TraderAtDestinationType03(); traderAtDestinationType03.setIdentificationNumber(XPATH.evaluate(IDENTIFICATION_NUMBER_TRADER_AT_DEST, root)); messageOut.setTraderAtDestination(traderAtDestinationType03); for (Violation violation : violations) { messageOut.getFunctionalError().add(getCCFunctionalErrorType04(violation)); } } catch (XPathExpressionException e) { log.error(e.getLocalizedMessage()); } return messageOut; } private StatisticalMessage createStatisticalMessage903(String messageIdentification, String payload, String regime) { return StatisticalMessage.builder() .messageId(messageIdentification) .messageType(MessageTypes.CD_903_D.value()) .payload(payload) .regime(regime) .build(); } private FunctionalErrorType04 getCCFunctionalErrorType04(Violation violation) { FunctionalErrorType04 functionalError = new FunctionalErrorType04(); functionalError.setErrorPointer(violation.getFieldName()); functionalError.setErrorCode(violation.getCode()); functionalError.setErrorReason(violation.getReason()); if (!Objects.isNull(violation.getRejectedValue()) && StringUtils.isNotBlank(violation.getRejectedValue().toString())) functionalError.setOriginalAttributeValue(violation.getRejectedValue().toString()); return functionalError; } private boolean isOfficeIdValid(Message message, String officeRoleType, String officeId, String countryCode) { OfficeRoleTypesEnum officeRoleTypesEnum = OfficeRoleTypesEnum.of(officeRoleType); switch (officeRoleTypesEnum) { case DEPARTURE: return true; case DESTINATION: if (OODEST_SKIP_OFFICE_ID_VALIDATION_MESSAGE_TYPES.contains(message.getMessageType())) { return true; } else { return officeId.startsWith(countryCode) || getCountryCodeService.getAccommodatingCountryCodes() .contains(MessageUtil.extractOfficeCountryCode(officeId)); } case INCIDENT: case TRANSIT: case EXIT: case LODGEMENT: case CARGO_DESTINATION: return officeId.startsWith(countryCode) || getCountryCodeService.getAccommodatingCountryCodes() .contains(MessageUtil.extractOfficeCountryCode(officeId)); default: return false; } } /** * Used to handle special cases that need an extra check in order to decide whether to create a movement for a specific office role */ private boolean shouldCreateMovement(String officeRoleType, Message message, String countryCode, List<Movement> existingMovements) { if(MessageUtil.isCCOrCDMessage(message.getMessageType())) { MessageTypes messageType = MessageTypes.fromValue(message.getMessageType()); switch (messageType) { case CD_150_C: return shouldCreateMovementForCD150C(officeRoleType, message, countryCode, existingMovements); case CD_114_C: return shouldCreateMovementForCD114C(officeRoleType, message, existingMovements); case CD_094_C: case CD_144_C: case CD_142_C: case CD_002_C: case CD_164_C: case CD_059_C: return false; default: return true; } } else if (MessageUtil.isCargoMessage(message.getMessageType())) { return true; } else { log.error("Invalid message type for message {}", message.getMessageType()); return false; } } /** * For officeRoleType in (DESTINATION) then create Movement only if CountryCode of the IE150 MRN is NOT the Operating Country Code */ private boolean shouldCreateMovementForCD150C(String officeRoleType, Message message, String operatingCountryCode, List<Movement> existingMovements) { OfficeRoleTypesEnum officeRoleTypesEnum = OfficeRoleTypesEnum.of(officeRoleType); if (!existingMovements.isEmpty()) { log.info("shouldCreateMovementForCD150C() : is FALSE for OfficeRoleType [{}] cause [{}] already existing movement(s) where found: {}", officeRoleType, existingMovements.size(), existingMovements.stream().map(Movement::toStringShort).collect(Collectors.toList())); return false; } switch (officeRoleTypesEnum) { case DESTINATION: if (!extractMRNCountryCode(message.getMrn()).equalsIgnoreCase(operatingCountryCode)) { log.info("shouldCreateMovementForCD150C() : is TRUE for OfficeRoleType: [{}] and MRN: [{}]", officeRoleType, message.getMrn()); return true; } else { log.info("shouldCreateMovementForCD150C() : is FALSE for OfficeRoleType: [{}] and MRN: [{}]. (MRN country is same as Operating Country)", officeRoleType, message.getMrn()); return false; } case TRANSIT: case EXIT: case INCIDENT: log.info("shouldCreateMovementForCD150C() : is FALSE for OfficeRoleType {}", officeRoleType); return false; default: return true; // That one i have no idea ! Left as is ..... } } private boolean shouldCreateMovementForCD114C(String officeRoleType, Message message, List<Movement> existingMovements) { OfficeRoleTypesEnum officeRoleTypesEnum = OfficeRoleTypesEnum.of(officeRoleType); if (!existingMovements.isEmpty()) { log.info("shouldCreateMovementForCD114C() : is FALSE for OfficeRoleType [{}] cause [{}] already existing movement(s) were found: {}", officeRoleType, existingMovements.size(), existingMovements.stream().map(Movement::toStringShort).collect(Collectors.toList())); return false; } switch (officeRoleTypesEnum) { case DEPARTURE: log.info("shouldCreateMovementForCD114C() : is FALSE for OfficeRoleType: [{}] and MRN: [{}].", officeRoleType, message.getMrn()); return false; case TRANSIT: log.info("shouldCreateMovementForCD114C() : is TRUE for OfficeRoleType {}", officeRoleType); return true; default: return true; } } @SneakyThrows private AddressType07 createAddress(Node root) { if ((boolean) XPATH.evaluate(ADDRESS, root, XPathConstants.BOOLEAN)) { AddressType07 address = new AddressType07(); address.setStreetAndNumber(XPATH.evaluate(STREETANDNUMBER, root)); address.setPostcode(checkIfXpathIsEmptyString(POSTCODE, root)); address.setCity(XPATH.evaluate(CITY, root)); address.setCountry(XPATH.evaluate(COUNTRY, root)); return address; } else { return null; } } @SneakyThrows private RepresentativeType01 createRepresentative(Node root) { if ((boolean) XPATH.evaluate(REPRESENTATIVE, root, XPathConstants.BOOLEAN)) { RepresentativeType01 representative = new RepresentativeType01(); representative.setIdentificationNumber(XPATH.evaluate(IDENTIFICATION_NUMBER_REPRESENTATIVE, root)); representative.setStatus(XPATH.evaluate(STATUS, root)); return representative; } else { return null; } } @SneakyThrows private CustomsOfficeOfDepartureType03 createCustomsOfficeOfDeparture(Node root, List<Movement> movements) { CustomsOfficeOfDepartureType03 customsOfficeOfDeparture = new CustomsOfficeOfDepartureType03(); if ((boolean) XPATH.evaluate(MessageXPathsEnum.DEPARTURE_OFFICE_ID.getValue(), root, XPathConstants.BOOLEAN)) { customsOfficeOfDeparture.setReferenceNumber(XPATH.evaluate(MessageXPathsEnum.DEPARTURE_OFFICE_ID.getValue(), root)); } else if (!movements.isEmpty()) { String movementId = movements.get(0).getId(); List<MessageOverview> messageOverviews = dossierDataService.getMessagesOverview(MessageTypes.CC_015_C.value(), movementId, false); Message cc015message; if (!messageOverviews.isEmpty()) { cc015message = dossierDataService.getMessageById(messageOverviews.get(0).getId(), false); CC015CType cc015cTypeMessage = XmlConverter.buildMessageFromXML(cc015message.getPayload(), CC015CType.class); customsOfficeOfDeparture.setReferenceNumber(cc015cTypeMessage.getCustomsOfficeOfDeparture().getReferenceNumber()); } } else { customsOfficeOfDeparture.setReferenceNumber(XPATH.evaluate(MessageXPathsEnum.ENQUIRY_AT_DEPARTURE_OFFICE_ID.getValue(), root)); } return customsOfficeOfDeparture; } @SneakyThrows private String checkIfXpathIsEmptyString(String expression, Node root) { return (boolean) XPATH.evaluate(expression, root, XPathConstants.BOOLEAN) ? XPATH.evaluate(expression, root) : null; } /** * <pre> * If MRN belongs to Operating Country * -> Select Departure only * ELSE If MRN does NOT belong to Operating Country perform the checks in the following order : * If Movement exists at Destination -> Handle at Destination * Else If Movement exists at any Office of Transit -> Handle at Office of Transit * Else If Movement exists at any Office of Exit for Transit -> Handle at Office of Exit for Transit * Else if Movement exists at any Office of Incident -> Handle at Office of Incident * ELSE return NULL and a new Movement should be created at Office of Destination */ protected Movement findTargetMovementForIncomingIE150(String mrn, List<Movement> movementListByMRN, String operatingCountryCode) { if (movementListByMRN.isEmpty()) { return null; } AtomicReference<Movement> targetMovementFound = new AtomicReference<>(); // Create a Map of MovementsList by OfficeRoleType Map<String, List<Movement>> movementsByOfficeRoleTypeMap = getMovementsByOfficeRoleType(movementListByMRN); // If MRN belongs to Operating Country -> Select the movement at Departure if (MessageUtil.extractMRNCountryCode(mrn).equals(operatingCountryCode)) { List<Movement> movementsForDeparture = movementsByOfficeRoleTypeMap.getOrDefault(OfficeRoleTypesEnum.DEPARTURE.getValue(), List.of()); if (movementsForDeparture.isEmpty()) { throw new NotFoundException(String.format( "findTargetMovementForIncomingIE150() : MRN belongs to Operating Country: [%s] and No Movement found for MRN: [%s] and OfficeRoleType: [%s]. Cannot proceed!", operatingCountryCode, mrn, OfficeRoleTypesEnum.DEPARTURE.getValue())); } else { if (movementsForDeparture.size() > 1) { log.warn( "findTargetMovementForIncomingIE150() : MRN belongs to Operating Country: [{}]. More than one: [{}] movements where found for MRN: [{}] and OfficeRoleType: [{}]. Will peak the one with the most recent \"updated_dttm\" WITHOUT any state validation", operatingCountryCode, movementsForDeparture.size(), mrn, OfficeRoleTypesEnum.DEPARTURE.getValue()); movementsForDeparture.sort(Comparator.comparing(Movement::getUpdatedDateTime).reversed()); } targetMovementFound.set(movementsForDeparture.get(0)); log.info("findTargetMovementForIncomingIE150() : MRN belongs to Operating Country: [{}]. Target Movement selected is: {}", operatingCountryCode, targetMovementFound.get().toStringShort()); return targetMovementFound.get(); } } /* The Order of the OfficeRoleTypes in the List below is according to a specified lookup PRIORITY. Should not be modified. The first Movement found is the chosen one */ for (OfficeRoleTypesEnum officeRoleTypesEnum : List.of(OfficeRoleTypesEnum.DESTINATION, OfficeRoleTypesEnum.TRANSIT, OfficeRoleTypesEnum.EXIT, OfficeRoleTypesEnum.INCIDENT)) { List<Movement> movementsByOfficeRoleTypeList = movementsByOfficeRoleTypeMap.getOrDefault(officeRoleTypesEnum.getValue(), List.of()); if (!movementsByOfficeRoleTypeList.isEmpty()) { if (movementsByOfficeRoleTypeList.size() > 1) { // If more than one, pick up the most recently updated one. SOS ! Will not check for State Validity at this point. Movement might be rejected later on because of being in invalid state log.warn( "findTargetMovementForIncomingIE150() : More than one : [{}] movements where found for MRN: [{}] and OfficeRoleType: [{}]. Will peak the one with the most recent \"updated_dttm\" WITHOUT any state validation", movementsByOfficeRoleTypeList.size(), mrn, officeRoleTypesEnum.getValue()); movementsByOfficeRoleTypeList.sort(Comparator.comparing(Movement::getUpdatedDateTime).reversed()); } targetMovementFound.set(movementsByOfficeRoleTypeList.get(0)); log.info("findTargetMovementForIncomingIE150() : Target Movement selected is of Office: [{}] -> {}", officeRoleTypesEnum.getValue(), targetMovementFound.get().toStringShort()); break; } } if (targetMovementFound.get() == null) { log.info( "findTargetMovementForIncomingIE150() : No matching movements found for MRN: [{}] in any OfficeRoleType. Will return NULL and will probably create new movement in DESTINATION", mrn); } return targetMovementFound.get(); } protected List<Movement> findTargetMovementForIncomingIE152(String mrn, String messageSender, List<Movement> currentMovementListByMRN) { String operatingCountry = getCountryCodeService.getCountryCode(); String mrnCountryCode = MessageUtil.extractMRNCountryCode(mrn); Map<String, List<Movement>> movementsByOfficeRoleTypeMap = getMovementsByOfficeRoleType(currentMovementListByMRN); List<Movement> targetMovementsFound = new ArrayList<>(); if (isOnlyForDeparture(mrnCountryCode, operatingCountry, messageSender)) { // only for Departure List<Movement> movementsForDeparture = movementsByOfficeRoleTypeMap.getOrDefault(OfficeRoleTypesEnum.DEPARTURE.getValue(), List.of()); if (!movementsForDeparture.isEmpty()) { log.info("findTargetMovementForIncomingIE152() : Found [{}] matching movements found for MRN: [{}] in DEPARTURE.", movementsForDeparture.size(), mrn); movementsForDeparture.sort(Comparator.comparing(Movement::getUpdatedDateTime).reversed()); targetMovementsFound.add(movementsForDeparture.get(0)); } else { log.info("findTargetMovementForIncomingIE152() : No matching movements found for MRN: [{}] in DEPARTURE.", mrn); } } else { // to all others offices except of Departure for (OfficeRoleTypesEnum officeRoleTypesEnum : List.of(OfficeRoleTypesEnum.DESTINATION, OfficeRoleTypesEnum.TRANSIT, OfficeRoleTypesEnum.EXIT, OfficeRoleTypesEnum.INCIDENT)) { List<Movement> movementsByOfficeRoleTypeList = movementsByOfficeRoleTypeMap.getOrDefault(officeRoleTypesEnum.getValue(), List.of()); if (!movementsByOfficeRoleTypeList.isEmpty()) { log.info("findTargetMovementForIncomingIE152() : Found [{}] matching movements found for MRN: [{}] in [{}].", movementsByOfficeRoleTypeList.size(), mrn, officeRoleTypesEnum.getValue()); movementsByOfficeRoleTypeList.sort(Comparator.comparing(Movement::getUpdatedDateTime).reversed()); targetMovementsFound.add(movementsByOfficeRoleTypeList.get(0)); } else { log.info("findTargetMovementForIncomingIE152() : No matching movements found for MRN: [{}] in [{}].", mrn, officeRoleTypesEnum.getValue()); } } } return targetMovementsFound; } private boolean isOnlyForDeparture(String mrnCountryCode, String operatingCountry, String messageSender) { return mrnCountryCode.equals(operatingCountry) && !messageSender.equals(operatingCountry); } private Map<String, List<Movement>> getMovementsByOfficeRoleType(List<Movement> movements) { return movements.stream().collect( Collectors.groupingBy(Movement::getOfficeRoleType, LinkedHashMap::new, Collectors.toCollection(ArrayList::new))); } private List<Violation> trimRejectedValues(List<Violation> violations) { return violations.stream() .map(violation -> { if (violation.getRejectedValue() != null) { String rejectedValue = violation.getRejectedValue().toString(); int maxLength = Math.min(rejectedValue.length(), E1115_MAX_LENGTH); String trimmedRejectedValue = rejectedValue.substring(0, maxLength); return violation.toBuilder().rejectedValue(trimmedRejectedValue).build(); } else { return violation; } }).collect(Collectors.toList()); } private void createSubmissionUserIdMessageAttribute(String messageId) { MessageAttribute messageAttribute = MessageAttribute.builder() .messageId(messageId) .attrKey(MessageAttributeKeysEnum.SUBMISSION_USER_ID.getValue()) .attrValue(userDetailsService.getUsername()) .build(); dossierDataService.saveMessageAttributeList(List.of(messageAttribute)); } private void saveTransportId(String xmlPayload, String movementId) { try (StringReader sr = new StringReader(xmlPayload)) { InputSource xml = new InputSource(sr); Node root = (Node) XPATH.evaluate("/", xml, XPathConstants.NODE); NodeList nodeList = (NodeList) XPATH.evaluate(MessageXPathsEnum.BORDER_TRANSPORT_ID.getValue(), root, XPathConstants.NODESET); String[] results = new String[nodeList.getLength()]; for (int index = 0; index < nodeList.getLength(); index++) { Node node = nodeList.item(index); results[index] = node.getTextContent(); } if (results.length > 0) { MovementAttribute movementAttribute = MovementAttribute.builder() .movementId(movementId) .attrKey(MovementAttributeKeysEnum.ARRIVAL_OR_BORDER_TRANSPORT_ID.getValue()) .attrValue(Arrays.toString(results)) .build(); dossierDataService.saveMovementAttribute(movementAttribute); } } catch (Exception e) { log.error("ERROR: Could not retrieve Transport Id value from Message payload.", e); } } private List<Movement> determineWhichMovementsToUseForAssociation(List<Violation> violations, List<Movement> existingMovements, List<Movement> createdMovements, Message message) { return XSD_ERROR_REASON.equals(violations.get(0).getReason()) && MessageTypes.CC_015_C.value().equals(message.getMessageType()) && !message.isManualInserted() ? createdMovements : existingMovements; } private String determineErmisEventBusinessKey(Movement movement, String mrn) { // If both Movement and MRN are NULL, then NULL is returned: return (movement != null) ? movement.getId() : mrn; } }
package com.intrasoft.ermis.transit.management.core.service; import static com.intrasoft.ermis.transit.management.core.util.ViolationUtils.createViolation; import static com.intrasoft.ermis.transit.shared.testing.util.FileHelpers.xmlToString; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.ArgumentMatchers.eq; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.ddntav5152.messages.CC056CType; import com.intrasoft.ermis.ddntav5152.messages.CC057CType; import com.intrasoft.ermis.ddntav5152.messages.CC906CType; import com.intrasoft.ermis.ddntav5152.messages.CD150CType; import com.intrasoft.ermis.ddntav5152.messages.CD906CType; import com.intrasoft.ermis.ddntav5152.messages.FunctionalErrorType03; import com.intrasoft.ermis.ddntav5152.messages.MessageTypes; import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService; import com.intrasoft.ermis.transit.common.enums.DirectionEnum; import com.intrasoft.ermis.transit.common.enums.MessageOfficeTypeExpectedStatusesEnum; import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import com.intrasoft.ermis.transit.common.exceptions.NotFoundException; import com.intrasoft.ermis.transit.common.transition.period.TransitionPeriodService; import com.intrasoft.ermis.transit.common.util.MessageUtil; import com.intrasoft.ermis.transit.management.core.exception.BadRequestException; import com.intrasoft.ermis.transit.management.core.port.outbound.DDNTAMessageProducer; import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService; import com.intrasoft.ermis.transit.management.core.port.outbound.ProcessMessageCommandProducer; import com.intrasoft.ermis.transit.management.core.port.outbound.ValidationService; import com.intrasoft.ermis.transit.management.domain.Message; import com.intrasoft.ermis.transit.management.domain.Movement; import com.intrasoft.ermis.transit.management.domain.MovementQuery; import com.intrasoft.ermis.transit.management.domain.MovementsOrViolations; import com.intrasoft.ermis.transit.management.domain.Violation; import java.io.StringReader; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import lombok.SneakyThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.w3c.dom.Node; import org.xml.sax.InputSource; @ExtendWith(MockitoExtension.class) class DDNTAMessageProcessingServiceImplUT { @Mock private ErmisLogger ermisLogger; @Mock private DossierDataService dossierDataService; @Mock ProcessMessageCommandProducer processMessageCommandProducer; @Mock DDNTAMessageProducer ddntaMessageProducer; @Mock GetCountryCodeService getCountryCodeService; @Mock ValidationService validationService; @Mock DDNTAMessageCustomValidationServiceImpl ddntaMessageCustomValidationService; @Mock TransitionPeriodService transitionPeriodService; @Mock MessageValidationService messageValidationService; @Captor ArgumentCaptor<Message> messageArgumentCaptor; @Captor ArgumentCaptor<String> idArgumentCaptor; @Captor ArgumentCaptor<String> statusArgumentCaptor; @Captor ArgumentCaptor<Movement> createdMovementArgumentCaptor; @Captor ArgumentCaptor<Movement> publishedMovementArgumentCaptor; @Captor private ArgumentCaptor<String> messageIdCaptor; @Captor private ArgumentCaptor<String> movementIdCaptor; @Captor private ArgumentCaptor<String> messageTypeCaptor; @Captor private ArgumentCaptor<CD906CType> msgCD906CCaptor; @Captor private ArgumentCaptor<CC906CType> msgCC906CCaptor; @Captor private ArgumentCaptor<CC056CType> msgCC056CCaptor; @Captor private ArgumentCaptor<CC057CType> msgCC057CCaptor; @InjectMocks private DDNTAMessageProcessingServiceImpl messageProcessingService; private static final String OFFICE_OF_REQUEST = "//CustomsOfficeOfRequest/referenceNumber"; @Test @SneakyThrows void testProcessMessage_015_createMovementPerOfficeRoleType_success() { // given String messageXml = xmlToString("CC015C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DEPARTURE.getValue(), "AA000000", null, "1112236201149", ProcessingStatusTypeEnum.OODEP_NONE.getItemCode()); when(dossierDataService.createMovement(any())).thenReturn(movement); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn( MovementsOrViolations.of(List.of(nullifyMovementId(movement)), List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); assertThat(messageIdCaptor.getValue()).isEqualTo(savedMessage.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); assertThat(messageTypeCaptor.getValue()).isEqualTo(message.getMessageType()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertThat(publishedMovements).hasSize(1); assertTrue(publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DEPARTURE.getValue())) .allMatch(m -> m.getOfficeId().equals("AA000000"))); } @Test @SneakyThrows void testProcessMessage_010_associateMessageWithMovementPerOfficeRoleType_success() { // given String messageXml = xmlToString("CD010C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Movement destinationMovement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DESTINATION.getValue(), "AK020053", "31DE061F60A83E16K1", "1112236201149", ProcessingStatusTypeEnum.OODEST_AAR_CREATED.getItemCode()); Movement exitMovement = getMovement("aab0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.EXIT.getValue(), "DK005600", "31DE061F60A83E16K1", "1112236201149", ProcessingStatusTypeEnum.OOTRXS_AXR_CREATED.getItemCode()); List<Movement> existingMovements = new ArrayList<>(); existingMovements.add(destinationMovement); existingMovements.add(exitMovement); when(dossierDataService.findByCriteria("31DE061F60A83E16K1", null, null, null, 50)).thenReturn(existingMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("MM"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(existingMovements, List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(2)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); assertThat(createdMovementArgumentCaptor.getAllValues()).isEmpty(); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertEquals(1, (int) publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DESTINATION.getValue())) .filter(m -> m.getOfficeId().equals("AK020053")).count()); assertEquals(1, (int) publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.EXIT.getValue())) .filter(m -> m.getOfficeId().equals("DK005600")).count()); } @Test @SneakyThrows void testProcessMessage_001_createMovementPerOfficeRoleType_success() { // given String messageXml = xmlToString("CD001C.xml"); String messageType = "CD001C"; Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DESTINATION.getValue(), "MK001051", "21DE061F60A83E16K0", "1112236201149", ProcessingStatusTypeEnum.OODEST_NONE.getItemCode()); when(dossierDataService.createMovement(any())).thenReturn(movement); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn( MovementsOrViolations.of(List.of(nullifyMovementId(movement)), List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); assertEquals(savedMessage.getId(), messageIdCaptor.getValue()); assertEquals(movement.getId(), movementIdCaptor.getValue()); assertEquals(message.getMessageType(), messageTypeCaptor.getValue()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertEquals(1, publishedMovements.size()); for (Movement move : publishedMovements) { assertTrue(validOfficeRoleTypeForMessageType(move, messageType)); } assertTrue(publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DESTINATION.getValue())) .allMatch(m -> m.getOfficeId().equals("MK001051"))); } @Test @SneakyThrows void testProcessMessage_001_createMovementPerOfficeRoleType_same_NTA_success() { // given String messageXml = xmlToString("CD001C.xml"); String messageType = "CD001C"; Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); //There's already a movement in DEPARTURE. Only DESTINATION should be triggered to handle this when(dossierDataService.findByCriteria(savedMessage.getMrn(), null, null, null, 50)).thenReturn(List.of( getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fe", OfficeRoleTypesEnum.DEPARTURE.getValue(), "MK001051", savedMessage.getMrn(), "1112236201150", ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode()) )); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DESTINATION.getValue(), "MK001051", "21DE061F60A83E16K0", "1112236201149", ProcessingStatusTypeEnum.OODEST_NONE.getItemCode()); when(dossierDataService.createMovement(any())).thenReturn(movement); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn( MovementsOrViolations.of(List.of(nullifyMovementId(movement)), List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); assertEquals(savedMessage.getId(), messageIdCaptor.getValue()); assertEquals(movement.getId(), movementIdCaptor.getValue()); assertEquals(message.getMessageType(), messageTypeCaptor.getValue()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertEquals(1, publishedMovements.size()); for (Movement move : publishedMovements) { assertTrue(validOfficeRoleTypeForMessageType(move, messageType)); } assertTrue(publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DESTINATION.getValue())) .allMatch(m -> m.getOfficeId().equals("MK001051"))); } @Test @SneakyThrows void testProcessMessage_002_success() { // given String messageXml = xmlToString("CD002C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when when(dossierDataService.findByCriteria(anyString(), isNull(), isNull(), isNull(), anyInt())).thenReturn(new ArrayList<>()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(), List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); // IE002 need not create Movement: verify(dossierDataService, times(0)).createMovement(any()); verify(dossierDataService, times(0)).associateMessageWithMovement(any(), any()); // IE002 is directly published to Office of Departure: verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), ArgumentMatchers.eq(OfficeRoleTypesEnum.DEPARTURE.getValue())); assertEquals(savedMessage.getId(), messageIdCaptor.getValue()); assertEquals(savedMessage.getMessageType(), messageTypeCaptor.getValue()); } @Test @SneakyThrows void testProcessMessage_010_createMovementPerOfficeRoleType_fail() { // given String messageXml = xmlToString("CD010C.xml"); String messageType = "CD010C"; Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DESTINATION.getValue(), "DE002202", "31DE061F60A83E16K1", "1112236201149", ProcessingStatusTypeEnum.OODEST_INVALIDATED.getItemCode()); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria("31DE061F60A83E16K1", null, null, null, 50)).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(dossierDataService.getMessagesByCriteria(any())).thenReturn(List.of(savedMessage)); when(dossierDataService.saveRejectedMessage(any())).thenAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(true); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of( createViolation("/" + messageType, MessageUtil.ERROR_REASON_FOR_906, null, MessageUtil.ERROR_CODE_FOR_906)))); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(2)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(1)).publish(msgCD906CCaptor.capture(), eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); assertEquals(message.getSource(), msgCD906CCaptor.getValue().getMessageRecipient()); assertEquals(messageProcessingService.constructMessageSender(), msgCD906CCaptor.getValue().getMessageSender()); assertEquals(message.getMrn(), msgCD906CCaptor.getValue().getHeader().getMRN()); assertEquals("/" + messageType, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorPointer()); assertEquals(MessageUtil.ERROR_REASON_FOR_906, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorReason()); assertEquals(MessageUtil.ERROR_CODE_FOR_906, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorCode()); } @Test @SneakyThrows void testProcessMessage_014_createMovementPerOfficeRoleType_fail() { // given String messageXml = xmlToString("CC014C.xml"); String messageType = "CC014C"; Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("c4818a60-6cd1-4914-9dbc-37a428bdd93a", OfficeRoleTypesEnum.DEPARTURE.getValue(), "GB000121", "22DKWUGSKUXRQZ2EJ4", "SKIP_GMS_015_014", ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode()); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria("22DKWUGSKUXRQZ2EJ4", null, null, null, 50)).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); Violation violation = Violation.builder().fieldName("CC014C").code(MessageUtil.ERROR_CODE_FOR_906).reason(MessageUtil.ERROR_REASON_FOR_906).build(); when(validationService.validateMovementMessage(savedMessage.getId())).thenReturn(List.of(violation)); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(2)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(1)).publish(msgCC056CCaptor.capture(), any()); assertEquals(message.getSource(), msgCC056CCaptor.getValue().getMessageRecipient()); assertEquals(messageProcessingService.constructMessageSender(), msgCC056CCaptor.getValue().getMessageSender()); assertEquals(message.getMrn(), msgCC056CCaptor.getValue().getTransitOperation().getMRN()); assertEquals(messageType, msgCC056CCaptor.getValue().getFunctionalError().get(0).getErrorPointer()); assertEquals(MessageUtil.ERROR_REASON_FOR_906, msgCC056CCaptor.getValue().getFunctionalError().get(0).getErrorReason()); assertEquals(MessageUtil.ERROR_CODE_FOR_906, msgCC056CCaptor.getValue().getFunctionalError().get(0).getErrorCode()); } @Test @SneakyThrows void testProcessMessage_001_createMovementPerOfficeRoleType_fail() { // given String messageXml = xmlToString("CD001C.xml"); String messageType = "CD001C"; Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DESTINATION.getValue(), "DE002202", "31DE061F60A83E16K1", "1112236201149", ProcessingStatusTypeEnum.OODEST_INVALIDATED.getItemCode()); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria("21DE061F60A83E16K0", null, null, null, 50)).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(dossierDataService.getMessagesByCriteria(any())).thenReturn(List.of(savedMessage)); when(dossierDataService.saveRejectedMessage(any())).thenAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(false); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of(createViolation("/" + messageType, MessageUtil.ERROR_REASON_FOR_906, null, MessageUtil.ERROR_CODE_FOR_906)))); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(2)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(1)).publish(msgCD906CCaptor.capture(), eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); assertEquals(message.getSource(), msgCD906CCaptor.getValue().getMessageRecipient()); assertEquals(messageProcessingService.constructMessageSender(), msgCD906CCaptor.getValue().getMessageSender()); assertEquals(message.getMrn(), msgCD906CCaptor.getValue().getHeader().getMRN()); assertEquals("/" + messageType, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorPointer()); assertEquals(MessageUtil.ERROR_REASON_FOR_906, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorReason()); assertEquals(MessageUtil.ERROR_CODE_FOR_906, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorCode()); } @Test @SneakyThrows void testProcessMessage_044_createMovementPerOfficeRoleType_fail() { // given String messageXml = xmlToString("CC044C.xml"); String messageType = "CC044C"; Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DESTINATION.getValue(), "DE002202", "MRN-70P6", "1112236201149", ProcessingStatusTypeEnum.OODEST_NONE.getItemCode()); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria("MRN-70P6", null, null, null, 50)).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of( createViolation("/" + messageType, MessageUtil.ERROR_REASON_FOR_906, null, MessageUtil.ERROR_CODE_FOR_906) ))); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(2)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(1)).publish(msgCC057CCaptor.capture(), any()); assertEquals(message.getSource(), msgCC057CCaptor.getValue().getMessageRecipient()); assertEquals(messageProcessingService.constructMessageSender(), msgCC057CCaptor.getValue().getMessageSender()); assertEquals(message.getMrn(), msgCC057CCaptor.getValue().getTransitOperation().getMRN()); assertEquals("/" + messageType, msgCC057CCaptor.getValue().getFunctionalError().get(0).getErrorPointer()); assertEquals(MessageUtil.ERROR_REASON_FOR_906, msgCC057CCaptor.getValue().getFunctionalError().get(0).getErrorReason()); assertEquals(MessageUtil.ERROR_CODE_FOR_906, msgCC057CCaptor.getValue().getFunctionalError().get(0).getErrorCode()); } @Test @SneakyThrows void testProcessMessage_044_success() { // given String messageXml = xmlToString("CC044C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DESTINATION.getValue(), "DE002202", "MRN-70P6", "1112236201149", "E01"); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria("MRN-70P6", null, null, null, 50)).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(movement), List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(0)).publish(msgCC906CCaptor.capture(), anyString(), anyString(), any()); assertThat(messageIdCaptor.getValue()).isEqualTo(savedMessage.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); assertThat(messageTypeCaptor.getValue()).isEqualTo(message.getMessageType()); } @Test @SneakyThrows void testProcessMessage_saveAndPublishTwoMovements_success() { // given String messageXml = xmlToString("CD050C.xml"); String messageType = "CD050C"; // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); Movement movementForDK204000 = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.TRANSIT.getValue(), "DK204000", "21RS65CB8C1082C8M9", message.getLrn(), ProcessingStatusTypeEnum.OOTRS_NONE.getItemCode()); Movement movementForDK002031 = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.TRANSIT.getValue(), "DK002031", "21RS65CB8C1082C8M9", message.getLrn(), ProcessingStatusTypeEnum.OOTRS_NONE.getItemCode()); when(dossierDataService.createMovement(any())).thenReturn(movementForDK204000); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(dossierDataService.findByCriteria("21RS65CB8C1082C8M9", null, null, null, 50)).thenReturn(new ArrayList<>()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn( MovementsOrViolations.of(List.of(nullifyMovementId(movementForDK204000), nullifyMovementId(movementForDK002031)), List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(2)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(2)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); assertEquals(savedMessage.getId(), messageIdCaptor.getValue()); assertEquals(message.getMessageType(), messageTypeCaptor.getValue()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertEquals(2, publishedMovements.size()); for (Movement move : publishedMovements) { assertTrue(validOfficeRoleTypeForMessageType(move, messageType)); } assertTrue(publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DESTINATION.getValue())) .allMatch(m -> m.getOfficeId().equals("DK204000") || m.getOfficeId().equals("DK002031"))); } private boolean validOfficeRoleTypeForMessageType(Movement movement, String messageType) { return MessageOfficeTypeExpectedStatusesEnum.valueOf(messageType) .getOfficeRoleTypeStatuses() .stream() .anyMatch(officeRoleTypeStatuses -> officeRoleTypeStatuses.getOfficeRoleType() .getValue() .equals(movement.getOfficeRoleType())); } @Test @SneakyThrows void testProcessMessage_027_success() { //mock String messageXml = xmlToString("CD027C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); Movement movement = getMovement("TEST", OfficeRoleTypesEnum.DEPARTURE.getValue(), "TEST", "TEST", "", ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode()); when(dossierDataService.findByCriteria(anyString(), isNull(), isNull(), isNull(), anyInt())).thenReturn(List.of(movement)); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(movement), List.of())); //execute messageProcessingService.processMessage(messageXml); //confirm verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(0)).publish(msgCC906CCaptor.capture(), anyString(), anyString(), any()); assertThat(messageIdCaptor.getValue()).isEqualTo(savedMessage.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); assertThat(messageTypeCaptor.getValue()).isEqualTo(savedMessage.getMessageType()); } @Test @SneakyThrows void testProcessMessage_180_success() { //mock String messageXml = xmlToString("CD180C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); Movement movement = getMovement("TEST", OfficeRoleTypesEnum.DEPARTURE.getValue(), "TEST", "TEST", "", ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode()); when(dossierDataService.findByCriteria(anyString(), isNull(), isNull(), isNull(), anyInt())).thenReturn(List.of(movement)); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(movement), List.of())); //execute messageProcessingService.processMessage(messageXml); //confirm verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(0)).publish(msgCC906CCaptor.capture(), anyString(), anyString(), any()); assertThat(messageIdCaptor.getValue()).isEqualTo(savedMessage.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); assertThat(messageTypeCaptor.getValue()).isEqualTo(savedMessage.getMessageType()); } @Test @SneakyThrows void testProcessMessage_180_fail() { //mock String messageXml = xmlToString("CD180C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); when(dossierDataService.findByCriteria(anyString(), isNull(), isNull(), isNull(), anyInt())).thenReturn(List.of()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(dossierDataService.updateMessage(any(), any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(), List.of( createViolation("/CD180C/TransitOperation/MRN", "N/A", null, "90")))); when(dossierDataService.getMessagesByCriteria(any())).thenReturn( List.of(Message.builder().id(UUID.randomUUID().toString()).messageType(MessageTypes.CD_180_C.value()).build())); //execute messageProcessingService.processMessage(messageXml); //confirm verify(dossierDataService, times(2)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).updateMessage(idArgumentCaptor.capture(), statusArgumentCaptor.capture()); verify(dossierDataService, times(0)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(1)).publish(msgCD906CCaptor.capture(), any()); assertThat(msgCD906CCaptor.getValue().getFunctionalError().stream() .map(FunctionalErrorType03::getErrorCode) .collect(Collectors.toList())) .contains("90"); assertThat(msgCD906CCaptor.getValue().getFunctionalError() .stream() .map(FunctionalErrorType03::getErrorPointer).collect(Collectors.toList())) .contains("/CD180C/TransitOperation/MRN"); } @Test @SneakyThrows void testProcessMessage_144_success() { //mock String messageXml = xmlToString("CD144C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); Movement movement = getMovement("TEST", OfficeRoleTypesEnum.DESTINATION.getValue(), "TEST", "20DE71EAF5731899M3", "", ProcessingStatusTypeEnum.OODEST_AAR_CREATED.getItemCode()); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria("20DE71EAF5731899M3", null, null, null, 50)).thenReturn(storedMovements); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of())); //execute messageProcessingService.processMessage(messageXml); //confirm verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); assertEquals(savedMessage.getSource(), messageArgumentCaptor.getValue().getSource()); assertEquals(savedMessage.getDestination(), messageArgumentCaptor.getValue().getDestination()); assertEquals(savedMessage.getMrn(), messageArgumentCaptor.getValue().getMrn()); } @Test @SneakyThrows void testProcessMessage_180_multiple_offices_success() { //mock String messageXml = xmlToString("CD180C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); Movement ooDepMovement = getMovement("TEST", OfficeRoleTypesEnum.DEPARTURE.getValue(), "TEST", "TEST", "", ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode()); when(dossierDataService.findByCriteria(anyString(), isNull(), isNull(), isNull(), anyInt())).thenReturn(List.of(ooDepMovement)); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(ooDepMovement), List.of())); //execute messageProcessingService.processMessage(messageXml); //confirm verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(0)).publish(msgCC906CCaptor.capture(), anyString(), anyString(), any()); assertThat(messageIdCaptor.getValue()).isEqualTo(savedMessage.getId()); assertThat(messageTypeCaptor.getValue()).isEqualTo(savedMessage.getMessageType()); } @Test @SneakyThrows void testProcessMessage_181_success() { //mock String messageXml = xmlToString("CD181C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); Movement destMovement = getMovement("TEST", OfficeRoleTypesEnum.DESTINATION.getValue(), "TEST", "TEST", "", ProcessingStatusTypeEnum.OODEST_AAR_REQUESTED.getItemCode()); Movement exitMovement = getMovement("TEST", OfficeRoleTypesEnum.EXIT.getValue(), "TEST", "TEST", "", ProcessingStatusTypeEnum.OOTRXS_AXR_CREATED.getItemCode()); when(dossierDataService.findByCriteria(anyString(), isNull(), isNull(), isNull(), anyInt())).thenReturn(new ArrayList<>()); when(dossierDataService.createMovement(any())).thenReturn(destMovement); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn( MovementsOrViolations.of(List.of(nullifyMovementId(destMovement), nullifyMovementId(exitMovement)), List.of())); //execute messageProcessingService.processMessage(messageXml); //confirm verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(2)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(0)).publish(msgCC906CCaptor.capture(), anyString(), anyString(), any()); assertThat(messageIdCaptor.getValue()).isEqualTo(savedMessage.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(destMovement.getId()); assertThat(messageTypeCaptor.getValue()).isEqualTo(savedMessage.getMessageType()); } @Test @SneakyThrows void testHandle038_success() throws XPathExpressionException { // given String messageXml = xmlToString("CD038C.xml"); InputSource xml = new InputSource(new StringReader(messageXml)); XPath xpath = XPathFactory.newInstance().newXPath(); Node root = (Node) xpath.evaluate("/", xml, XPathConstants.NODE); String officeOfDeparture = xpath.evaluate(OFFICE_OF_REQUEST, root); //mock Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); MovementQuery movementQuery = getMovementQuery(savedMessage.getMrn()); when(validationService.validateMovementMessage(any())).thenReturn(Collections.emptyList()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(dossierDataService.findMovementQueriesByCriteria(any())).thenReturn(movementQuery); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(), List.of())); //execute messageProcessingService.handle038(messageXml); assertThat(movementQuery.getResponsePayload()).isEqualTo(messageXml); assertThat(movementQuery.getRespondent()).isEqualTo(officeOfDeparture); } @Test @SneakyThrows void testProcessMessage_CD201C_no_validation_errors() { // given String messageXml = xmlToString("CD201C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DEPARTURE.getValue(), "DK005600", savedMessage.getMrn(), null, null); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria(message.getMrn(), null, null, null, 50)).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(0)).publish(msgCD906CCaptor.capture(), eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); assertThat(messageIdCaptor.getValue()).isEqualTo(savedMessage.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); assertThat(messageTypeCaptor.getValue()).isEqualTo(message.getMessageType()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertThat(publishedMovements).hasSize(1); assertTrue(publishedMovements.stream() .filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DEPARTURE.getValue())) .allMatch(m -> m.getOfficeId().equals("DK005600"))); } // TODO: This looks like an erroneous test. Validation service will never throw OutOfOrder Functional Errors, only R&C @Test @SneakyThrows void testProcessMessage_CD201C_with_validation_errors() { // given String messageXml = xmlToString("CD201C.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); // when Message message = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); Movement movement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd", OfficeRoleTypesEnum.DEPARTURE.getValue(), "DK005600", savedMessage.getMrn(), null, null); List<Movement> storedMovements = new ArrayList<>(); storedMovements.add(movement); when(dossierDataService.findByCriteria(message.getMrn(), null, null, null, 50)).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(dossierDataService.getMessagesByCriteria(any())).thenReturn(List.of(savedMessage)); when(dossierDataService.saveRejectedMessage(any())).thenAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); Violation violation = Violation.builder().fieldName("/CD201C").code(MessageUtil.ERROR_CODE_FOR_906).reason(MessageUtil.ERROR_REASON_FOR_906).build(); when(validationService.validateMovementMessage(savedMessage.getId())).thenReturn(List.of(violation)); when(transitionPeriodService.isNowNCTSTransitionPeriod()).thenReturn(false); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of())); messageProcessingService.processMessage(messageXml); // then verify(dossierDataService, times(2)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(2)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(1)).publish(msgCD906CCaptor.capture(),eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertThat(publishedMovements).isEmpty(); assertEquals(message.getSource(), msgCD906CCaptor.getValue().getMessageRecipient()); assertEquals(messageProcessingService.constructMessageSender(), msgCD906CCaptor.getValue().getMessageSender()); assertEquals(message.getMrn(), msgCD906CCaptor.getValue().getHeader().getMRN()); assertEquals("/" + message.getMessageType(), msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorPointer()); assertEquals(MessageUtil.ERROR_REASON_FOR_906, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorReason()); assertEquals(MessageUtil.ERROR_CODE_FOR_906, msgCD906CCaptor.getValue().getFunctionalError().get(0).getErrorCode()); } @Test @SneakyThrows void testProcessMessage_CD150C_for_OoDep_ExistingMovement() { // given String messageXml = xmlToString("CD150C_for_departure.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(validationService.validateMovementMessage(savedMessage.getId())).thenReturn(List.of()); Movement depMovement = getMovement("depMovement", OfficeRoleTypesEnum.DEPARTURE.getValue(), "DK005600", savedMessage.getMrn(), null, ProcessingStatusTypeEnum.OODEP_RECOVERY_RECOMMENDED.getItemCode()); when(dossierDataService.findByCriteria(savedMessage.getMrn(), null, null, null, 99)).thenReturn(List.of(depMovement)); doNothing().when(dossierDataService).associateMessageWithMovement(savedMessage.getId(), depMovement.getId()); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(depMovement), List.of())); // when messageProcessingService.processMessage(messageXml); // then assertEquals(MessageUtil.extractMRNCountryCode(savedMessage.getMrn()), getCountryCodeService.getCountryCode()); verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertThat(publishedMovements).containsOnly(depMovement); } /** * For incoming IE150 will test all OfficeRoleTypes (as declared in the CsvSource Test Parameter) with a sample Valid State for each Office Role Type */ @ParameterizedTest @CsvSource({"DESTINATION,C07", "TRANSIT,D01", "EXIT,M02", "INCIDENT,I04"}) @SneakyThrows void testProcessMessage_CD150C_for_AllOffices_ExistingMovement(String officeRoleType, String processingStatus) { // given String messageXml = xmlToString("CD150C_for_destination.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(validationService.validateMovementMessage(savedMessage.getId())).thenReturn(List.of()); Movement existingMovement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fe", OfficeRoleTypesEnum.of(officeRoleType).getValue(), "DK000460", savedMessage.getMrn(), null, processingStatus); when(dossierDataService.findByCriteria(savedMessage.getMrn(), null, null, null, 99)).thenReturn(List.of(existingMovement)); doNothing().when(dossierDataService).associateMessageWithMovement(savedMessage.getId(), existingMovement.getId()); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(existingMovement), List.of())); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); // when messageProcessingService.processMessage(messageXml); // then assertNotEquals(MessageUtil.extractMRNCountryCode(savedMessage.getMrn()), getCountryCodeService.getCountryCode()); verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertThat(publishedMovements).containsOnly(existingMovement); } /** * For incoming IE150 will test all OfficeRoleTypes (as declared in the Enum Test Parameter) with all possible declared Valid States per OfficeRoleType */ @ParameterizedTest @EnumSource(value = OfficeRoleTypesEnum.class, names = {"DESTINATION", "TRANSIT", "EXIT", "INCIDENT"}) void testProcessMessage_CD150C_for_AllOffices_AllStates_ExistingMovement(OfficeRoleTypesEnum officeRoleTypesEnum) throws XPathExpressionException { // given String messageXml = xmlToString("CD150C_for_destination.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(validationService.validateMovementMessage(savedMessage.getId())).thenReturn(List.of()); Set<String> allValidStatesPerOfficeRoleType = MessageOfficeTypeExpectedStatusesEnum.getProcessingStatusItemCodesByMessageTypeAndRoleType(MessageTypes.CD_150_C, officeRoleTypesEnum); allValidStatesPerOfficeRoleType.forEach( state -> { Movement existingMovement = getMovement("movementId", officeRoleTypesEnum.getValue(), "DK000460", savedMessage.getMrn(), null, state); when(dossierDataService.findByCriteria(savedMessage.getMrn(), null, null, null, 99)).thenReturn(List.of(existingMovement)); doNothing().when(dossierDataService).associateMessageWithMovement(savedMessage.getId(), existingMovement.getId()); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn( MovementsOrViolations.of(List.of(existingMovement), List.of())); // when try { messageProcessingService.processMessage(messageXml); } catch (BadRequestException e) { throw new RuntimeException(e); } catch (XPathExpressionException e) { throw new RuntimeException(e); } // then assertNotEquals(MessageUtil.extractMRNCountryCode(savedMessage.getMrn()), getCountryCodeService.getCountryCode()); } ); verify(dossierDataService, times(allValidStatesPerOfficeRoleType.size())).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(allValidStatesPerOfficeRoleType.size())).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(allValidStatesPerOfficeRoleType.size())).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); } @Test @SneakyThrows void testProcessMessage_CD150C_for_OoDest_CreateNewMovement() throws JAXBException { // given String messageXml = xmlToString("CD150C_for_destination.xml"); Message savedMessage = messageProcessingService.setUpMessage(messageXml, false, DirectionEnum.RECEIVED); savedMessage.setId(UUID.randomUUID().toString()); CD150CType cd150CType = XmlConverter.buildMessageFromXML(savedMessage.getPayload(), CD150CType.class); Movement destMovement = getMovement("ceb0cc2b-dd74-495b-87cb-6ab27c7687fe", OfficeRoleTypesEnum.DESTINATION.getValue(), "DK000460", savedMessage.getMrn(), null, null); when(dossierDataService.persistMessage(any())).thenReturn(savedMessage); when(validationService.validateMovementMessage(savedMessage.getId())).thenReturn(List.of()); when(dossierDataService.findByCriteria(savedMessage.getMrn(), null, null, null, 99)).thenReturn(List.of()); when(dossierDataService.createMovement(any())).thenReturn(destMovement); doNothing().when(dossierDataService).associateMessageWithMovement(savedMessage.getId(), destMovement.getId()); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn( MovementsOrViolations.of(List.of(nullifyMovementId(destMovement)), List.of())); // when messageProcessingService.processMessage(messageXml); // then assertNotEquals(MessageUtil.extractMRNCountryCode(savedMessage.getMrn()), getCountryCodeService.getCountryCode()); verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(1)).createMovement(createdMovementArgumentCaptor.capture()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); Movement movementCreated = createdMovementArgumentCaptor.getValue(); assertEquals(movementCreated.getOfficeRoleType(), OfficeRoleTypesEnum.DESTINATION.getValue()); assertEquals(movementCreated.getOfficeId(), cd150CType.getCustomsOfficeOfRecoveryRequested().getReferenceNumber()); List<Movement> publishedMovements = publishedMovementArgumentCaptor.getAllValues(); assertThat(publishedMovements).containsOnly(destMovement); } @Test @SneakyThrows void testProcessMessage_906_success() { // given String cd181Xml = xmlToString("CD181C.xml"); Message saved181 = messageProcessingService.setUpMessage(cd181Xml, false, DirectionEnum.SENT); saved181.setId(UUID.randomUUID().toString()); String cd906Xml = xmlToString("CD906C.xml"); Message saved906 = messageProcessingService.setUpMessage(cd906Xml, false, DirectionEnum.RECEIVED); saved906.setId(UUID.randomUUID().toString()); Movement movement = getMovement(UUID.randomUUID().toString(), OfficeRoleTypesEnum.DESTINATION.getValue(), "DE002202", "MRN-70P6", "1112236201149", "E01"); List<Movement> storedMovements = List.of(movement); // when when(dossierDataService.findAssociatedMovements("test", DirectionEnum.SENT.getDirection())).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(saved906); when(dossierDataService.saveRejectedMessage(any())).thenAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); when(dossierDataService.getMessagesByCriteria(any())).thenReturn(List.of(saved181)); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(movement), List.of())); messageProcessingService.processMessage(cd906Xml); // then verify(validationService, times(0)).validateMovementMessage(any()); verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(any()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(any(), any(), any(Movement.class)); verify(ddntaMessageProducer, times(0)).publish(msgCD906CCaptor.capture(), eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); assertThat(messageIdCaptor.getValue()).isEqualTo(saved906.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); } @Test @SneakyThrows void testProcessMessage_906_invalid() { // given String cd181Xml = xmlToString("CD181C.xml"); Message saved181 = messageProcessingService.setUpMessage(cd181Xml, false, DirectionEnum.SENT); saved181.setId(UUID.randomUUID().toString()); String cd906Xml = xmlToString("CD906C_invalid.xml"); Message saved906 = messageProcessingService.setUpMessage(cd906Xml, false, DirectionEnum.RECEIVED); saved906.setId(UUID.randomUUID().toString()); Movement movement = getMovement(UUID.randomUUID().toString(), OfficeRoleTypesEnum.DESTINATION.getValue(), "DE002202", "MRN-70P6", "1112236201149", "E01"); List<Movement> storedMovements = List.of(movement); // when when(dossierDataService.findAssociatedMovements("test", DirectionEnum.SENT.getDirection())).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(saved906); when(dossierDataService.saveRejectedMessage(any())).thenAnswer(invocationOnMock -> invocationOnMock.getArgument(0)); when(dossierDataService.getMessagesByCriteria(any())).thenReturn(List.of(saved181)); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(storedMovements, List.of())); messageProcessingService.processMessage(cd906Xml); // then verify(validationService, times(0)).validateMovementMessage(any()); verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(any()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(), publishedMovementArgumentCaptor.capture()); verify(ddntaMessageProducer, times(0)).publish(msgCD906CCaptor.capture(), eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); assertThat(messageIdCaptor.getValue()).isEqualTo(saved906.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); } @Test @SneakyThrows void testProcessMessage_906_no_movement() { // given String cd906Xml = xmlToString("CD906C.xml"); Message saved906 = messageProcessingService.setUpMessage(cd906Xml, false, DirectionEnum.RECEIVED); saved906.setId(UUID.randomUUID().toString()); // when when(dossierDataService.findAssociatedMovements("test", DirectionEnum.SENT.getDirection())).thenReturn(new ArrayList<>()); when(dossierDataService.persistMessage(any())).thenReturn(saved906); when(dossierDataService.getMessagesByCriteria(any())).thenReturn( List.of(Message.builder().id(UUID.randomUUID().toString()).messageType(MessageTypes.CD_150_C.value()).build())); messageProcessingService.processMessage(cd906Xml); // then verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(any()); verify(dossierDataService, times(0)).associateMessageWithMovement(any(), any()); verify(processMessageCommandProducer, times(0)).publish(any(), any(), any(Movement.class)); verify(ddntaMessageProducer, times(0)).publish(msgCD906CCaptor.capture(), eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); } @Test @SneakyThrows void testProcessMessage_917_success() { // given String cd181Xml = xmlToString("CD181C.xml"); Message saved181 = messageProcessingService.setUpMessage(cd181Xml, false, DirectionEnum.SENT); saved181.setId(UUID.randomUUID().toString()); String cd917Xml = xmlToString("CD917C.xml"); Message saved917 = messageProcessingService.setUpMessage(cd917Xml, false, DirectionEnum.RECEIVED); saved917.setId(UUID.randomUUID().toString()); Movement movement = getMovement(UUID.randomUUID().toString(), OfficeRoleTypesEnum.DESTINATION.getValue(), "DE002202", "MRN-70P6", "1112236201149", "E01"); List<Movement> storedMovements = List.of(movement); // when when(dossierDataService.findAssociatedMovements("test", DirectionEnum.SENT.getDirection())).thenReturn(storedMovements); when(dossierDataService.persistMessage(any())).thenReturn(saved917); when(messageValidationService.performStateValidation(any(), anyList())).thenReturn(MovementsOrViolations.of(List.of(movement), List.of())); messageProcessingService.processMessage(cd917Xml); // then verify(validationService, times(0)).validateMovementMessage(any()); verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture()); verify(dossierDataService, times(0)).createMovement(any()); verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture()); verify(processMessageCommandProducer, times(0)).publish(any(), any(), any(Movement.class)); verify(ddntaMessageProducer, times(0)).publish(msgCD906CCaptor.capture(), eq("ceb0cc2b-dd74-495b-87cb-6ab27c7687fd")); assertThat(messageIdCaptor.getValue()).isEqualTo(saved917.getId()); assertThat(movementIdCaptor.getValue()).isEqualTo(movement.getId()); } protected Movement getMovement(String id, String officeRoleType, String officeId, String mrn, String lrn, String processingStatus) { return Movement.builder().id(id).officeRoleType(officeRoleType).officeId(officeId).mrn(mrn).lrn(lrn).processingStatus(processingStatus).build(); } protected MovementQuery getMovementQuery(String mrn) { return MovementQuery.builder().mrn(mrn).build(); } @Test @SneakyThrows void test_findTargetMovementForIncomingIE150() { String MRN = "22DKFUECYSBTH9ARK2"; List<Movement> movementListByMrn = generateMovementListByMrn(MRN); // MRN belongs to Operating Country -> Peak DEPARTURE with most recent updatedDateTime assertEquals("ooDep02", messageProcessingService.findTargetMovementForIncomingIE150(MRN, movementListByMrn, "DK").getOfficeId()); // MRN belongs to Operating Country and no DEPARTURE record found -> NotFoundException List<Movement> movementsWithoutDeparture = removeMovementsOfOfficeRoleType(movementListByMrn, EnumSet.of(OfficeRoleTypesEnum.DEPARTURE)); assertThrows(NotFoundException.class, () -> { messageProcessingService.findTargetMovementForIncomingIE150(MRN, movementsWithoutDeparture, "DK"); }); // Country of MRN is not Operating Country -> Peak DESTINATION with most recent updatedDateTime assertEquals("ooDest02", messageProcessingService.findTargetMovementForIncomingIE150(MRN, movementListByMrn, "DE").getOfficeId()); // Country of MRN is not Operating Country and DESTINATION removed -> Peak TRANSIT with most recent updatedDateTime assertEquals("ooTransit02", messageProcessingService.findTargetMovementForIncomingIE150(MRN, removeMovementsOfOfficeRoleType(movementListByMrn, EnumSet.of(OfficeRoleTypesEnum.DESTINATION)), "DE") .getOfficeId()); // Country of MRN is not Operating Country and DESTINATION and TRANSIT removed -> Peak EXIT with most recent updatedDateTime assertEquals("ooExit02", messageProcessingService.findTargetMovementForIncomingIE150(MRN, removeMovementsOfOfficeRoleType(movementListByMrn, EnumSet.of(OfficeRoleTypesEnum.DESTINATION, OfficeRoleTypesEnum.TRANSIT)), "DE") .getOfficeId()); // Country of MRN is not Operating Country and DESTINATION,TRANSIT and EXIT removed -> Peak INCIDENT with most recent updatedDateTime assertEquals("ooIncident02", messageProcessingService.findTargetMovementForIncomingIE150(MRN, removeMovementsOfOfficeRoleType(movementListByMrn, EnumSet.of(OfficeRoleTypesEnum.DESTINATION, OfficeRoleTypesEnum.TRANSIT, OfficeRoleTypesEnum.EXIT)), "DE") .getOfficeId()); // Country of MRN is not Operating Country and no record found for DESTINATION,TRANSIT,EXIT or INCIDENT. Return NULL assertNull(messageProcessingService.findTargetMovementForIncomingIE150(MRN, removeMovementsOfOfficeRoleType(movementListByMrn, EnumSet.of(OfficeRoleTypesEnum.DESTINATION, OfficeRoleTypesEnum.TRANSIT, OfficeRoleTypesEnum.EXIT, OfficeRoleTypesEnum.INCIDENT)), "DE") ); } @Test @SneakyThrows void test_findTargetMovementForIncomingIE152() { String MRN = "22DKFUECYSBTH9ARK2"; List<Movement> movementListByMrn = generateMovementListByMrn(MRN); when(getCountryCodeService.getCountryCode()).thenReturn("DK"); // return mrnCountryCode.equals(operatingCountry) && !messageSender.equals(operatingCountry); -> Departure assertEquals(1, messageProcessingService.findTargetMovementForIncomingIE152(MRN, "DE", movementListByMrn).size()); assertEquals("ooDep02", messageProcessingService.findTargetMovementForIncomingIE152(MRN, "DE", movementListByMrn).get(0).getOfficeId()); // otherwise any other existing movement except of Departure List<Movement> movementList = messageProcessingService.findTargetMovementForIncomingIE152(MRN, "DK", movementListByMrn); assertEquals(4, movementList.size()); for (OfficeRoleTypesEnum officeRoleTypesEnum : List.of(OfficeRoleTypesEnum.DESTINATION, OfficeRoleTypesEnum.TRANSIT, OfficeRoleTypesEnum.EXIT, OfficeRoleTypesEnum.INCIDENT)) { movementList.stream().map(movement -> assertThat(movement.getOfficeRoleType().contains(officeRoleTypesEnum.getValue()))); } } protected static List<Movement> generateMovementListByMrn(String MRN) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); List<Movement> movementList = Arrays.asList( Movement.builder() .mrn(MRN) .officeId("ooIncident01") .officeRoleType(OfficeRoleTypesEnum.INCIDENT.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:01", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooIncident02") .officeRoleType(OfficeRoleTypesEnum.INCIDENT.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:02", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooDep01") .officeRoleType(OfficeRoleTypesEnum.DEPARTURE.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:01", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooExit01") .officeRoleType(OfficeRoleTypesEnum.EXIT.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:01", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooExit02") .officeRoleType(OfficeRoleTypesEnum.EXIT.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:02", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooTransit01") .officeRoleType(OfficeRoleTypesEnum.TRANSIT.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:01", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooTransit02") .officeRoleType(OfficeRoleTypesEnum.TRANSIT.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:02", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooDest01") .officeRoleType(OfficeRoleTypesEnum.DESTINATION.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:01", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooDest02") .officeRoleType(OfficeRoleTypesEnum.DESTINATION.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:02", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooTansit02") .officeRoleType("Μπανάνες") .updatedDateTime(LocalDateTime.parse("2022-01-01 00:02", formatter)) .build(), Movement.builder() .mrn(MRN) .officeId("ooDep02") .officeRoleType(OfficeRoleTypesEnum.DEPARTURE.getValue()) .updatedDateTime(LocalDateTime.parse("2022-01-01 00:02", formatter)) .build() ); return movementList; } protected static List<Movement> removeMovementsOfOfficeRoleType(List<Movement> movementList, final EnumSet<OfficeRoleTypesEnum> officeRoleTypesEnumSet) { return movementList.stream() .filter(movement -> !officeRoleTypesEnumSet.contains(OfficeRoleTypesEnum.of(movement.getOfficeRoleType()))) .collect(Collectors.toList()); } private Movement nullifyMovementId(Movement movement) { return getMovement(null, movement.getOfficeRoleType(), movement.getOfficeId(), null, movement.getLrn(), ProcessingStatusTypeEnum.OODEP_NONE.getItemCode()); } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.validation.service; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.common.enums.ValidationRequestPropertyKeyEnum; import com.intrasoft.ermis.transit.common.exceptions.RetryableException; import com.intrasoft.ermis.transit.validation.configuration.ValidationRetryConfigurationProperties; import com.intrasoft.ermis.transit.validation.enums.BpmnFlowVariablesEnum; import com.intrasoft.ermis.transit.validation.enums.ValidationProcessInstanceEnum; import com.intrasoft.ermis.transit.validation.events.ValidationRequestedDomainEvent; import com.intrasoft.ermis.transit.validation.process.MainValidationFlowFacade; import lombok.RequiredArgsConstructor; import org.camunda.bpm.engine.RuntimeService; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class InitiateValidationServiceImpl implements InitiateValidationService { private final MainValidationFlowFacade mainValidationFlowFacade; private final RuntimeService runtimeService; private final ErmisLogger ermisLogger; // NOTE: Following bean is used in @Retryable SpEL expressions. private final ValidationRetryConfigurationProperties validationRetryConfigurationProperties; // TODO: Should probably add a @Recover method for RetryableException.class so that on complete failure, IE Message gets rejected. @Override @Retryable(value = {RetryableException.class}, maxAttemptsExpression = "#{@validationRetryConfigurationProperties.getMaxAttempts()}", backoff = @Backoff(delayExpression = "#{@validationRetryConfigurationProperties.getDelay()}", multiplierExpression = "#{@validationRetryConfigurationProperties.getMultiplier()}")) public void initiateValidationProcessRetryable(ValidationRequestedDomainEvent validationRequest) { // Check if validation is already running and throw exception to trigger retries: checkAndThrowIfValidationAlreadyRunning(validationRequest); // If no RetryableException was thrown, it is safe to initiate validation: mainValidationFlowFacade.initProcessInstance(validationRequest); } @Override public void initiateValidationProcess(ValidationRequestedDomainEvent validationRequest) { mainValidationFlowFacade.initProcessInstance(validationRequest); } private void checkAndThrowIfValidationAlreadyRunning(ValidationRequestedDomainEvent validationRequest) throws RetryableException { // Retrieve LRN from request event properties: String lrn = validationRequest.getProperties().get(ValidationRequestPropertyKeyEnum.LRN.getValue()); // Query Camunda to check if there is a running process for this LRN: boolean isValidationRunningForCurrentLRN = !runtimeService.createProcessInstanceQuery() .processDefinitionKey(ValidationProcessInstanceEnum.TRS_MAIN_VALIDATION_FLOW.getId()) .variableValueEquals(BpmnFlowVariablesEnum.LRN.getValue(), lrn) .active() .list() .isEmpty(); ermisLogger.info("Validation process for LRN: " + lrn + (isValidationRunningForCurrentLRN ? " is already running. Will retry..." : " is not running. Continuing...")); if (isValidationRunningForCurrentLRN) { throw new RetryableException("Validation already underway for LRN: " + lrn); } } }
package com.intrasoft.ermis.transit.validation.service; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.common.logging.ErmisLogger; import com.intrasoft.ermis.transit.common.enums.ValidationRequestPropertyKeyEnum; import com.intrasoft.ermis.transit.common.exceptions.RetryableException; import com.intrasoft.ermis.transit.validation.configuration.ValidationRetryConfigurationProperties; import com.intrasoft.ermis.transit.validation.events.ValidationRequestedDomainEvent; import com.intrasoft.ermis.transit.validation.process.MainValidationFlowFacade; import com.intrasoft.ermis.transit.validation.service.InitiateValidationServiceUT.TestConfig; import java.util.Collections; import java.util.List; import java.util.Map; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; import org.camunda.bpm.extension.mockito.CamundaMockito; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.retry.annotation.EnableRetry; import org.springframework.test.context.ContextConfiguration; @SpringBootTest @ContextConfiguration(classes = TestConfig.class) class InitiateValidationServiceUT { public static final int TEST_RETRIES = 5; private static final String LRN = "TEST_LRN"; @MockBean private MainValidationFlowFacade mainValidationFlowFacade; @MockBean private RuntimeService runtimeService; @MockBean private ErmisLogger ermisLogger; @Autowired private InitiateValidationService initiateValidationService; @ParameterizedTest @DisplayName("Test - Initiate Validation Process - Retryable") @ValueSource(booleans = {true, false}) void testInitiateValidationProcessRetryable(boolean processRunning) { // Mock the behavior to simulate that no validation is running for LRN: when(runtimeService.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); if (processRunning) { // Using ExecutionEntity as ProcessInstance extends it: ExecutionEntity processInstance = new ExecutionEntity(); CamundaMockito.mockProcessInstanceQuery(runtimeService).list(List.of(processInstance)); // Call the service method: assertThrows(RetryableException.class, () -> initiateValidationService.initiateValidationProcessRetryable(buildRequestEvent())); // Verify that initProcessInstance is not called when retries are triggered: verify(mainValidationFlowFacade, never()).initProcessInstance(any()); // RuntimeService should be queried #maxAttempts amount of times: verify(runtimeService, times(TEST_RETRIES)).createProcessInstanceQuery(); } else { CamundaMockito.mockProcessInstanceQuery(runtimeService).list(Collections.emptyList()); // Call the service method: initiateValidationService.initiateValidationProcessRetryable(buildRequestEvent()); // Verify that initProcessInstance is called once verify(mainValidationFlowFacade, times(1)).initProcessInstance(any()); } } @Test @DisplayName("Test - Initiate Validation Process") void testInitiateValidationProcessRetryable() { // Call the service method: initiateValidationService.initiateValidationProcess(buildRequestEvent()); // Verify that initProcessInstance is called once verify(mainValidationFlowFacade, times(1)).initProcessInstance(any()); } private ValidationRequestedDomainEvent buildRequestEvent() { return ValidationRequestedDomainEvent.builder() .properties(Map.of(ValidationRequestPropertyKeyEnum.LRN.getValue(), LRN)) .build(); } @EnableRetry @Configuration @Import(InitiateValidationServiceImpl.class) public static class TestConfig { @Bean(name = "validationRetryConfigurationProperties") public ValidationRetryConfigurationProperties validationRetryConfigurationProperties() { return new ValidationRetryConfigurationProperties() { @Override public int getMaxAttempts() { return TEST_RETRIES; } @Override public long getDelay() { return 100; } @Override public double getMultiplier() { return 1.5; } }; } } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service; import com.intrasoft.ermis.cargov1.messages.TB015CType; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.common.enums.AdditionalDeclarationTypeEnum; import javax.xml.bind.JAXBException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class DeclarationRegistrationServiceImpl implements DeclarationRegistrationService { private final DossierDataService dossierDataService; @Override public boolean isDeclarationPrelodged(String messageId) throws JAXBException { Message tb015c = dossierDataService.getMessageById(messageId); TB015CType tb015cType = XmlConverter.buildMessageFromXML(tb015c.getPayload(), TB015CType.class); return AdditionalDeclarationTypeEnum.DECLARATION_TYPE_D.getType().equals(tb015cType.getTransitOperation().getAdditionalDeclarationType()); } }
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.cargov1.messages.TB015CType; import com.intrasoft.ermis.common.xml.parsing.XmlConverter; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DeclarationRegistrationServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.test.util.TestDataUtilities; import com.intrasoft.ermis.transit.common.enums.AdditionalDeclarationTypeEnum; import com.intrasoft.ermis.transit.shared.testing.util.FileHelpers; import java.util.UUID; import javax.xml.bind.JAXBException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class DeclarationRegistrationServiceUT { private static final String MESSAGE_ID = UUID.randomUUID().toString(); @Mock private DossierDataService dossierDataService; @InjectMocks private DeclarationRegistrationServiceImpl declarationRegistrationService; @ParameterizedTest @DisplayName("Test if the TB015C declaration is prelodged ") @ValueSource(strings = {"A", "D"}) void test_isDeclarationPrelodged(String additionalDeclarationType) throws JAXBException { String tb015cStringXml = FileHelpers.xmlToString(MessageTypes.TB_015_C.value() + ".xml"); TB015CType tb015CType = XmlConverter.buildMessageFromXML(tb015cStringXml, TB015CType.class); tb015CType.getTransitOperation().setAdditionalDeclarationType(additionalDeclarationType); String updatedXmlString = XmlConverter.marshal(tb015CType); when(dossierDataService.getMessageById(MESSAGE_ID)).thenReturn( TestDataUtilities.createMessage(MESSAGE_ID, MessageTypes.TB_015_C.value(), updatedXmlString)); boolean isPrelodged = declarationRegistrationService.isDeclarationPrelodged(MESSAGE_ID); if (AdditionalDeclarationTypeEnum.DECLARATION_TYPE_D.getType().equals(additionalDeclarationType)) { assertTrue(isPrelodged); } else { assertFalse(isPrelodged); } } }
You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class.