Search in sources :

Example 1 with InstancesBatchResponse

use of org.folio.rest.jaxrs.model.InstancesBatchResponse in project mod-inventory-storage by folio-org.

the class InstanceStorageBatchAPI method postInstanceStorageBatchInstances.

@Validate
@Override
public void postInstanceStorageBatchInstances(Instances entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
    final String statusUpdatedDate = generateStatusUpdatedDate();
    for (Instance instance : entity.getInstances()) {
        instance.setStatusUpdatedDate(statusUpdatedDate);
    }
    vertxContext.runOnContext(v -> {
        try {
            PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders);
            final InstanceDomainEventPublisher instanceDomainEventPublisher = new InstanceDomainEventPublisher(vertxContext, okapiHeaders);
            MetadataUtil.populateMetadata(entity.getInstances(), okapiHeaders);
            executeInBatch(entity.getInstances(), (instances) -> saveInstances(instances, postgresClient)).onComplete(ar -> {
                InstancesBatchResponse response = constructResponse(ar.result());
                if (!response.getInstances().isEmpty()) {
                    instanceDomainEventPublisher.publishInstancesCreated(response.getInstances()).onSuccess(notUsed -> asyncResultHandler.handle(succeededFuture(respond201WithApplicationJson(response)))).onFailure(error -> {
                        log.error("Failed to send events for instances", error);
                        asyncResultHandler.handle(succeededFuture(respond500WithTextPlain(error.getMessage())));
                    });
                } else {
                    // return 500 response with the list of errors - not one Instance was created
                    log.error("Failed to create some of the Instances: " + response.getErrorMessages());
                    asyncResultHandler.handle(succeededFuture(respond500WithApplicationJson(response)));
                }
            });
        } catch (Exception e) {
            log.error("Failed to create Instances", e);
            asyncResultHandler.handle(succeededFuture(respond500WithTextPlain(e.getMessage())));
        }
    });
}
Also used : Future.succeededFuture(io.vertx.core.Future.succeededFuture) Instance(org.folio.rest.jaxrs.model.Instance) Function(java.util.function.Function) Context(io.vertx.core.Context) ArrayList(java.util.ArrayList) PostInstanceStorageBatchInstancesResponse.respond500WithApplicationJson(org.folio.rest.jaxrs.resource.InstanceStorageBatchInstances.PostInstanceStorageBatchInstancesResponse.respond500WithApplicationJson) MetadataUtil(org.folio.rest.tools.utils.MetadataUtil) CompositeFuture(io.vertx.core.CompositeFuture) Lists(com.google.common.collect.Lists) StatusUpdatedDateGenerator.generateStatusUpdatedDate(org.folio.rest.support.StatusUpdatedDateGenerator.generateStatusUpdatedDate) Instances(org.folio.rest.jaxrs.model.Instances) Map(java.util.Map) InstanceDomainEventPublisher(org.folio.services.domainevent.InstanceDomainEventPublisher) PostInstanceStorageBatchInstancesResponse.respond500WithTextPlain(org.folio.rest.jaxrs.resource.InstanceStorageBatchInstances.PostInstanceStorageBatchInstancesResponse.respond500WithTextPlain) AsyncResult(io.vertx.core.AsyncResult) PostInstanceStorageBatchInstancesResponse.respond201WithApplicationJson(org.folio.rest.jaxrs.resource.InstanceStorageBatchInstances.PostInstanceStorageBatchInstancesResponse.respond201WithApplicationJson) MODULE_SPECIFIC_ARGS(org.folio.rest.RestVerticle.MODULE_SPECIFIC_ARGS) Vertx(io.vertx.core.Vertx) Collectors(java.util.stream.Collectors) Validate(org.folio.rest.annotations.Validate) Future(io.vertx.core.Future) PostgresClient(org.folio.rest.persist.PostgresClient) HridManager(org.folio.rest.support.HridManager) InstanceStorageBatchInstances(org.folio.rest.jaxrs.resource.InstanceStorageBatchInstances) List(java.util.List) PgUtil(org.folio.rest.persist.PgUtil) Logger(org.apache.logging.log4j.Logger) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) Response(javax.ws.rs.core.Response) InstancesBatchResponse(org.folio.rest.jaxrs.model.InstancesBatchResponse) Handler(io.vertx.core.Handler) LogManager(org.apache.logging.log4j.LogManager) Instance(org.folio.rest.jaxrs.model.Instance) PostgresClient(org.folio.rest.persist.PostgresClient) InstancesBatchResponse(org.folio.rest.jaxrs.model.InstancesBatchResponse) InstanceDomainEventPublisher(org.folio.services.domainevent.InstanceDomainEventPublisher) Validate(org.folio.rest.annotations.Validate)

Example 2 with InstancesBatchResponse

use of org.folio.rest.jaxrs.model.InstancesBatchResponse in project mod-inventory-storage by folio-org.

the class InstanceStorageBatchAPI method constructResponse.

/**
 * Iterates through list of completed result futures and constructs InstancesBatchResponse
 *
 * @param saveFutures list of completed individual result futures
 * @return InstancesBatchResponse
 */
private InstancesBatchResponse constructResponse(List<Future> saveFutures) {
    InstancesBatchResponse response = new InstancesBatchResponse();
    saveFutures.forEach(save -> {
        if (save.failed()) {
            response.getErrorMessages().add(save.cause().getMessage());
        } else {
            response.getInstances().add((Instance) save.result());
        }
    });
    response.setTotalRecords(response.getInstances().size());
    return response;
}
Also used : InstancesBatchResponse(org.folio.rest.jaxrs.model.InstancesBatchResponse)

