Search in sources :

Example 26 with Context

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

the class PrecedingSucceedingTitlesHelper method deletePrecedingSucceedingTitles.

public Future<Void> deletePrecedingSucceedingTitles(Set<String> titlesIds, Context context) {
    CollectionResourceClient precedingSucceedingTitlesClient = createPrecedingSucceedingTitlesClient(context);
    CollectionResourceRepository precedingSucceedingTitlesRepository = new CollectionResourceRepository(precedingSucceedingTitlesClient);
    titlesIds.forEach(id -> precedingSucceedingTitlesRepository.delete(id).whenComplete((v, e) -> {
        if (e != null) {
            LOGGER.error("Error during deleting PrecedingSucceedingTitles with ids {}", id, e);
            LOGGER.info("Error during deleting PrecedingSucceedingTitles retry delete PrecedingSucceedingTitles");
            precedingSucceedingTitlesRepository.delete(id);
        }
    }));
    return Future.succeededFuture();
}
Also used : Context(org.folio.inventory.common.Context) MalformedURLException(java.net.MalformedURLException) WebClient(io.vertx.ext.web.client.WebClient) SneakyThrows(lombok.SneakyThrows) CollectionResourceRepository(org.folio.inventory.storage.external.CollectionResourceRepository) URL(java.net.URL) Promise(io.vertx.core.Promise) Set(java.util.Set) JsonArrayHelper(org.folio.inventory.support.JsonArrayHelper) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) UUID(java.util.UUID) Function(java.util.function.Function) Future(io.vertx.core.Future) String.format(java.lang.String.format) PrecedingSucceedingTitle(org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitle) PrecedingSucceedingTitleCollection(org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitleCollection) ArrayList(java.util.ArrayList) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) JsonObject(io.vertx.core.json.JsonObject) Instance(org.folio.inventory.domain.instances.Instance) LogManager(org.apache.logging.log4j.LogManager) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) CollectionResourceRepository(org.folio.inventory.storage.external.CollectionResourceRepository)

Example 27 with Context

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

the class PrecedingSucceedingTitlesHelper method createPrecedingSucceedingTitles.

public Future<Void> createPrecedingSucceedingTitles(Instance instance, Context context) {
    CollectionResourceClient precedingSucceedingTitlesClient = createPrecedingSucceedingTitlesClient(context);
    CollectionResourceRepository precedingSucceedingTitlesRepository = new CollectionResourceRepository(precedingSucceedingTitlesClient);
    List<PrecedingSucceedingTitle> precedingSucceedingTitles = new ArrayList<>();
    preparePrecedingTitles(instance, precedingSucceedingTitles);
    prepareSucceedingTitles(instance, precedingSucceedingTitles);
    precedingSucceedingTitles.forEach(title -> precedingSucceedingTitlesRepository.post(title).whenComplete((v, e) -> {
        if (e != null) {
            LOGGER.error("Error during creating PrecedingSucceedingTitle for instance {}", instance.getId(), e);
            LOGGER.info("Error during creating PrecedingSucceedingTitles retry creating new PrecedingSucceedingTitles");
            precedingSucceedingTitlesRepository.post(title);
        }
    }));
    return Future.succeededFuture();
}
Also used : Context(org.folio.inventory.common.Context) MalformedURLException(java.net.MalformedURLException) WebClient(io.vertx.ext.web.client.WebClient) SneakyThrows(lombok.SneakyThrows) CollectionResourceRepository(org.folio.inventory.storage.external.CollectionResourceRepository) URL(java.net.URL) Promise(io.vertx.core.Promise) Set(java.util.Set) JsonArrayHelper(org.folio.inventory.support.JsonArrayHelper) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) UUID(java.util.UUID) Function(java.util.function.Function) Future(io.vertx.core.Future) String.format(java.lang.String.format) PrecedingSucceedingTitle(org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitle) PrecedingSucceedingTitleCollection(org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitleCollection) ArrayList(java.util.ArrayList) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) JsonObject(io.vertx.core.json.JsonObject) Instance(org.folio.inventory.domain.instances.Instance) LogManager(org.apache.logging.log4j.LogManager) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) CollectionResourceRepository(org.folio.inventory.storage.external.CollectionResourceRepository) PrecedingSucceedingTitle(org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitle) ArrayList(java.util.ArrayList)

