Search in sources :

Example 21 with Context

use of org.folio.inventory.common.Context in project mod-inventory by folio-org.

the class DataImportKafkaHandler method handle.

@Override
public Future<String> handle(KafkaConsumerRecord<String, String> record) {
    try {
        Promise<String> promise = Promise.promise();
        Event event = Json.decodeValue(record.value(), Event.class);
        DataImportEventPayload eventPayload = Json.decodeValue(event.getEventPayload(), DataImportEventPayload.class);
        Map<String, String> headersMap = KafkaHeaderUtils.kafkaHeadersToMap(record.headers());
        String recordId = headersMap.get(RECORD_ID_HEADER);
        String chunkId = headersMap.get(CHUNK_ID_HEADER);
        String jobExecutionId = eventPayload.getJobExecutionId();
        LOGGER.info("Data import event payload has been received with event type: {}, recordId: {} by jobExecution: {} and chunkId: {}", eventPayload.getEventType(), recordId, jobExecutionId, chunkId);
        eventPayload.getContext().put(RECORD_ID_HEADER, recordId);
        eventPayload.getContext().put(CHUNK_ID_HEADER, chunkId);
        Context context = EventHandlingUtil.constructContext(eventPayload.getTenant(), eventPayload.getToken(), eventPayload.getOkapiUrl());
        String jobProfileSnapshotId = eventPayload.getContext().get(PROFILE_SNAPSHOT_ID_KEY);
        profileSnapshotCache.get(jobProfileSnapshotId, context).toCompletionStage().thenCompose(snapshotOptional -> snapshotOptional.map(profileSnapshot -> EventManager.handleEvent(eventPayload, profileSnapshot)).orElse(CompletableFuture.failedFuture(new EventProcessingException(format("Job profile snapshot with id '%s' does not exist", jobProfileSnapshotId))))).whenComplete((processedPayload, throwable) -> {
            if (throwable != null) {
                promise.fail(throwable);
            } else if (DI_ERROR.value().equals(processedPayload.getEventType())) {
                promise.fail("Failed to process data import event payload");
            } else {
                promise.complete(record.key());
            }
        });
        return promise.future();
    } catch (Exception e) {
        LOGGER.error(format("Failed to process data import kafka record from topic %s", record.topic()), e);
        return Future.failedFuture(e);
    }
}
Also used : Context(org.folio.inventory.common.Context) AuthorityLoader(org.folio.inventory.dataimport.handlers.matching.loaders.AuthorityLoader) MarcValueReaderImpl(org.folio.processing.matching.reader.MarcValueReaderImpl) StaticValueReaderImpl(org.folio.processing.matching.reader.StaticValueReaderImpl) ItemWriterFactory(org.folio.inventory.dataimport.ItemWriterFactory) MarcBibMatchedPostProcessingEventHandler(org.folio.inventory.dataimport.handlers.actions.MarcBibMatchedPostProcessingEventHandler) UpdateItemEventHandler(org.folio.inventory.dataimport.handlers.actions.UpdateItemEventHandler) MarcHoldingsReaderFactory(org.folio.processing.mapping.mapper.reader.record.marc.MarcHoldingsReaderFactory) Map(java.util.Map) EventManager(org.folio.processing.events.EventManager) ProfileSnapshotCache(org.folio.inventory.dataimport.cache.ProfileSnapshotCache) MatchInstanceEventHandler(org.folio.inventory.dataimport.handlers.matching.MatchInstanceEventHandler) PrecedingSucceedingTitlesHelper(org.folio.inventory.dataimport.handlers.actions.PrecedingSucceedingTitlesHelper) DataImportEventPayload(org.folio.DataImportEventPayload) ItemLoader(org.folio.inventory.dataimport.handlers.matching.loaders.ItemLoader) HoldingsIdStorageService(org.folio.inventory.services.HoldingsIdStorageService) Future(io.vertx.core.Future) String.format(java.lang.String.format) Storage(org.folio.inventory.storage.Storage) Logger(org.apache.logging.log4j.Logger) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) HoldingWriterFactory(org.folio.inventory.dataimport.HoldingWriterFactory) EventHandlingUtil(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil) MatchItemEventHandler(org.folio.inventory.dataimport.handlers.matching.MatchItemEventHandler) ReplaceInstanceEventHandler(org.folio.inventory.dataimport.handlers.actions.ReplaceInstanceEventHandler) InstanceIdStorageService(org.folio.inventory.services.InstanceIdStorageService) EntityIdStorageDaoImpl(org.folio.inventory.common.dao.EntityIdStorageDaoImpl) KafkaHeaderUtils(org.folio.kafka.KafkaHeaderUtils) DeleteAuthorityEventHandler(org.folio.inventory.dataimport.handlers.actions.DeleteAuthorityEventHandler) HttpClient(io.vertx.core.http.HttpClient) UpdateHoldingEventHandler(org.folio.inventory.dataimport.handlers.actions.UpdateHoldingEventHandler) Json(io.vertx.core.json.Json) Context(org.folio.inventory.common.Context) PostgresClientFactory(org.folio.inventory.common.dao.PostgresClientFactory) WebClient(io.vertx.ext.web.client.WebClient) MappingManager(org.folio.processing.mapping.MappingManager) CreateMarcHoldingsEventHandler(org.folio.inventory.dataimport.handlers.actions.CreateMarcHoldingsEventHandler) MarcBibModifiedPostProcessingEventHandler(org.folio.inventory.dataimport.handlers.actions.MarcBibModifiedPostProcessingEventHandler) CompletableFuture(java.util.concurrent.CompletableFuture) CreateItemEventHandler(org.folio.inventory.dataimport.handlers.actions.CreateItemEventHandler) DI_ERROR(org.folio.DataImportEventTypes.DI_ERROR) CreateAuthorityEventHandler(org.folio.inventory.dataimport.handlers.actions.CreateAuthorityEventHandler) InstanceWriterFactory(org.folio.inventory.dataimport.InstanceWriterFactory) MatchHoldingEventHandler(org.folio.inventory.dataimport.handlers.matching.MatchHoldingEventHandler) CreateHoldingEventHandler(org.folio.inventory.dataimport.handlers.actions.CreateHoldingEventHandler) MatchAuthorityEventHandler(org.folio.inventory.dataimport.handlers.matching.MatchAuthorityEventHandler) AuthorityIdStorageService(org.folio.inventory.services.AuthorityIdStorageService) Event(org.folio.rest.jaxrs.model.Event) MatchValueReaderFactory(org.folio.processing.matching.reader.MatchValueReaderFactory) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ItemIdStorageService(org.folio.inventory.services.ItemIdStorageService) UpdateAuthorityEventHandler(org.folio.inventory.dataimport.handlers.actions.UpdateAuthorityEventHandler) AsyncRecordHandler(org.folio.kafka.AsyncRecordHandler) CreateInstanceEventHandler(org.folio.inventory.dataimport.handlers.actions.CreateInstanceEventHandler) InstanceUpdateDelegate(org.folio.inventory.dataimport.handlers.actions.InstanceUpdateDelegate) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) HoldingLoader(org.folio.inventory.dataimport.handlers.matching.loaders.HoldingLoader) MarcBibReaderFactory(org.folio.processing.mapping.mapper.reader.record.marc.MarcBibReaderFactory) LogManager(org.apache.logging.log4j.LogManager) KafkaEventPublisher(org.folio.processing.events.services.publisher.KafkaEventPublisher) MatchValueLoaderFactory(org.folio.processing.matching.loader.MatchValueLoaderFactory) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) InstanceLoader(org.folio.inventory.dataimport.handlers.matching.loaders.InstanceLoader) KafkaConfig(org.folio.kafka.KafkaConfig) Event(org.folio.rest.jaxrs.model.Event) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) DataImportEventPayload(org.folio.DataImportEventPayload) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 22 with Context