Example 3 with InstancesBatchResponse

use of org.folio.rest.jaxrs.model.InstancesBatchResponse in project mod-inventory-storage by folio-org.

the class InstanceStorageTest method cannotCreateACollectionOfInstancesWithHRIDFailure.

@Test
public void cannotCreateACollectionOfInstancesWithHRIDFailure() throws Exception {
    log.info("Starting cannotCreateACollectionOfInstancesWithHRIDFailure");
    final JsonArray instancesArray = new JsonArray();
    final int numberOfInstances = 2;
    final UUID[] uuids = new UUID[numberOfInstances];
    instancesArray.add(uprooted(uuids[0] = UUID.randomUUID()));
    final JsonObject t = temeraire(uuids[1] = UUID.randomUUID());
    t.put("hrid", "");
    instancesArray.add(t);
    final JsonObject instanceCollection = new JsonObject().put(INSTANCES_KEY, instancesArray).put(TOTAL_RECORDS_KEY, numberOfInstances);
    setInstanceSequence(99_999_999_999L);
    final CompletableFuture<Response> createCompleted = new CompletableFuture<>();
    client.post(instancesStorageBatchInstancesUrl(StringUtils.EMPTY), instanceCollection, TENANT_ID, json(createCompleted));
    final Response response = createCompleted.get(5, SECONDS);
    assertThat(response.getStatusCode(), is(201));
    final InstancesBatchResponse ibr = response.getJson().mapTo(InstancesBatchResponse.class);
    assertThat(ibr.getErrorMessages(), notNullValue());
    assertThat(ibr.getErrorMessages().get(0), isMaximumSequenceValueError("hrid_instances_seq"));
    log.info("Finished cannotCreateACollectionOfInstancesWithHRIDFailure");
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonErrorResponse(org.folio.rest.support.JsonErrorResponse) InstancesBatchResponse(org.folio.rest.jaxrs.model.InstancesBatchResponse) Response(org.folio.rest.support.Response) CompletableFuture(java.util.concurrent.CompletableFuture) JsonObject(io.vertx.core.json.JsonObject) UUID(java.util.UUID) InstancesBatchResponse(org.folio.rest.jaxrs.model.InstancesBatchResponse) Test(org.junit.Test)

Example 4 with InstancesBatchResponse

use of org.folio.rest.jaxrs.model.InstancesBatchResponse in project mod-inventory-storage by folio-org.

the class InstanceStorageTest method cannotCreateACollectionOfInstancesWithDuplicatedHRIDs.

@Test
public void cannotCreateACollectionOfInstancesWithDuplicatedHRIDs() throws Exception {
    log.info("Starting cannotCreateACollectionOfInstancesWithDuplicatedHRIDs");
    final JsonArray instancesArray = new JsonArray();
    final int numberOfInstances = 2;
    final UUID[] uuids = new UUID[numberOfInstances];
    instancesArray.add(uprooted(uuids[0] = UUID.randomUUID()));
    final JsonObject t = temeraire(uuids[1] = UUID.randomUUID());
    t.put("hrid", "in00000000001");
    instancesArray.add(t);
    final JsonObject instanceCollection = new JsonObject().put(INSTANCES_KEY, instancesArray).put(TOTAL_RECORDS_KEY, numberOfInstances);
    setInstanceSequence(1);
    final CompletableFuture<Response> createCompleted = new CompletableFuture<>();
    client.post(instancesStorageBatchInstancesUrl(StringUtils.EMPTY), instanceCollection, TENANT_ID, json(createCompleted));
    final Response response = createCompleted.get(5, SECONDS);
    assertThat(response.getStatusCode(), is(201));
    final InstancesBatchResponse ibr = response.getJson().mapTo(InstancesBatchResponse.class);
    assertThat(ibr.getErrorMessages(), hasSize(1));
    assertThat(ibr.getErrorMessages().get(0), isUniqueViolation("instance_hrid_idx_unique"));
    log.info("Finished cannotCreateACollectionOfInstancesWithDuplicatedHRIDs");
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonErrorResponse(org.folio.rest.support.JsonErrorResponse) InstancesBatchResponse(org.folio.rest.jaxrs.model.InstancesBatchResponse) Response(org.folio.rest.support.Response) CompletableFuture(java.util.concurrent.CompletableFuture) JsonObject(io.vertx.core.json.JsonObject) UUID(java.util.UUID) InstancesBatchResponse(org.folio.rest.jaxrs.model.InstancesBatchResponse) Test(org.junit.Test)

Aggregations

InstancesBatchResponse (org.folio.rest.jaxrs.model.InstancesBatchResponse)4 JsonArray (io.vertx.core.json.JsonArray)2 JsonObject (io.vertx.core.json.JsonObject)2 UUID (java.util.UUID)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 JsonErrorResponse (org.folio.rest.support.JsonErrorResponse)2 Response (org.folio.rest.support.Response)2 Test (org.junit.Test)2 Lists (com.google.common.collect.Lists)1 AsyncResult (io.vertx.core.AsyncResult)1 CompositeFuture (io.vertx.core.CompositeFuture)1 Context (io.vertx.core.Context)1 Future (io.vertx.core.Future)1 Future.succeededFuture (io.vertx.core.Future.succeededFuture)1 Handler (io.vertx.core.Handler)1 Vertx (io.vertx.core.Vertx)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1 Function (java.util.function.Function)1