Search in sources :

Example 21 with WebContext

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

the class Items method deleteAll.

private void deleteAll(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    storage.getItemCollection(context).empty(v -> SuccessResponse.noContent(routingContext.response()), FailureResponseConsumer.serverError(routingContext.response()));
}
Also used : WebContext(org.folio.inventory.common.WebContext)

Example 22 with WebContext

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

the class Items method update.

private void update(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    JsonObject itemRequest = routingContext.getBodyAsJson();
    Optional<ValidationError> validationError = itemHasCorrectStatus(itemRequest);
    if (validationError.isPresent()) {
        unprocessableEntity(routingContext.response(), validationError.get());
        return;
    }
    Item newItem = ItemUtil.jsonToItem(itemRequest);
    ItemCollection itemCollection = storage.getItemCollection(context);
    UserCollection userCollection = storage.getUserCollection(context);
    final String itemId = routingContext.request().getParam("id");
    final CompletableFuture<Success<Item>> getItemFuture = new CompletableFuture<>();
    itemCollection.findById(itemId, getItemFuture::complete, FailureResponseConsumer.serverError(routingContext.response()));
    getItemFuture.thenApply(Success::getResult).thenCompose(ItemsValidator::refuseWhenItemNotFound).thenCompose(oldItem -> hridChanged(oldItem, newItem)).thenCompose(oldItem -> claimedReturnedMarkedAsMissing(oldItem, newItem)).thenAccept(oldItem -> {
        if (hasSameBarcode(newItem, oldItem)) {
            findUserAndUpdateItem(routingContext, newItem, oldItem, userCollection, itemCollection);
        } else {
            try {
                checkForNonUniqueBarcode(routingContext, newItem, oldItem, itemCollection, userCollection);
            } catch (UnsupportedEncodingException e) {
                ServerErrorResponse.internalError(routingContext.response(), e.toString());
            }
        }
    }).exceptionally(doExceptionally(routingContext));
}
Also used : ItemUtil(org.folio.inventory.support.ItemUtil) URL(java.net.URL) FailureResponseConsumer(org.folio.inventory.support.http.server.FailureResponseConsumer) ZonedDateTime(java.time.ZonedDateTime) MoveItemIntoStatusService(org.folio.inventory.services.MoveItemIntoStatusService) JsonArrayHelper(org.folio.inventory.support.JsonArrayHelper) Router(io.vertx.ext.web.Router) FutureAssistance.allOf(org.folio.inventory.common.FutureAssistance.allOf) Item(org.folio.inventory.domain.items.Item) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) CirculationNote(org.folio.inventory.domain.items.CirculationNote) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) ItemCollection(org.folio.inventory.domain.items.ItemCollection) JsonObject(io.vertx.core.json.JsonObject) ZoneOffset(java.time.ZoneOffset) ForwardResponse(org.folio.inventory.support.http.server.ForwardResponse) EndpointFailureHandler.doExceptionally(org.folio.inventory.support.EndpointFailureHandler.doExceptionally) UserCollection(org.folio.inventory.domain.user.UserCollection) MethodHandles(java.lang.invoke.MethodHandles) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) Collectors(java.util.stream.Collectors) Storage(org.folio.inventory.storage.Storage) HTTP_OK(org.folio.HttpStatus.HTTP_OK) ItemsValidator(org.folio.inventory.validation.ItemsValidator) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) ValidationError(org.folio.inventory.support.http.server.ValidationError) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PagingParameters(org.folio.inventory.common.api.request.PagingParameters) HttpClient(io.vertx.core.http.HttpClient) CqlHelper.multipleRecordsCqlQuery(org.folio.inventory.support.CqlHelper.multipleRecordsCqlQuery) java.util(java.util) WebContext(org.folio.inventory.common.WebContext) ItemsValidator.claimedReturnedMarkedAsMissing(org.folio.inventory.validation.ItemsValidator.claimedReturnedMarkedAsMissing) WebClient(io.vertx.ext.web.client.WebClient) ClientErrorResponse(org.folio.inventory.support.http.server.ClientErrorResponse) ItemsValidator.hridChanged(org.folio.inventory.validation.ItemsValidator.hridChanged) ItemStatusValidator.itemHasCorrectStatus(org.folio.inventory.validation.ItemStatusValidator.itemHasCorrectStatus) CompletableFuture(java.util.concurrent.CompletableFuture) Response(org.folio.inventory.support.http.client.Response) Function(java.util.function.Function) MultipleRecords(org.folio.inventory.common.domain.MultipleRecords) JsonResponse(org.folio.inventory.support.http.server.JsonResponse) Clients(org.folio.inventory.storage.external.Clients) MalformedURLException(java.net.MalformedURLException) ItemStatusName(org.folio.inventory.domain.items.ItemStatusName) CqlHelper(org.folio.inventory.support.CqlHelper) User(org.folio.inventory.domain.user.User) JsonResponse.unprocessableEntity(org.folio.inventory.support.http.server.JsonResponse.unprocessableEntity) JsonArray(io.vertx.core.json.JsonArray) DateTimeFormatter(java.time.format.DateTimeFormatter) Success(org.folio.inventory.common.domain.Success) SuccessResponse(org.folio.inventory.support.http.server.SuccessResponse) LogManager(org.apache.logging.log4j.LogManager) WebContext(org.folio.inventory.common.WebContext) JsonObject(io.vertx.core.json.JsonObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ItemCollection(org.folio.inventory.domain.items.ItemCollection) Success(org.folio.inventory.common.domain.Success) ItemsValidator(org.folio.inventory.validation.ItemsValidator) Item(org.folio.inventory.domain.items.Item) CompletableFuture(java.util.concurrent.CompletableFuture) ValidationError(org.folio.inventory.support.http.server.ValidationError) UserCollection(org.folio.inventory.domain.user.UserCollection)

Example 23 with WebContext

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

the class Items method create.

private void create(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    JsonObject item = routingContext.getBodyAsJson();
    Optional<ValidationError> validationError = itemHasCorrectStatus(item);
    if (validationError.isPresent()) {
        unprocessableEntity(routingContext.response(), validationError.get());
        return;
    }
    Item newItem = ItemUtil.jsonToItem(item);
    ItemCollection itemCollection = storage.getItemCollection(context);
    UserCollection userCollection = storage.getUserCollection(context);
    if (newItem.getBarcode() != null) {
        try {
            itemCollection.findByCql(CqlHelper.barcodeIs(newItem.getBarcode()), PagingParameters.defaults(), findResult -> {
                if (findResult.getResult().records.isEmpty()) {
                    findUserAndAddItem(routingContext, context, newItem, userCollection, itemCollection);
                } else {
                    ClientErrorResponse.badRequest(routingContext.response(), String.format("Barcode must be unique, %s is already assigned to another item", newItem.getBarcode()));
                }
            }, FailureResponseConsumer.serverError(routingContext.response()));
        } catch (UnsupportedEncodingException e) {
            ServerErrorResponse.internalError(routingContext.response(), e.toString());
        }
    } else {
        findUserAndAddItem(routingContext, context, newItem, userCollection, itemCollection);
    }
}
Also used : Item(org.folio.inventory.domain.items.Item) WebContext(org.folio.inventory.common.WebContext) JsonObject(io.vertx.core.json.JsonObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ItemCollection(org.folio.inventory.domain.items.ItemCollection) ValidationError(org.folio.inventory.support.http.server.ValidationError) UserCollection(org.folio.inventory.domain.user.UserCollection)

Example 24 with WebContext

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

the class Items method getAll.

private void getAll(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    String search = context.getStringParameter("query", null);
    PagingParameters pagingParameters = PagingParameters.from(context);
    if (pagingParameters == null) {
        ClientErrorResponse.badRequest(routingContext.response(), "limit and offset must be numeric when supplied");
        return;
    }
    if (search == null) {
        storage.getItemCollection(context).findAll(pagingParameters, success -> respondWithManyItems(routingContext, context, success.getResult()), FailureResponseConsumer.serverError(routingContext.response()));
    } else {
        try {
            storage.getItemCollection(context).findByCql(search, pagingParameters, success -> respondWithManyItems(routingContext, context, success.getResult()), FailureResponseConsumer.serverError(routingContext.response()));
        } catch (UnsupportedEncodingException e) {
            ServerErrorResponse.internalError(routingContext.response(), e.toString());
        }
    }
}
Also used : PagingParameters(org.folio.inventory.common.api.request.PagingParameters) WebContext(org.folio.inventory.common.WebContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 25 with WebContext

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

the class Items method respondWithManyItems.

protected void respondWithManyItems(RoutingContext routingContext, WebContext context, MultipleRecords<Item> wrappedItems) {
    CollectionResourceClient holdingsClient;
    CollectionResourceClient instancesClient;
    CollectionResourceClient materialTypesClient;
    CollectionResourceClient loanTypesClient;
    CollectionResourceClient locationsClient;
    CollectionResourceClient boundWithPartsClient;
    try {
        OkapiHttpClient okapiClient = createHttpClient(routingContext, context);
        holdingsClient = createHoldingsClient(okapiClient, context);
        instancesClient = createInstancesClient(okapiClient, context);
        materialTypesClient = createMaterialTypesClient(okapiClient, context);
        loanTypesClient = createLoanTypesClient(okapiClient, context);
        locationsClient = createLocationsClient(okapiClient, context);
        boundWithPartsClient = createBoundWithPartsClient(okapiClient, context);
    } catch (MalformedURLException e) {
        invalidOkapiUrlResponse(routingContext, context);
        return;
    }
    ArrayList<CompletableFuture<Response>> allMaterialTypeFutures = new ArrayList<>();
    ArrayList<CompletableFuture<Response>> allLoanTypeFutures = new ArrayList<>();
    ArrayList<CompletableFuture<Response>> allLocationsFutures = new ArrayList<>();
    ArrayList<CompletableFuture<Response>> allFutures = new ArrayList<>();
    List<String> holdingsIds = wrappedItems.records.stream().map(Item::getHoldingId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
    CompletableFuture<Response> holdingsFetched = new CompletableFuture<>();
    String holdingsQuery = multipleRecordsCqlQuery(holdingsIds);
    holdingsClient.getMany(holdingsQuery, holdingsIds.size(), 0, holdingsFetched::complete);
    holdingsFetched.thenAccept(holdingsResponse -> {
        if (holdingsResponse.getStatusCode() != 200) {
            ServerErrorResponse.internalError(routingContext.response(), String.format("Holdings request (%s) failed %s: %s", holdingsQuery, holdingsResponse.getStatusCode(), holdingsResponse.getBody()));
        }
        final List<JsonObject> holdings = JsonArrayHelper.toList(holdingsResponse.getJson().getJsonArray("holdingsRecords"));
        List<String> instanceIds = holdings.stream().map(holding -> holding.getString("instanceId")).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        CompletableFuture<Response> instancesFetched = new CompletableFuture<>();
        String instancesQuery = multipleRecordsCqlQuery(instanceIds);
        instancesClient.getMany(instancesQuery, instanceIds.size(), 0, instancesFetched::complete);
        instancesFetched.thenAccept(instancesResponse -> {
            if (instancesResponse.getStatusCode() != 200) {
                ServerErrorResponse.internalError(routingContext.response(), String.format("Instances request (%s) failed %s: %s", instancesQuery, instancesResponse.getStatusCode(), instancesResponse.getBody()));
            }
            final List<JsonObject> instances = JsonArrayHelper.toList(instancesResponse.getJson().getJsonArray("instances"));
            List<String> materialTypeIds = wrappedItems.records.stream().map(Item::getMaterialTypeId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            materialTypeIds.forEach(id -> {
                CompletableFuture<Response> newFuture = new CompletableFuture<>();
                allFutures.add(newFuture);
                allMaterialTypeFutures.add(newFuture);
                materialTypesClient.get(id, newFuture::complete);
            });
            List<String> permanentLoanTypeIds = wrappedItems.records.stream().map(Item::getPermanentLoanTypeId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            List<String> temporaryLoanTypeIds = wrappedItems.records.stream().map(Item::getTemporaryLoanTypeId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            Stream.concat(permanentLoanTypeIds.stream(), temporaryLoanTypeIds.stream()).distinct().forEach(id -> {
                CompletableFuture<Response> newFuture = new CompletableFuture<>();
                allFutures.add(newFuture);
                allLoanTypeFutures.add(newFuture);
                loanTypesClient.get(id, newFuture::complete);
            });
            List<String> effectiveLocationIds = wrappedItems.records.stream().map(Item::getEffectiveLocationId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            List<String> permanentLocationIds = wrappedItems.records.stream().map(Item::getPermanentLocationId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            List<String> temporaryLocationIds = wrappedItems.records.stream().map(Item::getTemporaryLocationId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            Stream.concat(Stream.concat(permanentLocationIds.stream(), temporaryLocationIds.stream()), effectiveLocationIds.stream()).distinct().forEach(id -> {
                CompletableFuture<Response> newFuture = new CompletableFuture<>();
                allFutures.add(newFuture);
                allLocationsFutures.add(newFuture);
                locationsClient.get(id, newFuture::complete);
            });
            CompletableFuture<Response> boundWithPartsFuture = getBoundWithPartsForMultipleItemsFuture(wrappedItems, boundWithPartsClient);
            allFutures.add(boundWithPartsFuture);
            CompletableFuture<Void> allDoneFuture = allOf(allFutures);
            allDoneFuture.thenAccept(v -> {
                log.info("GET all items: all futures completed");
                try {
                    Map<String, JsonObject> foundMaterialTypes = allMaterialTypeFutures.stream().map(CompletableFuture::join).filter(response -> response.getStatusCode() == 200).map(Response::getJson).collect(Collectors.toMap(r -> r.getString("id"), r -> r));
                    Map<String, JsonObject> foundLoanTypes = allLoanTypeFutures.stream().map(CompletableFuture::join).filter(response -> response.getStatusCode() == 200).map(Response::getJson).collect(Collectors.toMap(r -> r.getString("id"), r -> r));
                    Map<String, JsonObject> foundLocations = allLocationsFutures.stream().map(CompletableFuture::join).filter(response -> response.getStatusCode() == 200).map(Response::getJson).collect(Collectors.toMap(r -> r.getString("id"), r -> r));
                    setBoundWithFlagsOnItems(wrappedItems, boundWithPartsFuture);
                    JsonResponse.success(routingContext.response(), new ItemRepresentation(RELATIVE_ITEMS_PATH).toJson(wrappedItems, holdings, instances, foundMaterialTypes, foundLoanTypes, foundLocations, context));
                } catch (Exception e) {
                    ServerErrorResponse.internalError(routingContext.response(), e.toString());
                }
            });
        });
    });
}
Also used : ItemUtil(org.folio.inventory.support.ItemUtil) URL(java.net.URL) FailureResponseConsumer(org.folio.inventory.support.http.server.FailureResponseConsumer) ZonedDateTime(java.time.ZonedDateTime) MoveItemIntoStatusService(org.folio.inventory.services.MoveItemIntoStatusService) JsonArrayHelper(org.folio.inventory.support.JsonArrayHelper) Router(io.vertx.ext.web.Router) FutureAssistance.allOf(org.folio.inventory.common.FutureAssistance.allOf) Item(org.folio.inventory.domain.items.Item) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) CirculationNote(org.folio.inventory.domain.items.CirculationNote) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) ItemCollection(org.folio.inventory.domain.items.ItemCollection) JsonObject(io.vertx.core.json.JsonObject) ZoneOffset(java.time.ZoneOffset) ForwardResponse(org.folio.inventory.support.http.server.ForwardResponse) EndpointFailureHandler.doExceptionally(org.folio.inventory.support.EndpointFailureHandler.doExceptionally) UserCollection(org.folio.inventory.domain.user.UserCollection) MethodHandles(java.lang.invoke.MethodHandles) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) Collectors(java.util.stream.Collectors) Storage(org.folio.inventory.storage.Storage) HTTP_OK(org.folio.HttpStatus.HTTP_OK) ItemsValidator(org.folio.inventory.validation.ItemsValidator) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) ValidationError(org.folio.inventory.support.http.server.ValidationError) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PagingParameters(org.folio.inventory.common.api.request.PagingParameters) HttpClient(io.vertx.core.http.HttpClient) CqlHelper.multipleRecordsCqlQuery(org.folio.inventory.support.CqlHelper.multipleRecordsCqlQuery) java.util(java.util) WebContext(org.folio.inventory.common.WebContext) ItemsValidator.claimedReturnedMarkedAsMissing(org.folio.inventory.validation.ItemsValidator.claimedReturnedMarkedAsMissing) WebClient(io.vertx.ext.web.client.WebClient) ClientErrorResponse(org.folio.inventory.support.http.server.ClientErrorResponse) ItemsValidator.hridChanged(org.folio.inventory.validation.ItemsValidator.hridChanged) ItemStatusValidator.itemHasCorrectStatus(org.folio.inventory.validation.ItemStatusValidator.itemHasCorrectStatus) CompletableFuture(java.util.concurrent.CompletableFuture) Response(org.folio.inventory.support.http.client.Response) Function(java.util.function.Function) MultipleRecords(org.folio.inventory.common.domain.MultipleRecords) JsonResponse(org.folio.inventory.support.http.server.JsonResponse) Clients(org.folio.inventory.storage.external.Clients) MalformedURLException(java.net.MalformedURLException) ItemStatusName(org.folio.inventory.domain.items.ItemStatusName) CqlHelper(org.folio.inventory.support.CqlHelper) User(org.folio.inventory.domain.user.User) JsonResponse.unprocessableEntity(org.folio.inventory.support.http.server.JsonResponse.unprocessableEntity) JsonArray(io.vertx.core.json.JsonArray) DateTimeFormatter(java.time.format.DateTimeFormatter) Success(org.folio.inventory.common.domain.Success) SuccessResponse(org.folio.inventory.support.http.server.SuccessResponse) LogManager(org.apache.logging.log4j.LogManager) MalformedURLException(java.net.MalformedURLException) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) JsonObject(io.vertx.core.json.JsonObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) ForwardResponse(org.folio.inventory.support.http.server.ForwardResponse) ClientErrorResponse(org.folio.inventory.support.http.server.ClientErrorResponse) Response(org.folio.inventory.support.http.client.Response) JsonResponse(org.folio.inventory.support.http.server.JsonResponse) SuccessResponse(org.folio.inventory.support.http.server.SuccessResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) CompletableFuture(java.util.concurrent.CompletableFuture)

Aggregations

WebContext (org.folio.inventory.common.WebContext)36 JsonObject (io.vertx.core.json.JsonObject)27 RoutingContext (io.vertx.ext.web.RoutingContext)20 Router (io.vertx.ext.web.Router)19 Collectors (java.util.stream.Collectors)17 JsonArray (io.vertx.core.json.JsonArray)16 ServerErrorResponse (org.folio.inventory.support.http.server.ServerErrorResponse)16 BodyHandler (io.vertx.ext.web.handler.BodyHandler)15 MalformedURLException (java.net.MalformedURLException)15 URL (java.net.URL)15 ArrayList (java.util.ArrayList)15 List (java.util.List)15 CollectionResourceClient (org.folio.inventory.storage.external.CollectionResourceClient)15 HttpClient (io.vertx.core.http.HttpClient)14 CompletableFuture (java.util.concurrent.CompletableFuture)14 Storage (org.folio.inventory.storage.Storage)14 JsonResponse (org.folio.inventory.support.http.server.JsonResponse)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 ClientErrorResponse (org.folio.inventory.support.http.server.ClientErrorResponse)12 PagingParameters (org.folio.inventory.common.api.request.PagingParameters)11