use of org.folio.inventory.common.Context in project mod-inventory by folio-org.

the class MarcBibInstanceHridSetKafkaHandler method handle.

@Override
public Future<String> handle(KafkaConsumerRecord<String, String> record) {
    try {
        Promise<String> promise = Promise.promise();
        Event event = OBJECT_MAPPER.readValue(record.value(), Event.class);
        @SuppressWarnings("unchecked") HashMap<String, String> eventPayload = OBJECT_MAPPER.readValue(event.getEventPayload(), HashMap.class);
        Map<String, String> headersMap = KafkaHeaderUtils.kafkaHeadersToMap(record.headers());
        String recordId = headersMap.get(RECORD_ID_HEADER);
        String chunkId = headersMap.get(CHUNK_ID_HEADER);
        String jobExecutionId = eventPayload.get(JOB_EXECUTION_ID_HEADER);
        LOGGER.info("Event payload has been received with event type: {}, recordId: {} by jobExecution: {} and chunkId: {}", event.getEventType(), recordId, jobExecutionId, chunkId);
        if (isEmpty(eventPayload.get(MARC_KEY))) {
            String message = format("Event payload does not contain required data to update Instance with event type: '%s', recordId: '%s' by jobExecution: '%s' and chunkId: '%s'", event.getEventType(), recordId, jobExecutionId, chunkId);
            LOGGER.error(message);
            return Future.failedFuture(message);
        }
        Context context = EventHandlingUtil.constructContext(headersMap.get(OKAPI_TENANT_HEADER), headersMap.get(OKAPI_TOKEN_HEADER), headersMap.get(OKAPI_URL_HEADER));
        Record marcRecord = new JsonObject(eventPayload.get(MARC_KEY)).mapTo(Record.class);
        mappingMetadataCache.get(jobExecutionId, context).map(metadataOptional -> metadataOptional.orElseThrow(() -> new EventProcessingException(format(MAPPING_METADATA_NOT_FOUND_MSG, jobExecutionId)))).onSuccess(mappingMetadataDto -> ensureEventPayloadWithMappingMetadata(eventPayload, mappingMetadataDto)).compose(v -> instanceUpdateDelegate.handle(eventPayload, marcRecord, context)).onComplete(ar -> {
            if (ar.succeeded()) {
                eventPayload.remove(CURRENT_RETRY_NUMBER);
                promise.complete(record.key());
            } else {
                if (ar.cause() instanceof OptimisticLockingException) {
                    processOLError(record, promise, eventPayload, ar);
                } else {
                    eventPayload.remove(CURRENT_RETRY_NUMBER);
                    LOGGER.error("Failed to set MarcBib Hrid by jobExecutionId {}:{}", jobExecutionId, ar.cause());
                    promise.fail(ar.cause());
                }
            }
        });
        return promise.future();
    } catch (Exception e) {
        LOGGER.error(format("Failed to process data import kafka record from topic %s", record.topic()), e);
        return Future.failedFuture(e);
    }
}
Also used : Context(org.folio.inventory.common.Context) MappingMetadataDto(org.folio.MappingMetadataDto) Context(org.folio.inventory.common.Context) OKAPI_TENANT_HEADER(org.folio.rest.util.OkapiConnectionParams.OKAPI_TENANT_HEADER) HashMap(java.util.HashMap) OKAPI_URL_HEADER(org.folio.rest.util.OkapiConnectionParams.OKAPI_URL_HEADER) ObjectMapperTool(org.folio.dbschema.ObjectMapperTool) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) Event(org.folio.rest.jaxrs.model.Event) Record(org.folio.rest.jaxrs.model.Record) Promise(io.vertx.core.Promise) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) AsyncRecordHandler(org.folio.kafka.AsyncRecordHandler) Future(io.vertx.core.Future) String.format(java.lang.String.format) InstanceUpdateDelegate(org.folio.inventory.dataimport.handlers.actions.InstanceUpdateDelegate) Logger(org.apache.logging.log4j.Logger) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) EventHandlingUtil(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil) OKAPI_TOKEN_HEADER(org.folio.rest.util.OkapiConnectionParams.OKAPI_TOKEN_HEADER) Instance(org.folio.inventory.domain.instances.Instance) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) LogManager(org.apache.logging.log4j.LogManager) KafkaHeaderUtils(org.folio.kafka.KafkaHeaderUtils) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) 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) Event(org.folio.rest.jaxrs.model.Event) Record(org.folio.rest.jaxrs.model.Record) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 23 with Context