Example 28 with Context

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

the class UpdateItemEventHandler method handle.

@Override
public CompletableFuture<DataImportEventPayload> handle(DataImportEventPayload dataImportEventPayload) {
    CompletableFuture<DataImportEventPayload> future = new CompletableFuture<>();
    try {
        dataImportEventPayload.setEventType(DI_INVENTORY_ITEM_UPDATED.value());
        HashMap<String, String> payloadContext = dataImportEventPayload.getContext();
        if (isNull(payloadContext) || isBlank(payloadContext.get(MARC_BIBLIOGRAPHIC.value())) || isBlank(payloadContext.get(ITEM.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));
        }
        LOG.info("Processing UpdateItemEventHandler starting with jobExecutionId: {}.", dataImportEventPayload.getJobExecutionId());
        AtomicBoolean isProtectedStatusChanged = new AtomicBoolean();
        Context context = EventHandlingUtil.constructContext(dataImportEventPayload.getTenant(), dataImportEventPayload.getToken(), dataImportEventPayload.getOkapiUrl());
        String jobExecutionId = dataImportEventPayload.getJobExecutionId();
        String recordId = dataImportEventPayload.getContext().get(RECORD_ID_HEADER);
        String chunkId = dataImportEventPayload.getContext().get(CHUNK_ID_HEADER);
        mappingMetadataCache.get(jobExecutionId, context).map(parametersOptional -> parametersOptional.orElseThrow(() -> new EventProcessingException(format(MAPPING_METADATA_NOT_FOUND_MSG, jobExecutionId, recordId, chunkId)))).compose(mappingMetadataDto -> {
            String oldItemStatus = preparePayloadAndGetStatus(dataImportEventPayload, payloadContext, mappingMetadataDto);
            JsonObject mappedItemAsJson = new JsonObject(payloadContext.get(ITEM.value()));
            mappedItemAsJson = mappedItemAsJson.containsKey(ITEM_PATH_FIELD) ? mappedItemAsJson.getJsonObject(ITEM_PATH_FIELD) : mappedItemAsJson;
            List<String> errors = validateItem(mappedItemAsJson, requiredFields);
            if (!errors.isEmpty()) {
                String msg = format("Mapped Instance is invalid: %s, by jobExecutionId: '%s' and recordId: '%s' and chunkId: '%s' ", errors, jobExecutionId, recordId, chunkId);
                LOG.error(msg);
                return Future.failedFuture(msg);
            }
            String newItemStatus = mappedItemAsJson.getJsonObject(STATUS_KEY).getString("name");
            isProtectedStatusChanged.set(isProtectedStatusChanged(oldItemStatus, newItemStatus));
            if (isProtectedStatusChanged.get()) {
                mappedItemAsJson.getJsonObject(STATUS_KEY).put("name", oldItemStatus);
            }
            ItemCollection itemCollection = storage.getItemCollection(context);
            Item itemToUpdate = ItemUtil.jsonToItem(mappedItemAsJson);
            return verifyItemBarcodeUniqueness(itemToUpdate, itemCollection).compose(v -> updateItemAndRetryIfOLExists(itemToUpdate, itemCollection, dataImportEventPayload)).onSuccess(updatedItem -> {
                if (isProtectedStatusChanged.get()) {
                    String msg = String.format(STATUS_UPDATE_ERROR_MSG, oldItemStatus, newItemStatus);
                    LOG.warn(msg);
                    dataImportEventPayload.getContext().put(ITEM.value(), ItemUtil.mapToJson(updatedItem).encode());
                    future.completeExceptionally(new EventProcessingException(msg));
                } else {
                    addHoldingToPayloadIfNeeded(dataImportEventPayload, context, updatedItem).onComplete(item -> {
                        dataImportEventPayload.getContext().put(ITEM.value(), ItemUtil.mapToJson(updatedItem).encode());
                        future.complete(dataImportEventPayload);
                    });
                }
            });
        }).onFailure(e -> {
            LOG.error("Failed to update inventory Item by jobExecutionId: '{}' and recordId: '{}' and chunkId: '{}' ", jobExecutionId, recordId, chunkId, e);
            future.completeExceptionally(e);
        });
    } catch (Exception e) {
        LOG.error("Error updating inventory Item", e);
        future.completeExceptionally(e);
    }
    return future;
}
Also used : Context(org.folio.inventory.common.Context) MappingContext(org.folio.processing.mapping.mapper.MappingContext) Arrays(java.util.Arrays) MappingMetadataDto(org.folio.MappingMetadataDto) EventHandler(org.folio.processing.events.services.handler.EventHandler) ItemUtil(org.folio.inventory.support.ItemUtil) JsonHelper(org.folio.inventory.support.JsonHelper) ZonedDateTime(java.time.ZonedDateTime) HttpStatus(org.apache.http.HttpStatus) Failure(org.folio.inventory.common.domain.Failure) Item(org.folio.inventory.domain.items.Item) ACTION_PROFILE(org.folio.rest.jaxrs.model.ProfileSnapshotWrapper.ContentType.ACTION_PROFILE) StringUtils(org.apache.commons.lang3.StringUtils) ITEM(org.folio.rest.jaxrs.model.EntityType.ITEM) HoldingsRecordCollection(org.folio.inventory.domain.HoldingsRecordCollection) ProfileSnapshotWrapper(org.folio.rest.jaxrs.model.ProfileSnapshotWrapper) ObjectMapperTool(org.folio.dbschema.ObjectMapperTool) Objects.isNull(java.util.Objects.isNull) ItemCollection(org.folio.inventory.domain.items.ItemCollection) JsonObject(io.vertx.core.json.JsonObject) ZoneOffset(java.time.ZoneOffset) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) DataImportEventPayload(org.folio.DataImportEventPayload) Set(java.util.Set) UUID(java.util.UUID) Future(io.vertx.core.Future) 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) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PagingParameters(org.folio.inventory.common.api.request.PagingParameters) Context(org.folio.inventory.common.Context) Json(io.vertx.core.json.Json) MappingManager(org.folio.processing.mapping.MappingManager) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) DI_INVENTORY_ITEM_UPDATED(org.folio.DataImportEventTypes.DI_INVENTORY_ITEM_UPDATED) HashSet(java.util.HashSet) MARC_BIBLIOGRAPHIC(org.folio.rest.jaxrs.model.EntityType.MARC_BIBLIOGRAPHIC) ActionProfile(org.folio.ActionProfile) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) MappingContext(org.folio.processing.mapping.mapper.MappingContext) HOLDINGS(org.folio.rest.jaxrs.model.EntityType.HOLDINGS) ItemStatusName(org.folio.inventory.domain.items.ItemStatusName) CqlHelper(org.folio.inventory.support.CqlHelper) Promise(io.vertx.core.Promise) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) UPDATE(org.folio.ActionProfile.Action.UPDATE) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) STATUS_KEY(org.folio.inventory.domain.items.Item.STATUS_KEY) DateTimeFormatter(java.time.format.DateTimeFormatter) LogManager(org.apache.logging.log4j.LogManager) MappingMetadataCache(org.folio.inventory.dataimport.cache.MappingMetadataCache) JsonObject(io.vertx.core.json.JsonObject) ItemCollection(org.folio.inventory.domain.items.ItemCollection) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) DataImportEventPayload(org.folio.DataImportEventPayload) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Item(org.folio.inventory.domain.items.Item) CompletableFuture(java.util.concurrent.CompletableFuture) List(java.util.List) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 29 with Context

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

