Search in sources :

Example 1 with MappingMetadataDto

use of org.folio.MappingMetadataDto in project mod-inventory by folio-org.

the class MarcBibModifiedPostProcessingEventHandler method handle.

@Override
public CompletableFuture<DataImportEventPayload> handle(DataImportEventPayload dataImportEventPayload) {
    CompletableFuture<DataImportEventPayload> future = new CompletableFuture<>();
    try {
        HashMap<String, String> payloadContext = dataImportEventPayload.getContext();
        if (isNull(payloadContext) || isBlank(payloadContext.get(MARC_BIBLIOGRAPHIC.value()))) {
            LOGGER.error(PAYLOAD_HAS_NO_DATA_MSG);
            return CompletableFuture.failedFuture(new EventProcessingException(PAYLOAD_HAS_NO_DATA_MSG));
        }
        LOGGER.info("Processing ReplaceInstanceEventHandler starting with jobExecutionId: {}.", dataImportEventPayload.getJobExecutionId());
        Record record = new JsonObject(payloadContext.get(MARC_BIBLIOGRAPHIC.value())).mapTo(Record.class);
        String instanceId = ParsedRecordUtil.getAdditionalSubfieldValue(record.getParsedRecord(), ParsedRecordUtil.AdditionalSubfields.I);
        if (isBlank(instanceId)) {
            return CompletableFuture.completedFuture(dataImportEventPayload);
        }
        record.setExternalIdsHolder(new ExternalIdsHolder().withInstanceId(instanceId));
        Context context = EventHandlingUtil.constructContext(dataImportEventPayload.getTenant(), dataImportEventPayload.getToken(), dataImportEventPayload.getOkapiUrl());
        Promise<Instance> instanceUpdatePromise = Promise.promise();
        mappingMetadataCache.get(dataImportEventPayload.getJobExecutionId(), context).map(parametersOptional -> parametersOptional.orElseThrow(() -> new EventProcessingException(format(MAPPING_METADATA_NOT_FOUND_MSG, dataImportEventPayload.getJobExecutionId())))).map(mappingMetadataDto -> buildPayloadForInstanceUpdate(dataImportEventPayload, mappingMetadataDto)).compose(payloadForUpdate -> instanceUpdateDelegate.handle(payloadForUpdate, record, context)).onSuccess(instanceUpdatePromise::complete).compose(updatedInstance -> precedingSucceedingTitlesHelper.getExistingPrecedingSucceedingTitles(updatedInstance, context)).map(precedingSucceedingTitles -> precedingSucceedingTitles.stream().map(titleJson -> titleJson.getString("id")).collect(Collectors.toSet())).compose(precedingSucceedingTitles -> precedingSucceedingTitlesHelper.deletePrecedingSucceedingTitles(precedingSucceedingTitles, context)).compose(ar -> precedingSucceedingTitlesHelper.createPrecedingSucceedingTitles(instanceUpdatePromise.future().result(), context)).onComplete(updateAr -> {
            if (updateAr.succeeded()) {
                dataImportEventPayload.getContext().remove(CURRENT_RETRY_NUMBER);
                Instance resultedInstance = instanceUpdatePromise.future().result();
                if (resultedInstance.getVersion() != null) {
                    int currentVersion = Integer.parseInt(resultedInstance.getVersion());
                    int incrementedVersion = currentVersion + 1;
                    resultedInstance.setVersion(String.valueOf(incrementedVersion));
                }
                dataImportEventPayload.getContext().put(INSTANCE.value(), Json.encode(resultedInstance));
                future.complete(dataImportEventPayload);
            } else {
                if (updateAr.cause() instanceof OptimisticLockingException) {
                    processOLError(dataImportEventPayload, future, updateAr);
                } else {
                    dataImportEventPayload.getContext().remove(CURRENT_RETRY_NUMBER);
                    LOGGER.error("Error updating inventory instance by id: '{}' by jobExecutionId: '{}'", instanceId, dataImportEventPayload.getJobExecutionId(), updateAr.cause());
                    future.completeExceptionally(updateAr.cause());
                }
            }
        });
    } catch (Exception e) {
        dataImportEventPayload.getContext().remove(CURRENT_RETRY_NUMBER);
        LOGGER.error("Error updating inventory instance", e);
        future.completeExceptionally(e);
    }
    return future;
}
Also used : Context(org.folio.inventory.common.Context) ParsedRecordUtil(org.folio.inventory.dataimport.util.ParsedRecordUtil) Json(io.vertx.core.json.Json) Context(org.folio.inventory.common.Context) MappingMetadataDto(org.folio.MappingMetadataDto) EventHandler(org.folio.processing.events.services.handler.EventHandler) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) MARC_BIBLIOGRAPHIC(org.folio.rest.jaxrs.model.EntityType.MARC_BIBLIOGRAPHIC) ExternalIdsHolder(org.folio.rest.jaxrs.model.ExternalIdsHolder) Map(java.util.Map) EntityType(org.folio.rest.jaxrs.model.EntityType) MAPPING_PROFILE(org.folio.rest.jaxrs.model.ProfileSnapshotWrapper.ContentType.MAPPING_PROFILE) JsonObject(io.vertx.core.json.JsonObject) Objects.isNull(java.util.Objects.isNull) AsyncResult(io.vertx.core.AsyncResult) MappingProfile(org.folio.MappingProfile) Record(org.folio.rest.jaxrs.model.Record) Promise(io.vertx.core.Promise) DataImportEventPayload(org.folio.DataImportEventPayload) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Logger(org.apache.logging.log4j.Logger) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) EventHandlingUtil(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil) INSTANCE(org.folio.ActionProfile.FolioRecord.INSTANCE) Instance(org.folio.inventory.domain.instances.Instance) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) LogManager(org.apache.logging.log4j.LogManager) DI_SRS_MARC_BIB_RECORD_MODIFIED_READY_FOR_POST_PROCESSING(org.folio.DataImportEventTypes.DI_SRS_MARC_BIB_RECORD_MODIFIED_READY_FOR_POST_PROCESSING) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) ExternalIdsHolder(org.folio.rest.jaxrs.model.ExternalIdsHolder) Instance(org.folio.inventory.domain.instances.Instance) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) JsonObject(io.vertx.core.json.JsonObject) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) DataImportEventPayload(org.folio.DataImportEventPayload) CompletableFuture(java.util.concurrent.CompletableFuture) Record(org.folio.rest.jaxrs.model.Record) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 2 with MappingMetadataDto

