Search in sources :

Example 1 with BatchResult

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

the class ExternalStorageModuleInstanceCollection method addBatch.

@Override
public void addBatch(List<Instance> items, Consumer<Success<BatchResult<Instance>>> resultCallback, Consumer<Failure> failureCallback) {
    List<JsonObject> jsonList = items.stream().map(this::mapToRequest).collect(Collectors.toList());
    JsonObject batchRequest = new JsonObject().put("instances", new JsonArray(jsonList)).put("totalRecords", jsonList.size());
    final var futureResponse = new CompletableFuture<AsyncResult<HttpResponse<Buffer>>>();
    final HttpRequest<Buffer> request = withStandardHeaders(webClient.postAbs(batchAddress));
    request.sendJsonObject(batchRequest, futureResponse::complete);
    futureResponse.thenCompose(this::mapAsyncResultToCompletionStage).thenAccept(response -> {
        if (isBatchResponse(response)) {
            try {
                JsonObject batchResponse = response.getJson();
                JsonArray createdInstances = batchResponse.getJsonArray("instances");
                List<Instance> instancesList = new ArrayList<>();
                for (int i = 0; i < createdInstances.size(); i++) {
                    instancesList.add(mapFromJson(createdInstances.getJsonObject(i)));
                }
                BatchResult<Instance> batchResult = new BatchResult<>();
                batchResult.setBatchItems(instancesList);
                batchResult.setErrorMessages(batchResponse.getJsonArray("errorMessages").getList());
                resultCallback.accept(new Success<>(batchResult));
            } catch (Exception e) {
                LOGGER.error(e);
                failureCallback.accept(new Failure(e.getMessage(), response.getStatusCode()));
            }
        } else {
            failureCallback.accept(new Failure(response.getBody(), response.getStatusCode()));
        }
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Instance(org.folio.inventory.domain.instances.Instance) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) HttpResponse(io.vertx.ext.web.client.HttpResponse) BatchResult(org.folio.inventory.domain.BatchResult) JsonArray(io.vertx.core.json.JsonArray) CompletableFuture(java.util.concurrent.CompletableFuture) Failure(org.folio.inventory.common.domain.Failure)

Aggregations

Buffer (io.vertx.core.buffer.Buffer)1 JsonArray (io.vertx.core.json.JsonArray)1 JsonObject (io.vertx.core.json.JsonObject)1 HttpResponse (io.vertx.ext.web.client.HttpResponse)1 ArrayList (java.util.ArrayList)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 Failure (org.folio.inventory.common.domain.Failure)1 BatchResult (org.folio.inventory.domain.BatchResult)1 Instance (org.folio.inventory.domain.instances.Instance)1