the class AuthorityUpdateDelegate method handle.

public Future<Authority> 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 authorityId = marcRecord.getExternalIdsHolder().getAuthorityId();
        RecordMapper<Authority> recordMapper = RecordMapperBuilder.buildMapper(MARC_FORMAT);
        var mappedAuthority = recordMapper.mapRecord(parsedRecord, mappingParameters, mappingRules);
        AuthorityRecordCollection authorityRecordCollection = storage.getAuthorityRecordCollection(context);
        return getAuthorityRecordById(authorityId, authorityRecordCollection).onSuccess(existingAuthorityRecord -> fillVersion(existingAuthorityRecord, eventPayload)).compose(existingAuthorityRecord -> mergeRecords(existingAuthorityRecord, mappedAuthority)).compose(updatedAuthorityRecord -> updateAuthorityRecord(updatedAuthorityRecord, authorityRecordCollection));
    } catch (Exception e) {
        LOGGER.error("Error updating Authority", e);
        return Future.failedFuture(e);
    }
}
Also used : Context(org.folio.inventory.common.Context) AuthorityRecordCollection(org.folio.inventory.domain.AuthorityRecordCollection) Record(org.folio.rest.jaxrs.model.Record) Promise(io.vertx.core.Promise) 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) Authority(org.folio.Authority) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) DataImportException(org.folio.inventory.dataimport.exceptions.DataImportException) 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) Authority(org.folio.Authority) JsonObject(io.vertx.core.json.JsonObject) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) AuthorityRecordCollection(org.folio.inventory.domain.AuthorityRecordCollection) DataImportException(org.folio.inventory.dataimport.exceptions.DataImportException)

