input
stringlengths 994
134k
| 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;\n\nimport com.intrasoft.ermis.common(...TRUNCATED) | "package com.intrasoft.ermis.trs.officeofdeparture.service;\n\nimport static org.junit.jupiter.api.A(...TRUNCATED) | "You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for t(...TRUNCATED) |
"package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;\n\nimport com.intrasoft.(...TRUNCATED) | "package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;\n\nimport static org.moc(...TRUNCATED) | "You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for t(...TRUNCATED) |
"package com.intrasoft.ermis.transit.officeofdeparture.service;\n\nimport com.intrasoft.ermis.common(...TRUNCATED) | "package com.intrasoft.ermis.trs.officeofdeparture;\n\nimport static org.junit.jupiter.api.Assertion(...TRUNCATED) | "You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for t(...TRUNCATED) |
"package com.intrasoft.ermis.transit.officeofexitfortransit.core.service;\n\nimport com.intrasoft.er(...TRUNCATED) | "package com.intrasoft.ermis.transit.officeofexitfortransit.service;\n\nimport static org.junit.jupi(...TRUNCATED) | "You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for t(...TRUNCATED) |
"package com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service;\n\nimport com.intraso(...TRUNCATED) | "package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;\n\nimport static org.jun(...TRUNCATED) | "You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for t(...TRUNCATED) |
"package com.intrasoft.ermis.transit.management.core.service;\n\nimport static com.intrasoft.ermis.t(...TRUNCATED) | "package com.intrasoft.ermis.transit.management.core.actions;\n\nimport static com.intrasoft.ermis.d(...TRUNCATED) | "You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for t(...TRUNCATED) |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 30