use of org.folio.inventory.common.Context in project mod-inventory by folio-org.

the class MarcHoldingsRecordHridSetKafkaHandler method handle.

@Override
public Future<String> handle(KafkaConsumerRecord<String, String> record) {
    try {
        Promise<String> promise = Promise.promise();
        Event event = OBJECT_MAPPER.readValue(record.value(), Event.class);
        @SuppressWarnings("unchecked") HashMap<String, String> eventPayload = OBJECT_MAPPER.readValue(event.getEventPayload(), HashMap.class);
        Map<String, String> headersMap = KafkaHeaderUtils.kafkaHeadersToMap(record.headers());
        String recordId = headersMap.get(RECORD_ID_HEADER);
        String chunkId = headersMap.get(CHUNK_ID_HEADER);
        String jobExecutionId = eventPayload.get(JOB_EXECUTION_ID_HEADER);
        LOGGER.info("Event payload has been received with event type: {}, recordId: {} by jobExecution: {} and chunkId: {}", event.getEventType(), recordId, jobExecutionId, chunkId);
        if (isEmpty(eventPayload.get(MARC_KEY))) {
            String message = String.format("Event payload does not contain required data to update Holdings with event type: '%s', recordId: '%s' by jobExecution: '%s' and chunkId: '%s'", event.getEventType(), recordId, jobExecutionId, chunkId);
            LOGGER.error(message);
            return Future.failedFuture(message);
        }
        Context context = constructContext(headersMap.get(OKAPI_TENANT_HEADER), headersMap.get(OKAPI_TOKEN_HEADER), headersMap.get(OKAPI_URL_HEADER));
        Record marcRecord = Json.decodeValue(eventPayload.get(MARC_KEY), Record.class);
        mappingMetadataCache.get(jobExecutionId, context).map(metadataOptional -> metadataOptional.orElseThrow(() -> new EventProcessingException(format(MAPPING_METADATA_NOT_FOUND_MSG, jobExecutionId)))).onSuccess(mappingMetadataDto -> ensureEventPayloadWithMappingMetadata(eventPayload, mappingMetadataDto)).compose(v -> holdingsRecordUpdateDelegate.handle(eventPayload, marcRecord, context)).onComplete(ar -> {
            if (ar.succeeded()) {
                eventPayload.remove(CURRENT_RETRY_NUMBER);
                promise.complete(record.key());
            } else {
                if (ar.cause() instanceof OptimisticLockingException) {
                    processOLError(record, promise, eventPayload, ar);
                } else {
                    eventPayload.remove(CURRENT_RETRY_NUMBER);
                    LOGGER.error("Failed to process data import event payload ", ar.cause());
                    promise.fail(ar.cause());
                }
            }
        });
        return promise.future();
    } catch (Exception e) {
        LOGGER.error(format("Failed to process data import kafka record from topic %s ", record.topic()), e);
        return Future.failedFuture(e);
    }
}
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) OKAPI_TENANT_HEADER(org.folio.rest.util.OkapiConnectionParams.OKAPI_TENANT_HEADER) HashMap(java.util.HashMap) OKAPI_URL_HEADER(org.folio.rest.util.OkapiConnectionParams.OKAPI_URL_HEADER) EventHandlingUtil.constructContext(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil.constructContext) HoldingsUpdateDelegate(org.folio.inventory.dataimport.handlers.actions.HoldingsUpdateDelegate) ObjectMapperTool(org.folio.dbschema.ObjectMapperTool) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) Event(org.folio.rest.jaxrs.model.Event) Record(org.folio.rest.jaxrs.model.Record) Promise(io.vertx.core.Promise) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) AsyncRecordHandler(org.folio.kafka.AsyncRecordHandler) Future(io.vertx.core.Future) HoldingsRecord(org.folio.HoldingsRecord) String.format(java.lang.String.format) Logger(org.apache.logging.log4j.Logger) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) OKAPI_TOKEN_HEADER(org.folio.rest.util.OkapiConnectionParams.OKAPI_TOKEN_HEADER) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) LogManager(org.apache.logging.log4j.LogManager) KafkaHeaderUtils(org.folio.kafka.KafkaHeaderUtils) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) Event(org.folio.rest.jaxrs.model.Event) Record(org.folio.rest.jaxrs.model.Record) HoldingsRecord(org.folio.HoldingsRecord) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 24 with Context