Example 30 with Context

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

the class UpdateHoldingsQuickMarcEventHandlerTest method shouldProcessEvent.

@Test
public void shouldProcessEvent() {
    List<HoldingsType> holdings = new ArrayList<>();
    holdings.add(new HoldingsType().withName("testingnote$a").withId("fe19bae4-da28-472b-be90-d442e2428eadx"));
    MappingParameters mappingParameters = new MappingParameters();
    mappingParameters.withHoldingsTypes(holdings);
    HashMap<String, String> eventPayload = new HashMap<>();
    eventPayload.put("RECORD_TYPE", "MARC_HOLDING");
    eventPayload.put("MARC_HOLDING", record.encode());
    eventPayload.put("MAPPING_RULES", mappingRules.encode());
    eventPayload.put("MAPPING_PARAMS", Json.encode(mappingParameters));
    eventPayload.put("RELATED_RECORD_VERSION", HOLDINGS_VERSION.toString());
    Future<HoldingsRecord> future = updateHoldingsQuickMarcEventHandler.handle(eventPayload);
    HoldingsRecord updatedHoldings = future.result();
    Assert.assertNotNull(updatedHoldings);
    Assert.assertEquals(HOLDINGS_ID, updatedHoldings.getId());
    Assert.assertEquals(HOLDINGS_VERSION, updatedHoldings.getVersion());
    Assert.assertNull(updatedHoldings.getHoldingsTypeId());
    Assert.assertNotNull(updatedHoldings.getHoldingsStatements());
    Assert.assertEquals(21, updatedHoldings.getHoldingsStatements().size());
    Assert.assertNotNull(updatedHoldings.getNotes());
    Assert.assertEquals("testingnote$a ; testingnote$u ; testingnote$3 ; testingnote$5 ; testingnote$6 ; testingnote$8", updatedHoldings.getNotes().get(0).getNote());
    ArgumentCaptor<Context> argument = ArgumentCaptor.forClass(Context.class);
    verify(holdingsUpdateDelegate).handle(any(), any(), argument.capture());
    Assert.assertEquals("token", argument.getValue().getToken());
    Assert.assertEquals("dummy", argument.getValue().getTenantId());
    Assert.assertEquals("http://localhost", argument.getValue().getOkapiLocation());
}
Also used : Context(org.folio.inventory.common.Context) HoldingsRecord(org.folio.HoldingsRecord) HoldingsType(org.folio.HoldingsType) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MappingParameters(org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

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