Search in sources :

Example 26 with WebContext

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

the class ItemsByHoldingsRecordId method getBoundWithItems.

private void getBoundWithItems(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    String queryByHoldingsRecordId = context.getStringParameter("query", null);
    String relationsParam = context.getStringParameter("relations", null);
    if (queryByHoldingsRecordId == null || !queryByHoldingsRecordId.contains("holdingsRecordId")) {
        ClientErrorResponse.badRequest(routingContext.response(), "Items must be retrieved by 'holdingsRecordId' from this API. Query was: " + queryByHoldingsRecordId);
        return;
    }
    if (relationsParam != null) {
        if (!Arrays.asList(RELATION_PARAM_ONLY_BOUND_WITHS, RELATION_PARAM_ONLY_BOUND_WITHS_SKIP_DIRECTLY_LINKED_ITEM).contains(relationsParam)) {
            ClientErrorResponse.badRequest(routingContext.response(), "The only valid values of the request parameter 'relations' are: '" + RELATION_PARAM_ONLY_BOUND_WITHS + "' and '" + RELATION_PARAM_ONLY_BOUND_WITHS_SKIP_DIRECTLY_LINKED_ITEM + "'");
            return;
        }
    }
    String[] keyVal = queryByHoldingsRecordId.replaceAll("[()]", "").split("[=]{1,2}");
    if (keyVal.length != 2) {
        ClientErrorResponse.badRequest(routingContext.response(), "Items must be retrieved by 'holdingsRecordId' from this API: query=holdingsRecordId==[a UUID]. Query was: " + queryByHoldingsRecordId);
        return;
    }
    String holdingsRecordId = keyVal[1];
    CollectionResourceClient itemsClient = getCollectionResourceRepository(routingContext, context, ITEM_STORAGE_PATH);
    itemsClient.getMany("holdingsRecordId==" + holdingsRecordId, 1000, 0, response -> {
        List<String> holdingsRecordsItemIds = response.getJson().getJsonArray("items").stream().map(item -> ((JsonObject) item).getString("id")).collect(Collectors.toList());
        String queryByHoldingsRecordsItemIds = "";
        if (holdingsRecordsItemIds.size() > 0) {
            queryByHoldingsRecordsItemIds += " or " + buildQueryByItemIds(holdingsRecordsItemIds);
        }
        CollectionResourceClient boundWithPartsClient = getCollectionResourceRepository(routingContext, context, BOUND_WITH_PARTS_STORAGE_PATH);
        boundWithPartsClient.getMany(queryByHoldingsRecordId + queryByHoldingsRecordsItemIds, 1000, 0, response2 -> {
            joinAndRespondWithManyItems(routingContext, context, response2, holdingsRecordId, relationsParam);
        });
    });
}
Also used : WebContext(org.folio.inventory.common.WebContext) Arrays(java.util.Arrays) WebClient(io.vertx.ext.web.client.WebClient) FailureResponseConsumer(org.folio.inventory.support.http.server.FailureResponseConsumer) URL(java.net.URL) ClientErrorResponse(org.folio.inventory.support.http.server.ClientErrorResponse) Router(io.vertx.ext.web.Router) Response(org.folio.inventory.support.http.client.Response) RoutingContext(io.vertx.ext.web.RoutingContext) ArrayList(java.util.ArrayList) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) CqlHelper.buildQueryByIds(org.folio.inventory.support.CqlHelper.buildQueryByIds) JsonObject(io.vertx.core.json.JsonObject) MalformedURLException(java.net.MalformedURLException) MethodHandles(java.lang.invoke.MethodHandles) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Storage(org.folio.inventory.storage.Storage) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Logger(org.apache.logging.log4j.Logger) LogManager(org.apache.logging.log4j.LogManager) PagingParameters(org.folio.inventory.common.api.request.PagingParameters) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClient(io.vertx.core.http.HttpClient) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) WebContext(org.folio.inventory.common.WebContext) JsonObject(io.vertx.core.json.JsonObject)

Example 27 with WebContext

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

the class MoveApi method moveHoldings.