use of org.folio.inventory.common.Context in project mod-inventory by folio-org.

the class CreateItemEventHandler method handle.

@Override
public CompletableFuture<DataImportEventPayload> handle(DataImportEventPayload dataImportEventPayload) {
    CompletableFuture<DataImportEventPayload> future = new CompletableFuture<>();
    try {
        dataImportEventPayload.setEventType(DI_INVENTORY_ITEM_CREATED.value());
        HashMap<String, String> payloadContext = dataImportEventPayload.getContext();
        if (payloadContext == null || isBlank(payloadContext.get(EntityType.MARC_BIBLIOGRAPHIC.value()))) {
            LOG.error(PAYLOAD_HAS_NO_DATA_MSG);
            return CompletableFuture.failedFuture(new EventProcessingException(PAYLOAD_HAS_NO_DATA_MSG));
        }
        if (dataImportEventPayload.getCurrentNode().getChildSnapshotWrappers().isEmpty()) {
            LOG.error(ACTION_HAS_NO_MAPPING_MSG);
            return CompletableFuture.failedFuture(new EventProcessingException(ACTION_HAS_NO_MAPPING_MSG));
        }
        dataImportEventPayload.getEventsChain().add(dataImportEventPayload.getEventType());
        dataImportEventPayload.setCurrentNode(dataImportEventPayload.getCurrentNode().getChildSnapshotWrappers().get(0));
        dataImportEventPayload.getContext().put(ITEM.value(), new JsonObject().encode());
        String jobExecutionId = dataImportEventPayload.getJobExecutionId();
        String recordId = dataImportEventPayload.getContext().get(RECORD_ID_HEADER);
        String chunkId = dataImportEventPayload.getContext().get(CHUNK_ID_HEADER);
        Future<RecordToEntity> recordToItemFuture = idStorageService.store(recordId, UUID.randomUUID().toString(), dataImportEventPayload.getTenant());
        recordToItemFuture.onSuccess(res -> {
            String itemId = res.getEntityId();
            Context context = EventHandlingUtil.constructContext(dataImportEventPayload.getTenant(), dataImportEventPayload.getToken(), dataImportEventPayload.getOkapiUrl());
            ItemCollection itemCollection = storage.getItemCollection(context);
            mappingMetadataCache.get(jobExecutionId, context).map(parametersOptional -> parametersOptional.orElseThrow(() -> new EventProcessingException(format(MAPPING_METADATA_NOT_FOUND_MSG, jobExecutionId, recordId, chunkId)))).map(mappingMetadataDto -> {
                MappingParameters mappingParameters = Json.decodeValue(mappingMetadataDto.getMappingParams(), MappingParameters.class);
                MappingManager.map(dataImportEventPayload, new MappingContext().withMappingParameters(mappingParameters));
                return processMappingResult(dataImportEventPayload, itemId);
            }).compose(mappedItemJson -> {
                List<String> errors = validateItem(mappedItemJson, requiredFields);
                if (!errors.isEmpty()) {
                    String msg = format("Mapped Item is invalid: %s, by jobExecutionId: '%s' and recordId: '%s' and chunkId: '%s' ", errors, jobExecutionId, recordId, chunkId);
                    LOG.error(msg);
                    return Future.failedFuture(msg);
                }
                Item mappedItem = ItemUtil.jsonToItem(mappedItemJson);
                return isItemBarcodeUnique(mappedItemJson.getString("barcode"), itemCollection).compose(isUnique -> isUnique ? addItem(mappedItem, itemCollection) : Future.failedFuture(format("Barcode must be unique, %s is already assigned to another item", mappedItemJson.getString("barcode"))));
            }).onComplete(ar -> {
                if (ar.succeeded()) {
                    dataImportEventPayload.getContext().put(ITEM.value(), Json.encode(ar.result()));
                    future.complete(dataImportEventPayload);
                } else {
                    if (!(ar.cause() instanceof DuplicateEventException)) {
                        LOG.error("Error creating inventory Item by jobExecutionId: '{}' and recordId: '{}' and chunkId: '{}' ", jobExecutionId, recordId, chunkId, ar.cause());
                    }
                    future.completeExceptionally(ar.cause());
                }
            });
        }).onFailure(failure -> {
            LOG.error("Error creating inventory recordId and itemId relationship by jobExecutionId: '{}' and recordId: '{}' and chunkId: '{}' ", jobExecutionId, recordId, chunkId, failure);
            future.completeExceptionally(failure);
        });
    } catch (Exception e) {
        LOG.error("Error creating inventory Item", e);
        future.completeExceptionally(e);
    }
    return future;
}
Also used : ParsedRecordUtil(org.folio.inventory.dataimport.util.ParsedRecordUtil) CREATE(org.folio.ActionProfile.Action.CREATE) Arrays(java.util.Arrays) EventHandler(org.folio.processing.events.services.handler.EventHandler) ItemUtil(org.folio.inventory.support.ItemUtil) JsonHelper(org.folio.inventory.support.JsonHelper) ZonedDateTime(java.time.ZonedDateTime) Item(org.folio.inventory.domain.items.Item) ACTION_PROFILE(org.folio.rest.jaxrs.model.ProfileSnapshotWrapper.ContentType.ACTION_PROFILE) StringUtils(org.apache.commons.lang3.StringUtils) CirculationNote(org.folio.inventory.domain.items.CirculationNote) UNIQUE_ID_ERROR_MESSAGE(org.folio.inventory.dataimport.util.DataImportConstants.UNIQUE_ID_ERROR_MESSAGE) JsonObject(io.vertx.core.json.JsonObject) ItemCollection(org.folio.inventory.domain.items.ItemCollection) ZoneOffset(java.time.ZoneOffset) RecordToEntity(org.folio.inventory.domain.relationship.RecordToEntity) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) DuplicateEventException(org.folio.kafka.exception.DuplicateEventException) DataImportEventPayload(org.folio.DataImportEventPayload) UUID(java.util.UUID) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Storage(org.folio.inventory.storage.Storage) List(java.util.List) Logger(org.apache.logging.log4j.Logger) EventHandlingUtil(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil) ITEM(org.folio.ActionProfile.FolioRecord.ITEM) PagingParameters(org.folio.inventory.common.api.request.PagingParameters) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Json(io.vertx.core.json.Json) Context(org.folio.inventory.common.Context) MappingManager(org.folio.processing.mapping.MappingManager) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) DI_INVENTORY_ITEM_CREATED(org.folio.DataImportEventTypes.DI_INVENTORY_ITEM_CREATED) EntityType(org.folio.rest.jaxrs.model.EntityType) IdStorageService(org.folio.inventory.services.IdStorageService) ActionProfile(org.folio.ActionProfile) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) MappingContext(org.folio.processing.mapping.mapper.MappingContext) ItemStatusName(org.folio.inventory.domain.items.ItemStatusName) Record(org.folio.rest.jaxrs.model.Record) Promise(io.vertx.core.Promise) CqlHelper(org.folio.inventory.support.CqlHelper) StringUtils.isNotBlank(org.apache.commons.lang.StringUtils.isNotBlank) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) DateTimeFormatter(java.time.format.DateTimeFormatter) LogManager(org.apache.logging.log4j.LogManager) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) Context(org.folio.inventory.common.Context) MappingContext(org.folio.processing.mapping.mapper.MappingContext) DuplicateEventException(org.folio.kafka.exception.DuplicateEventException) JsonObject(io.vertx.core.json.JsonObject) ItemCollection(org.folio.inventory.domain.items.ItemCollection) RecordToEntity(org.folio.inventory.domain.relationship.RecordToEntity) DuplicateEventException(org.folio.kafka.exception.DuplicateEventException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) DataImportEventPayload(org.folio.DataImportEventPayload) MappingContext(org.folio.processing.mapping.mapper.MappingContext) Item(org.folio.inventory.domain.items.Item) CompletableFuture(java.util.concurrent.CompletableFuture) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 25 with Context

