repo_id
stringclasses
1 value
file_path
stringlengths
83
111
content
stringlengths
994
134k
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/ProcessingStatusServiceUT.java
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.mockito.Mockito.verify; import static org.junit.jupiter.api.Assertions.assertEquals; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService; import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ProcessingStatusServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus; import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ProcessingStatusServiceUT { private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID"; @Mock private DossierDataService dossierDataService; @InjectMocks private ProcessingStatusServiceImpl processingStatusService; @Captor private ArgumentCaptor<ProcessingStatus> processingStatusArgumentCaptor; @Test @DisplayName("Test - Save Processing Status") void testSaveProcessingStatus() { // Call ProcessingStatusService method: processingStatusService.saveProcessingStatus(MOVEMENT_ID, ProcessingStatusTypeEnum.CARGO_OODEST_WRITTEN_OFF.getItemCode()); // Verification & Assertions: verify(dossierDataService).saveProcessingStatus(processingStatusArgumentCaptor.capture()); assertEquals(MOVEMENT_ID, processingStatusArgumentCaptor.getValue().getMovementId()); assertEquals(ProcessingStatusTypeEnum.CARGO_OODEST_WRITTEN_OFF.getItemCode(), processingStatusArgumentCaptor.getValue().getStatus()); } }
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/HandleDDNTAMessageServiceImpl.java
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()); } } }
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/DossierDataServiceUT.java
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.intrasoft.ermis.cargov1.messages.MessageTypes; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapper; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapperImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service.DossierDataServiceImpl; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus; import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult; import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum; import com.intrasoft.ermis.platform.contracts.dossier.dtos.DeclarationDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.MessageDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.MovementDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.PaginatedDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.ProcessingStatusDTO; import com.intrasoft.ermis.platform.contracts.dossier.dtos.ValidationResultDTO; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierDeclarationPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMessagePort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMovementPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierProcessingStatusPort; import com.intrasoft.ermis.transit.shared.dossier.clients.DossierValidationResultsPort; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.ResponseEntity; @ExtendWith(MockitoExtension.class) class DossierDataServiceUT { private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID"; private static final String MESSAGE_ID = "TEST_MESSAGE_ID"; private static final String MESSAGE_IDENTIFICATION = "TEST_MESSAGE_IDENTIFICATION"; private static final String MRN = "TEST_MRN"; @Mock private DossierMovementPort dossierMovementPort; @Mock private DossierMessagePort dossierMessagePort; @Mock private DossierProcessingStatusPort dossierProcessingStatusPort; @Mock private DossierDeclarationPort dossierDeclarationPort; @Mock private DossierValidationResultsPort dossierValidationResultsPort; @Spy private MovementDTOMapper movementDTOMapper = new MovementDTOMapperImpl(); @Spy private MessageDTOMapper messageDTOMapper = new MessageDTOMapperImpl(); @Spy private MessageOverviewDTOMapper messageOverviewDTOMapper = new MessageOverviewDTOMapperImpl(); @Spy private ProcessingStatusDTOMapper processingStatusDTOMapper = new ProcessingStatusDTOMapperImpl(); @Spy private DeclarationDTOMapper declarationDTOMapper = new DeclarationDTOMapperImpl(); @Spy private ValidationResultDTOMapper validationResultDTOMapper = new ValidationResultDTOMapperImpl(); @InjectMocks private DossierDataServiceImpl dossierDataService; @Captor private ArgumentCaptor<MovementDTO> movementDTOArgumentCaptor; @Captor private ArgumentCaptor<ProcessingStatusDTO> processingStatusDTOArgumentCaptor; @Captor private ArgumentCaptor<DeclarationDTO> declarationDTOArgumentCaptor; @Captor private ArgumentCaptor<MessageDTO> messageDTOArgumentCaptor; @Captor private ArgumentCaptor<List<ValidationResultDTO>> validationResultDTOListArgumentCaptor; @Captor private ArgumentCaptor<String> messageIdCaptor; @Captor private ArgumentCaptor<String> statusCaptor; @Test @DisplayName("Test - Get Movement by ID") void testGetMovementById() { // Stub: when(dossierMovementPort.findById(MOVEMENT_ID, false)).thenReturn(ResponseEntity.ok(new MovementDTO())); // Call DossierDataService method: dossierDataService.getMovementById(MOVEMENT_ID); // Verification: verify(dossierMovementPort, times(1)).findById(MOVEMENT_ID, false); } @Test @DisplayName("Test - Update Movement") void testUpdateMovement() { Movement testMovement = Movement.builder().id(MOVEMENT_ID).build(); // Stub: when(dossierMovementPort.update(any(), eq(MOVEMENT_ID))).thenReturn(ResponseEntity.ok(new MovementDTO())); // Call DossierDataService method: dossierDataService.updateMovement(testMovement); // Verification & Assertion: verify(dossierMovementPort, times(1)).update(movementDTOArgumentCaptor.capture(), eq(MOVEMENT_ID)); assertEquals(MOVEMENT_ID, movementDTOArgumentCaptor.getValue().getId()); } @Test @DisplayName("Test - Get Message Overview List") void testGetMessageOverviewList() { // Stub: when(dossierMessagePort.findOverviewByCriteria(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null, null, null, null, 0, 20, false)).thenReturn(ResponseEntity.ok(new PaginatedDTO<>())); // Call DossierDataService method: dossierDataService.getMessageOverviewList(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null); // Verification: verify(dossierMessagePort, times(1)).findOverviewByCriteria(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null, null, null, null, 0, 20, false); } @Test @DisplayName("Test - Save Message") void testSaveMessage() { Message testMessage = Message.builder().messageIdentification(MESSAGE_IDENTIFICATION).build(); // Stub: when(dossierMessagePort.add(any(MessageDTO.class))).thenReturn(ResponseEntity.ok(new MessageDTO())); // Call DossierDataService method: dossierDataService.saveMessage(testMessage); // Verification & Assertion: verify(dossierMessagePort, times(1)).add(messageDTOArgumentCaptor.capture()); assertEquals(MESSAGE_IDENTIFICATION, messageDTOArgumentCaptor.getValue().getMessageIdentification()); } @Test @DisplayName("Test - Get Message by ID") void testGetMessageById() { // Stub: when(dossierMessagePort.findById(MESSAGE_ID, false, false, false)).thenReturn(ResponseEntity.ok(new MessageDTO())); // Call DossierDataService method: dossierDataService.getMessageById(MESSAGE_ID); // Verification: verify(dossierMessagePort, times(1)).findById(MESSAGE_ID, false, false, false); } @Test @DisplayName("Test - Associate Message with Movement") void testAssociateMessageWithMovement() { // Stub: when(dossierMessagePort.associateMovement(MESSAGE_ID, MOVEMENT_ID)).thenReturn(ResponseEntity.ok(null)); // Call DossierDataService method: dossierDataService.associateMessageWithMovement(MESSAGE_ID, MOVEMENT_ID); // Verification: verify(dossierMessagePort, times(1)).associateMovement(MESSAGE_ID, MOVEMENT_ID); } @Test @DisplayName("Test - Update Message Status") void testUpdateMessageStatus() { // Stub: when(dossierMessagePort.update(MESSAGE_ID, MessageStatusEnum.REJECTED.name())).thenReturn(ResponseEntity.ok(new MessageDTO())); // Call DossierDataService method: dossierDataService.updateMessageStatus(MESSAGE_ID, MessageStatusEnum.REJECTED.name()); // Verification: verify(dossierMessagePort, times(1)).update(MESSAGE_ID, MessageStatusEnum.REJECTED.name()); } @Test @DisplayName("Test - Save Processing Status") void testSaveProcessingStatus() { ProcessingStatus testProcessingStatus = ProcessingStatus.builder() .movementId(MOVEMENT_ID) .status("TEST_STATUS") .reasonType("TEST_REASON") .build(); // Call DossierDataService method: dossierDataService.saveProcessingStatus(testProcessingStatus); // Verification & Assertions: verify(dossierProcessingStatusPort, times(1)).add(processingStatusDTOArgumentCaptor.capture()); assertEquals(testProcessingStatus.getMovementId(), processingStatusDTOArgumentCaptor.getValue().getMovementId()); assertEquals(testProcessingStatus.getStatus(), processingStatusDTOArgumentCaptor.getValue().getStatus()); assertEquals(testProcessingStatus.getReasonType(), processingStatusDTOArgumentCaptor.getValue().getReasonType()); } @Test @DisplayName("Test - Create Declaration") void testCreateDeclaration() { Declaration testMovement = Declaration.builder().movementId(MOVEMENT_ID).build(); // Call DossierDataService method: dossierDataService.createDeclaration(testMovement); // Verification & Assertion: verify(dossierDeclarationPort, times(1)).add(declarationDTOArgumentCaptor.capture()); assertEquals(MOVEMENT_ID, declarationDTOArgumentCaptor.getValue().getMovementId()); } @Test @DisplayName("Test - Get latest Declaration by Movement ID") void testGetLatestDeclarationByMovementId() { // Stub: when(dossierDeclarationPort.findCurrentVersionByMovementId(MOVEMENT_ID, false, false)).thenReturn(ResponseEntity.ok(new DeclarationDTO())); // Call DossierDataService method: dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID); // Verification: verify(dossierDeclarationPort, times(1)).findCurrentVersionByMovementId(MOVEMENT_ID, false, false); } @Test @DisplayName("Test - Save Validation Result List") void testSaveValidationResultList() { List<ValidationResult> testValidationResultList = new ArrayList<>(); ValidationResult testValidationResult = new ValidationResult(); testValidationResult.setMessageId(MESSAGE_ID); testValidationResultList.add(testValidationResult); // Call DossierDataService method: dossierDataService.saveValidationResultList(testValidationResultList); // Verification & Assertion: verify(dossierValidationResultsPort, times(1)).saveValidationResults(validationResultDTOListArgumentCaptor.capture()); assertEquals(MESSAGE_ID, validationResultDTOListArgumentCaptor.getValue().get(0).getMessageId()); } @Test @DisplayName("Test - Find Validation Result list by Message ID") void testFindValidationResultListByMessageId() { // Stub: when(dossierValidationResultsPort.findValidationResultsByMessageId(MESSAGE_ID)).thenReturn(ResponseEntity.ok(new ArrayList<>())); // Call DossierDataService method: dossierDataService.findValidationResultListByMessageId(MESSAGE_ID); // Verification: verify(dossierValidationResultsPort, times(1)).findValidationResultsByMessageId(MESSAGE_ID); } @ParameterizedTest @DisplayName("Test - MRN Exists") @ValueSource(booleans = {true, false}) void testMRNExists(boolean mrnExists) { // Stub: when(dossierMovementPort.existsByCriteria(MRN, null, null, null)) .thenReturn(ResponseEntity.ok(mrnExists)); // Call DossierDataService method: boolean returnedValue = dossierDataService.mrnExists(MRN); // Verification & Assertion: verify(dossierMovementPort, times(1)).existsByCriteria(MRN, null, null, null); assertEquals(mrnExists, returnedValue); } }
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/GenerateMessageServiceImpl.java
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; } }
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/AmendmentRequestServiceImpl.java
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); } }
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/ExternalSystemValidationServiceImpl.java
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"); } }
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/ProcessPersonDetailsServiceImpl.java
"package com.intrasoft.ermis.transit.officeofdeparture.service;\n\nimport com.intrasoft.ermis.common(...TRUNCATED)
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/HandleDDNTAMessageServiceUT.java
"package com.intrasoft.ermis.trs.officeofdeparture.service;\n\nimport static org.junit.jupiter.api.A(...TRUNCATED)
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/ProcessingStatusServiceImpl.java
"package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;\n\nimport com.intrasoft.(...TRUNCATED)
samlple_tests
/home/gerasmark/IdeaProjects/FineTuning/Code-LLM/sample-tests/CustomsOfficerActionServiceImpl.java
"package com.intrasoft.ermis.transit.officeofdeparture.service;\n\nimport com.intrasoft.ermis.common(...TRUNCATED)
README.md exists but content is empty.
Downloads last month
40