private void moveHoldings(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    JsonObject holdingsMoveJsonRequest = routingContext.getBodyAsJson();
    Optional<ValidationError> validationError = holdingsMoveHasRequiredFields(holdingsMoveJsonRequest);
    if (validationError.isPresent()) {
        unprocessableEntity(routingContext.response(), validationError.get());
        return;
    }
    String toInstanceId = holdingsMoveJsonRequest.getString(TO_INSTANCE_ID);
    List<String> holdingsRecordsIdsToUpdate = toListOfStrings(holdingsMoveJsonRequest.getJsonArray(HOLDINGS_RECORD_IDS));
    storage.getInstanceCollection(context).findById(toInstanceId).thenAccept(instance -> {
        if (instance == null) {
            JsonResponse.unprocessableEntity(routingContext.response(), String.format("Instance with id=%s not found", toInstanceId));
            return;
        }
        try {
            CollectionResourceClient holdingsStorageClient = createHoldingsStorageClient(createHttpClient(routingContext, context), context);
            MultipleRecordsFetchClient holdingsRecordFetchClient = createHoldingsRecordsFetchClient(holdingsStorageClient);
            holdingsRecordFetchClient.find(holdingsRecordsIdsToUpdate, this::fetchByIdCql).thenAccept(jsons -> {
                List<HoldingsRecord> holdingsRecordsToUpdate = updateInstanceIdForHoldings(toInstanceId, jsons);
                updateHoldings(routingContext, context, holdingsRecordsIdsToUpdate, holdingsRecordsToUpdate);
            }).exceptionally(e -> {
                ServerErrorResponse.internalError(routingContext.response(), e);
                return null;
            });
        } catch (Exception e) {
            ServerErrorResponse.internalError(routingContext.response(), e);
        }
    }).exceptionally(e -> {
        ServerErrorResponse.internalError(routingContext.response(), e);
        return null;
    });
}
Also used : WebContext(org.folio.inventory.common.WebContext) ItemUtil(org.folio.inventory.support.ItemUtil) WebClient(io.vertx.ext.web.client.WebClient) URL(java.net.URL) Router(io.vertx.ext.web.Router) CompletableFuture(java.util.concurrent.CompletableFuture) Item(org.folio.inventory.domain.items.Item) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) ArrayList(java.util.ArrayList) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) JsonResponse(org.folio.inventory.support.http.server.JsonResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) HoldingsRecordCollection(org.folio.inventory.domain.HoldingsRecordCollection) MultipleRecordsFetchClient(org.folio.inventory.storage.external.MultipleRecordsFetchClient) MoveValidator.holdingsMoveHasRequiredFields(org.folio.inventory.validation.MoveValidator.holdingsMoveHasRequiredFields) ItemCollection(org.folio.inventory.domain.items.ItemCollection) JsonObject(io.vertx.core.json.JsonObject) JsonArrayHelper.toListOfStrings(org.folio.inventory.support.JsonArrayHelper.toListOfStrings) MalformedURLException(java.net.MalformedURLException) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) JsonResponse.unprocessableEntity(org.folio.inventory.support.http.server.JsonResponse.unprocessableEntity) JsonResponse.success(org.folio.inventory.support.http.server.JsonResponse.success) Collectors(java.util.stream.Collectors) HoldingsRecord(org.folio.HoldingsRecord) Storage(org.folio.inventory.storage.Storage) Objects(java.util.Objects) Collectors.toList(java.util.stream.Collectors.toList) MoveValidator.itemsMoveHasRequiredFields(org.folio.inventory.validation.MoveValidator.itemsMoveHasRequiredFields) List(java.util.List) ListUtils(org.apache.commons.collections15.ListUtils) HttpServerResponse(io.vertx.core.http.HttpServerResponse) ValidationError(org.folio.inventory.support.http.server.ValidationError) Optional(java.util.Optional) CqlQuery(org.folio.inventory.storage.external.CqlQuery) HttpClient(io.vertx.core.http.HttpClient) HoldingsRecord(org.folio.HoldingsRecord) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) WebContext(org.folio.inventory.common.WebContext) JsonObject(io.vertx.core.json.JsonObject) MultipleRecordsFetchClient(org.folio.inventory.storage.external.MultipleRecordsFetchClient) ValidationError(org.folio.inventory.support.http.server.ValidationError) MalformedURLException(java.net.MalformedURLException)