use of org.folio.MappingMetadataDto in project mod-inventory by folio-org.

the class AbstractMatchEventHandler method handle.

@Override
public CompletableFuture<DataImportEventPayload> handle(DataImportEventPayload dataImportEventPayload) {
    CompletableFuture<DataImportEventPayload> future = new CompletableFuture<>();
    dataImportEventPayload.getEventsChain().add(dataImportEventPayload.getEventType());
    Context context = constructContext(dataImportEventPayload.getTenant(), dataImportEventPayload.getToken(), dataImportEventPayload.getOkapiUrl());
    mappingMetadataCache.get(dataImportEventPayload.getJobExecutionId(), context).toCompletionStage().thenCompose(metadataOptional -> metadataOptional.map(mappingMetadataDto -> doMatching(dataImportEventPayload, mappingMetadataDto, new MatchingParametersRelations())).orElse(CompletableFuture.failedFuture(new EventProcessingException(MAPPING_METADATA_NOT_FOUND_MSG)))).whenComplete((matched, throwable) -> {
        if (throwable != null) {
            future.completeExceptionally(throwable);
        } else {
            if (Boolean.TRUE.equals(matched)) {
                dataImportEventPayload.setEventType(getMatchedEventType());
            } else {
                dataImportEventPayload.setEventType(getNotMatchedEventType());
            }
            future.complete(dataImportEventPayload);
        }
    });
    return future;
}
Also used : Context(org.folio.inventory.common.Context) EventHandlingUtil.constructContext(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil.constructContext) Json(io.vertx.core.json.Json) Context(org.folio.inventory.common.Context) MappingMetadataDto(org.folio.MappingMetadataDto) EventHandler(org.folio.processing.events.services.handler.EventHandler) DataImportEventPayload(org.folio.DataImportEventPayload) CompletableFuture(java.util.concurrent.CompletableFuture) MATCH_PROFILE(org.folio.rest.jaxrs.model.ProfileSnapshotWrapper.ContentType.MATCH_PROFILE) EventHandlingUtil.constructContext(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil.constructContext) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) EntityType(org.folio.rest.jaxrs.model.EntityType) JsonObject(io.vertx.core.json.JsonObject) MatchProfile(org.folio.MatchProfile) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) MatchingParametersRelations(org.folio.inventory.dataimport.handlers.matching.util.MatchingParametersRelations) MatchingManager(org.folio.processing.matching.MatchingManager) CompletableFuture(java.util.concurrent.CompletableFuture) MatchingParametersRelations(org.folio.inventory.dataimport.handlers.matching.util.MatchingParametersRelations) DataImportEventPayload(org.folio.DataImportEventPayload) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 3 with MappingMetadataDto