use of org.folio.inventory.common.Context in project mod-inventory by folio-org.

the class InstanceUpdateDelegate method handle.

public Future<Instance> handle(Map<String, String> eventPayload, Record marcRecord, Context context) {
    try {
        JsonObject mappingRules = new JsonObject(eventPayload.get(MAPPING_RULES_KEY));
        MappingParameters mappingParameters = new JsonObject(eventPayload.get(MAPPING_PARAMS_KEY)).mapTo(MappingParameters.class);
        JsonObject parsedRecord = retrieveParsedContent(marcRecord.getParsedRecord());
        String instanceId = marcRecord.getExternalIdsHolder().getInstanceId();
        RecordMapper<org.folio.Instance> recordMapper = RecordMapperBuilder.buildMapper(MARC_FORMAT);
        var mappedInstance = recordMapper.mapRecord(parsedRecord, mappingParameters, mappingRules);
        InstanceCollection instanceCollection = storage.getInstanceCollection(context);
        return getInstanceById(instanceId, instanceCollection).onSuccess(existingInstance -> fillVersion(existingInstance, eventPayload)).compose(existingInstance -> updateInstance(existingInstance, mappedInstance)).compose(updatedInstance -> updateInstanceInStorage(updatedInstance, instanceCollection));
    } catch (Exception e) {
        LOGGER.error("Error updating inventory instance", e);
        return Future.failedFuture(e);
    }
}
Also used : Context(org.folio.inventory.common.Context) Record(org.folio.rest.jaxrs.model.Record) Promise(io.vertx.core.Promise) HttpStatus(org.apache.http.HttpStatus) InstanceCollection(org.folio.inventory.domain.instances.InstanceCollection) InstanceUtil(org.folio.inventory.support.InstanceUtil) Future(io.vertx.core.Future) String.format(java.lang.String.format) RecordMapperBuilder(org.folio.processing.mapping.defaultmapper.RecordMapperBuilder) Storage(org.folio.inventory.storage.Storage) Logger(org.apache.logging.log4j.Logger) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) Instance(org.folio.inventory.domain.instances.Instance) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) LogManager(org.apache.logging.log4j.LogManager) ParsedRecord(org.folio.rest.jaxrs.model.ParsedRecord) RecordMapper(org.folio.processing.mapping.defaultmapper.RecordMapper) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) Instance(org.folio.inventory.domain.instances.Instance) InstanceCollection(org.folio.inventory.domain.instances.InstanceCollection) JsonObject(io.vertx.core.json.JsonObject) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException)

Aggregations

Context (org.folio.inventory.common.Context)30 JsonObject (io.vertx.core.json.JsonObject)25 Future (io.vertx.core.Future)20 String.format (java.lang.String.format)20 HashMap (java.util.HashMap)19 Json (io.vertx.core.json.Json)17 Storage (org.folio.inventory.storage.Storage)17 Promise (io.vertx.core.Promise)16 LogManager (org.apache.logging.log4j.LogManager)16 Logger (org.apache.logging.log4j.Logger)16 DataImportEventPayload (org.folio.DataImportEventPayload)16 MappingMetadataCache (org.folio.inventory.dataimport.cache.MappingMetadataCache)16 EventProcessingException (org.folio.processing.exceptions.EventProcessingException)16 Record (org.folio.rest.jaxrs.model.Record)15 CompletableFuture (java.util.concurrent.CompletableFuture)13 UUID (java.util.UUID)12 MappingParameters (org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters)11 List (java.util.List)10 MappingMetadataDto (org.folio.MappingMetadataDto)10 Instance (org.folio.inventory.domain.instances.Instance)10