Example 28 with WebContext

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

the class TenantApi method delete.

public void delete(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    deleteSchemaForTenant(context.getTenantId()).onSuccess(result -> routingContext.response().setStatusCode(HttpStatus.HTTP_NO_CONTENT.toInt()).end()).onFailure(fail -> routingContext.response().setStatusCode(HttpStatus.HTTP_INTERNAL_SERVER_ERROR.toInt()).end(fail.toString()));
}
Also used : WebContext(org.folio.inventory.common.WebContext) Connection(java.sql.Connection) Contexts(liquibase.Contexts) DatabaseFactory(liquibase.database.DatabaseFactory) Router(io.vertx.ext.web.Router) SingleConnectionProvider(org.folio.inventory.rest.impl.SingleConnectionProvider) RoutingContext(io.vertx.ext.web.RoutingContext) Database(liquibase.database.Database) Future(io.vertx.core.Future) Liquibase(liquibase.Liquibase) String.format(java.lang.String.format) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) Logger(org.apache.logging.log4j.Logger) PostgresConnectionOptions.convertToPsqlStandard(org.folio.inventory.common.dao.PostgresConnectionOptions.convertToPsqlStandard) HttpStatus(org.folio.HttpStatus) JdbcConnection(liquibase.database.jvm.JdbcConnection) LiquibaseException(liquibase.exception.LiquibaseException) LogManager(org.apache.logging.log4j.LogManager) WebContext(org.folio.inventory.common.WebContext)

Example 29 with WebContext

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

the class TenantApi method create.

public void create(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    initializeSchemaForTenant(context.getTenantId()).onSuccess(result -> routingContext.response().setStatusCode(HttpStatus.HTTP_NO_CONTENT.toInt()).end()).onFailure(fail -> routingContext.response().setStatusCode(HttpStatus.HTTP_INTERNAL_SERVER_ERROR.toInt()).end(fail.toString()));
}
Also used : WebContext(org.folio.inventory.common.WebContext) Connection(java.sql.Connection) Contexts(liquibase.Contexts) DatabaseFactory(liquibase.database.DatabaseFactory) Router(io.vertx.ext.web.Router) SingleConnectionProvider(org.folio.inventory.rest.impl.SingleConnectionProvider) RoutingContext(io.vertx.ext.web.RoutingContext) Database(liquibase.database.Database) Future(io.vertx.core.Future) Liquibase(liquibase.Liquibase) String.format(java.lang.String.format) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) Logger(org.apache.logging.log4j.Logger) PostgresConnectionOptions.convertToPsqlStandard(org.folio.inventory.common.dao.PostgresConnectionOptions.convertToPsqlStandard) HttpStatus(org.folio.HttpStatus) JdbcConnection(liquibase.database.jvm.JdbcConnection) LiquibaseException(liquibase.exception.LiquibaseException) LogManager(org.apache.logging.log4j.LogManager) WebContext(org.folio.inventory.common.WebContext)

Example 30 with WebContext

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

the class Instances method create.