use of org.folio.MappingMetadataDto in project mod-inventory by folio-org.

the class MatchInstanceEventHandlerUnitTest method setUp.

@Before
public void setUp() {
    MatchValueReaderFactory.clearReaderFactory();
    MatchValueLoaderFactory.clearLoaderFactory();
    MockitoAnnotations.initMocks(this);
    when(marcValueReader.isEligibleForEntityType(MARC_BIBLIOGRAPHIC)).thenReturn(true);
    when(storage.getInstanceCollection(any(Context.class))).thenReturn(instanceCollection);
    when(marcValueReader.read(any(DataImportEventPayload.class), any(MatchDetail.class))).thenReturn(StringValue.of(INSTANCE_HRID));
    MatchValueReaderFactory.register(marcValueReader);
    MatchValueLoaderFactory.register(instanceLoader);
    when(mappingMetadataCache.get(anyString(), any(Context.class))).thenReturn(Future.succeededFuture(Optional.of(new MappingMetadataDto().withMappingRules(new JsonObject().encode()).withMappingParams(LOCATIONS_PARAMS))));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Context(org.folio.inventory.common.Context) JsonObject(io.vertx.core.json.JsonObject) MappingMetadataDto(org.folio.MappingMetadataDto) MatchDetail(org.folio.MatchDetail) DataImportEventPayload(org.folio.DataImportEventPayload) Before(org.junit.Before)

Example 4 with MappingMetadataDto

use of org.folio.MappingMetadataDto in project mod-inventory by folio-org.

the class CreateItemEventHandlerTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    Mockito.when(fakeReaderFactory.createReader()).thenReturn(fakeReader);
    Mockito.when(fakeReader.read(any(MappingRule.class))).thenReturn(StringValue.of(AVAILABLE.value()), StringValue.of(UUID.randomUUID().toString()), StringValue.of(UUID.randomUUID().toString()), StringValue.of("645398607547"));
    Mockito.when(mockedStorage.getItemCollection(ArgumentMatchers.any(Context.class))).thenReturn(mockedItemCollection);
    Mockito.when(mappingMetadataCache.get(anyString(), any(Context.class))).thenReturn(Future.succeededFuture(Optional.of(new MappingMetadataDto().withMappingRules(new JsonObject().encode()).withMappingParams(Json.encode(new MappingParameters())))));
    createItemHandler = new CreateItemEventHandler(mockedStorage, mappingMetadataCache, itemIdStorageService);
    MappingManager.clearReaderFactories();
}
Also used : Context(org.folio.inventory.common.Context) JsonObject(io.vertx.core.json.JsonObject) MappingMetadataDto(org.folio.MappingMetadataDto) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) MappingRule(org.folio.rest.jaxrs.model.MappingRule) Before(org.junit.Before)

Example 5 with MappingMetadataDto

use of org.folio.MappingMetadataDto in project mod-inventory by folio-org.

the class CreateMarcHoldingsEventHandlerTest method setUp.

