Search in sources :

Example 1 with HoldingCollection

use of org.folio.inventory.domain.HoldingCollection in project mod-inventory by folio-org.

the class MarcBibMatchedPostProcessingEventHandler method handle.

@Override
public CompletableFuture<DataImportEventPayload> handle(DataImportEventPayload dataImportEventPayload) {
    CompletableFuture<DataImportEventPayload> future = new CompletableFuture<>();
    try {
        HashMap<String, String> payloadContext = dataImportEventPayload.getContext();
        if (isNull(payloadContext)) {
            LOGGER.error(PAYLOAD_HAS_NO_DATA_MSG);
            future.completeExceptionally(new EventProcessingException(PAYLOAD_HAS_NO_DATA_MSG));
            return future;
        }
        if (isBlank(payloadContext.get(MATCHED_MARC_BIB_KEY))) {
            LOGGER.info(MATCHED_RECORD_NOT_EXISTS_MSG);
            future.complete(dataImportEventPayload);
            return future;
        }
        Record matchedRecord = new JsonObject(payloadContext.get(MATCHED_MARC_BIB_KEY)).mapTo(Record.class);
        String instanceId = ParsedRecordUtil.getAdditionalSubfieldValue(matchedRecord.getParsedRecord(), ParsedRecordUtil.AdditionalSubfields.I);
        Context context = EventHandlingUtil.constructContext(dataImportEventPayload.getTenant(), dataImportEventPayload.getToken(), dataImportEventPayload.getOkapiUrl());
        InstanceCollection instanceCollection = storage.getInstanceCollection(context);
        HoldingCollection holdingCollection = storage.getHoldingCollection(context);
        if (isBlank(instanceId)) {
            future.complete(dataImportEventPayload);
            return future;
        }
        instanceCollection.findById(instanceId).whenComplete((v, t) -> {
            if (t == null && v != null) {
                dataImportEventPayload.getContext().put(INSTANCE.value(), Json.encode(v));
                try {
                    holdingCollection.findByCql(format("instanceId=%s", v.getId()), PagingParameters.defaults(), findResult -> {
                        if (findResult.getResult() != null && findResult.getResult().totalRecords == 1) {
                            dataImportEventPayload.getContext().put(HOLDINGS.value(), Json.encode(findResult.getResult().records.get(0)));
                        }
                        future.complete(dataImportEventPayload);
                    }, failure -> {
                        LOGGER.error(ERROR_HOLDING_MSG + format(". StatusCode: %s. Message: %s", failure.getStatusCode(), failure.getReason()));
                        future.complete(dataImportEventPayload);
                    });
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error(ERROR_HOLDING_MSG, e);
                    future.complete(dataImportEventPayload);
                }
            } else {
                LOGGER.error(ERROR_INSTANCE_MSG, t);
                future.complete(dataImportEventPayload);
            }
        });
    } catch (Exception e) {
        LOGGER.error(ERROR_INSTANCE_MSG, e);
        future.completeExceptionally(e);
    }
    return future;
}
Also used : Context(org.folio.inventory.common.Context) InstanceCollection(org.folio.inventory.domain.instances.InstanceCollection) JsonObject(io.vertx.core.json.JsonObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EventProcessingException(org.folio.processing.exceptions.EventProcessingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DataImportEventPayload(org.folio.DataImportEventPayload) CompletableFuture(java.util.concurrent.CompletableFuture) HoldingCollection(org.folio.inventory.domain.HoldingCollection) Record(org.folio.rest.jaxrs.model.Record) EventProcessingException(org.folio.processing.exceptions.EventProcessingException)

Example 2 with HoldingCollection

use of org.folio.inventory.domain.HoldingCollection in project mod-inventory by folio-org.

the class IngestMessageProcessor method processRecordsMessage.

private void processRecordsMessage(Message<JsonObject> message, final EventBus eventBus) {
    final CollectAll<Item> allItems = new CollectAll<>();
    final CollectAll<Instance> allInstances = new CollectAll<>();
    final CollectAll<Holding> allHoldings = new CollectAll<>();
    final MessagingContext context = new MessagingContext(message.headers());
    final JsonObject body = message.body();
    IngestMessages.completed(context.getJobId(), context).send(eventBus);
    final List<JsonObject> records = JsonArrayHelper.toList(body.getJsonArray("records"));
    final JsonObject materialTypes = body.getJsonObject("materialTypes");
    final JsonObject loanTypes = body.getJsonObject("loanTypes");
    final JsonObject locations = body.getJsonObject("locations");
    final JsonObject instanceTypes = body.getJsonObject("instanceTypes");
    final JsonObject identifierTypes = body.getJsonObject("identifierTypes");
    final JsonObject contributorNameTypes = body.getJsonObject("contributorNameTypes");
    final InstanceCollection instanceCollection = storage.getInstanceCollection(context);
    final ItemCollection itemCollection = storage.getItemCollection(context);
    final HoldingCollection holdingCollection = storage.getHoldingCollection(context);
    records.stream().map(record -> {
        List<JsonObject> identifiersJson = JsonArrayHelper.toList(record.getJsonArray("identifiers"));
        List<Identifier> identifiers = identifiersJson.stream().map(identifier -> new Identifier(identifierTypes.getString("ISBN"), identifier.getString("value"))).collect(Collectors.toList());
        List<JsonObject> contributorsJson = JsonArrayHelper.toList(record.getJsonArray("contributors"));
        List<Contributor> contributors = contributorsJson.stream().map(contributor -> new Contributor(contributorNameTypes.getString("Personal name"), contributor.getString("name"), "", "", null)).collect(Collectors.toList());
        if (contributors.isEmpty()) {
            contributors.add(new Contributor(contributorNameTypes.getString("Personal name"), "Unknown contributor", "", "", null));
        }
        return new Instance(UUID.randomUUID().toString(), "3", null, "Local: MODS", record.getString(TITLE_PROPERTY), instanceTypes.getString("text")).setIdentifiers(identifiers).setContributors(contributors);
    }).forEach(instance -> instanceCollection.add(instance, allInstances.receive(), failure -> log.error("Instance processing failed: " + failure.getReason())));
    allInstances.collect(instances -> {
        instances.stream().map(instance -> new Holding(UUID.randomUUID().toString(), instance.getId(), locations.getString("Main Library"))).forEach(holding -> holdingCollection.add(holding, allHoldings.receive(), failure -> log.error("Holding processing failed: " + failure.getReason())));
        allHoldings.collect(holdings -> records.stream().map(record -> {
            // Will fail if have multiple instances with exactly the same title
            Optional<Instance> possibleInstance = instances.stream().filter(instance -> StringUtils.equals(instance.getTitle(), record.getString(TITLE_PROPERTY))).findFirst();
            String instanceId = possibleInstance.map(Instance::getId).orElse(null);
            Optional<Holding> possibleHolding = holdings.stream().filter(holding -> StringUtils.equals(instanceId, holding.instanceId)).findFirst();
            String holdingId = possibleHolding.map(holding -> holding.id).orElse(null);
            return new Item(null, null, holdingId, new Status(ItemStatusName.AVAILABLE), materialTypes.getString("Book") != null ? materialTypes.getString("Book") : materialTypes.getString("book"), loanTypes.getString("Can Circulate") != null ? loanTypes.getString("Can Circulate") : loanTypes.getString("Can circulate"), null).withBarcode(record.getString("barcode"));
        }).forEach(item -> itemCollection.add(item, allItems.receive(), failure -> log.error("Item processing failed: " + failure.getReason()))));
    });
    allItems.collect(items -> IngestMessages.completed(context.getJobId(), context).send(eventBus));
}
Also used : Identifier(org.folio.inventory.domain.instances.Identifier) JsonArrayHelper(org.folio.inventory.support.JsonArrayHelper) Item(org.folio.inventory.domain.items.Item) InstanceCollection(org.folio.inventory.domain.instances.InstanceCollection) StringUtils(org.apache.commons.lang3.StringUtils) EventBus(io.vertx.core.eventbus.EventBus) MessagingContext(org.folio.inventory.common.MessagingContext) ItemCollection(org.folio.inventory.domain.items.ItemCollection) JsonObject(io.vertx.core.json.JsonObject) IngestJobState(org.folio.inventory.resources.ingest.IngestJobState) ItemStatusName(org.folio.inventory.domain.items.ItemStatusName) MethodHandles(java.lang.invoke.MethodHandles) Message(io.vertx.core.eventbus.Message) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Holding(org.folio.inventory.domain.Holding) Status(org.folio.inventory.domain.items.Status) Storage(org.folio.inventory.storage.Storage) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CollectAll(org.folio.inventory.common.CollectAll) Optional(java.util.Optional) IngestJob(org.folio.inventory.resources.ingest.IngestJob) Instance(org.folio.inventory.domain.instances.Instance) Handler(io.vertx.core.Handler) LogManager(org.apache.logging.log4j.LogManager) HoldingCollection(org.folio.inventory.domain.HoldingCollection) Messages(org.folio.inventory.domain.Messages) Contributor(org.folio.inventory.domain.instances.Contributor) Status(org.folio.inventory.domain.items.Status) Instance(org.folio.inventory.domain.instances.Instance) InstanceCollection(org.folio.inventory.domain.instances.InstanceCollection) Holding(org.folio.inventory.domain.Holding) JsonObject(io.vertx.core.json.JsonObject) Contributor(org.folio.inventory.domain.instances.Contributor) ItemCollection(org.folio.inventory.domain.items.ItemCollection) Item(org.folio.inventory.domain.items.Item) CollectAll(org.folio.inventory.common.CollectAll) Identifier(org.folio.inventory.domain.instances.Identifier) HoldingCollection(org.folio.inventory.domain.HoldingCollection) MessagingContext(org.folio.inventory.common.MessagingContext) List(java.util.List)

Aggregations

JsonObject (io.vertx.core.json.JsonObject)2 HoldingCollection (org.folio.inventory.domain.HoldingCollection)2 InstanceCollection (org.folio.inventory.domain.instances.InstanceCollection)2 Handler (io.vertx.core.Handler)1 EventBus (io.vertx.core.eventbus.EventBus)1 Message (io.vertx.core.eventbus.Message)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MethodHandles (java.lang.invoke.MethodHandles)1 List (java.util.List)1 Optional (java.util.Optional)1 UUID (java.util.UUID)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 Collectors (java.util.stream.Collectors)1 StringUtils (org.apache.commons.lang3.StringUtils)1 LogManager (org.apache.logging.log4j.LogManager)1 Logger (org.apache.logging.log4j.Logger)1 DataImportEventPayload (org.folio.DataImportEventPayload)1 CollectAll (org.folio.inventory.common.CollectAll)1 Context (org.folio.inventory.common.Context)1 MessagingContext (org.folio.inventory.common.MessagingContext)1