private void create(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    JsonObject instanceRequest = routingContext.getBodyAsJson();
    if (StringUtils.isBlank(instanceRequest.getString(Instance.TITLE_KEY))) {
        ClientErrorResponse.badRequest(routingContext.response(), "Title must be provided for an instance");
        return;
    }
    Instance newInstance = Instance.fromJson(instanceRequest);
    completedFuture(newInstance).thenCompose(InstancePrecedingSucceedingTitleValidators::refuseWhenUnconnectedHasNoTitle).thenCompose(instance -> storage.getInstanceCollection(context).add(instance)).thenCompose(response -> {
        response.setParentInstances(newInstance.getParentInstances());
        response.setChildInstances(newInstance.getChildInstances());
        response.setPrecedingTitles(newInstance.getPrecedingTitles());
        response.setSucceedingTitles(newInstance.getSucceedingTitles());
        return updateRelatedRecords(routingContext, context, response).thenApply(notUsed -> response);
    }).thenAccept(response -> {
        try {
            URL url = context.absoluteUrl(format("%s/%s", INSTANCES_PATH, response.getId()));
            RedirectResponse.created(routingContext.response(), url.toString());
        } catch (MalformedURLException e) {
            log.warn(format("Failed to create self link for instance: %s", e.toString()));
        }
    }).exceptionally(doExceptionally(routingContext));
}
Also used : FailureResponseConsumer(org.folio.inventory.support.http.server.FailureResponseConsumer) URL(java.net.URL) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) Router(io.vertx.ext.web.Router) JsonArrayHelper(org.folio.inventory.support.JsonArrayHelper) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) StringUtils(org.apache.commons.lang3.StringUtils) EndpointFailureHandler.handleFailure(org.folio.inventory.support.EndpointFailureHandler.handleFailure) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) EndpointFailureHandler.doExceptionally(org.folio.inventory.support.EndpointFailureHandler.doExceptionally) SuccessResponse.noContent(org.folio.inventory.support.http.server.SuccessResponse.noContent) EndpointFailureHandler.getKnownException(org.folio.inventory.support.EndpointFailureHandler.getKnownException) RedirectResponse(org.folio.inventory.support.http.server.RedirectResponse) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Storage(org.folio.inventory.storage.Storage) InstancePrecedingSucceedingTitleValidators(org.folio.inventory.validation.InstancePrecedingSucceedingTitleValidators) Objects(java.util.Objects) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) InstanceRelationshipToChild(org.folio.inventory.domain.instances.InstanceRelationshipToChild) UnprocessableEntityException(org.folio.inventory.exceptions.UnprocessableEntityException) Instance(org.folio.inventory.domain.instances.Instance) CompletableFutures.failedFuture(org.folio.inventory.support.CompletableFutures.failedFuture) PagingParameters(org.folio.inventory.common.api.request.PagingParameters) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClient(io.vertx.core.http.HttpClient) WebContext(org.folio.inventory.common.WebContext) ClientErrorResponse(org.folio.inventory.support.http.server.ClientErrorResponse) InstancesValidators.refuseWhenHridChanged(org.folio.inventory.validation.InstancesValidators.refuseWhenHridChanged) InstancesValidators(org.folio.inventory.validation.InstancesValidators) Response(org.folio.inventory.support.http.client.Response) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) InstanceCollection(org.folio.inventory.domain.instances.InstanceCollection) MultipleRecords(org.folio.inventory.common.domain.MultipleRecords) ArrayList(java.util.ArrayList) JsonResponse(org.folio.inventory.support.http.server.JsonResponse) MultipleRecordsFetchClient(org.folio.inventory.storage.external.MultipleRecordsFetchClient) ObjectUtils(org.apache.commons.lang3.ObjectUtils) InstanceRelationship(org.folio.inventory.domain.instances.InstanceRelationship) SourceStorageRecordsClient(org.folio.rest.client.SourceStorageRecordsClient) MalformedURLException(java.net.MalformedURLException) COMMA(io.netty.util.internal.StringUtil.COMMA) InstanceRelationshipToParent(org.folio.inventory.domain.instances.InstanceRelationshipToParent) PrecedingSucceedingTitle(org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitle) JsonArray(io.vertx.core.json.JsonArray) InstanceRelationshipsService(org.folio.inventory.services.InstanceRelationshipsService) HttpStatus(org.folio.HttpStatus) Success(org.folio.inventory.common.domain.Success) CqlQuery(org.folio.inventory.storage.external.CqlQuery) Collections(java.util.Collections) InstancePrecedingSucceedingTitleValidators(org.folio.inventory.validation.InstancePrecedingSucceedingTitleValidators) MalformedURLException(java.net.MalformedURLException) WebContext(org.folio.inventory.common.WebContext) Instance(org.folio.inventory.domain.instances.Instance) JsonObject(io.vertx.core.json.JsonObject) URL(java.net.URL)

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