@Before
public void setUp() throws IOException {
    MockitoAnnotations.openMocks(this);
    MappingManager.clearReaderFactories();
    MappingMetadataCache mappingMetadataCache = new MappingMetadataCache(vertx, vertx.createHttpClient(), 3600);
    createMarcHoldingsEventHandler = new CreateMarcHoldingsEventHandler(storage, mappingMetadataCache, holdingsIdStorageService);
    mappingRules = new JsonObject(TestUtil.readFileFromPath(MAPPING_RULES_PATH));
    doAnswer(invocationOnMock -> {
        instanceId = String.valueOf(UUID.randomUUID());
        Instance instance = new Instance(instanceId, "2", String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID()));
        List<Instance> instanceList = Collections.singletonList(instance);
        MultipleRecords<Instance> result = new MultipleRecords<>(instanceList, 1);
        Consumer<Success<MultipleRecords<Instance>>> successHandler = invocationOnMock.getArgument(2);
        successHandler.accept(new Success<>(result));
        return null;
    }).when(instanceRecordCollection).findByCql(anyString(), any(PagingParameters.class), any(Consumer.class), any(Consumer.class));
    doAnswer(invocationOnMock -> {
        HoldingsRecord holdingsRecord = invocationOnMock.getArgument(0);
        Consumer<Success<HoldingsRecord>> successHandler = invocationOnMock.getArgument(1);
        successHandler.accept(new Success<>(holdingsRecord));
        return null;
    }).when(holdingsRecordsCollection).add(any(), any(Consumer.class), any(Consumer.class));
    doAnswer(invocationOnMock -> {
        recordId = String.valueOf(UUID.randomUUID());
        holdingsId = String.valueOf(UUID.randomUUID());
        RecordToEntity recordToHoldings = RecordToEntity.builder().recordId(recordId).entityId(holdingsId).build();
        return Future.succeededFuture(recordToHoldings);
    }).when(holdingsIdStorageService).store(any(), any(), any());
    WireMock.stubFor(get(new UrlPathPattern(new RegexPattern(MAPPING_METADATA_URL + "/.*"), true)).willReturn(WireMock.ok().withBody(Json.encode(new MappingMetadataDto().withMappingParams(Json.encode(new MappingParameters())).withMappingRules(mappingRules.encode())))));
}
Also used : PagingParameters(org.folio.inventory.common.api.request.PagingParameters) Instance(org.folio.inventory.domain.instances.Instance) RegexPattern(com.github.tomakehurst.wiremock.matching.RegexPattern) JsonObject(io.vertx.core.json.JsonObject) MappingMetadataDto(org.folio.MappingMetadataDto) Success(org.folio.inventory.common.domain.Success) RecordToEntity(org.folio.inventory.domain.relationship.RecordToEntity) HoldingsRecord(org.folio.HoldingsRecord) Consumer(java.util.function.Consumer) UrlPathPattern(com.github.tomakehurst.wiremock.matching.UrlPathPattern) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) MultipleRecords(org.folio.inventory.common.domain.MultipleRecords) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) Before(org.junit.Before)

Aggregations

MappingMetadataDto (org.folio.MappingMetadataDto)23 JsonObject (io.vertx.core.json.JsonObject)21 Context (org.folio.inventory.common.Context)17 Before (org.junit.Before)16 MappingParameters (org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters)13 Success (org.folio.inventory.common.domain.Success)12 MappingMetadataCache (org.folio.inventory.dataimport.cache.MappingMetadataCache)11 Consumer (java.util.function.Consumer)8 DataImportEventPayload (org.folio.DataImportEventPayload)8 TestContext (io.vertx.ext.unit.TestContext)7 HoldingsRecord (org.folio.HoldingsRecord)7 Instance (org.folio.inventory.domain.instances.Instance)7 RegexPattern (com.github.tomakehurst.wiremock.matching.RegexPattern)6 UrlPathPattern (com.github.tomakehurst.wiremock.matching.UrlPathPattern)6 Record (org.folio.rest.jaxrs.model.Record)6 EventProcessingException (org.folio.processing.exceptions.EventProcessingException)5 Promise (io.vertx.core.Promise)4 Json (io.vertx.core.json.Json)4 KafkaConsumerRecord (io.vertx.kafka.client.consumer.KafkaConsumerRecord)4 String.format (java.lang.String.format)4