Search in sources :

Example 96 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-orders by folio-org.

the class RestClient method post.

public <T> CompletableFuture<T> post(RequestEntry requestEntry, JsonObject recordData, PostResponseType postResponseType, Class<T> responseType, RequestContext requestContext) {
    CompletableFuture<T> future = new CompletableFuture<>();
    String endpoint = requestEntry.buildEndpoint();
    if (logger.isDebugEnabled()) {
        logger.debug("Sending 'POST {}' with body: {}", endpoint, recordData.encodePrettily());
    }
    HttpClientInterface client = getHttpClient(requestContext.getHeaders());
    try {
        client.request(HttpMethod.POST, recordData.toBuffer(), endpoint, requestContext.getHeaders()).thenApply(response -> {
            client.closeClient();
            if (postResponseType == PostResponseType.BODY) {
                JsonObject body = HelperUtils.verifyAndExtractBody(response);
                if (responseType == JsonObject.class) {
                    return body;
                }
                T responseEntity = body.mapTo(responseType);
                if (logger.isDebugEnabled()) {
                    logger.debug("'POST {}' request successfully processed. Record with '{}' id has been created", endpoint, body);
                }
                return responseEntity;
            } else if (postResponseType == PostResponseType.UUID) {
                return HelperUtils.verifyAndExtractRecordId(response);
            }
            return HelperUtils.verifyAndExtractBody(response);
        }).thenAccept(body -> {
            client.closeClient();
            if (logger.isDebugEnabled()) {
                logger.debug("'POST {}' request successfully processed. Record with '{}' id has been created", endpoint, body);
            }
            future.complete(responseType.cast(body));
        }).exceptionally(t -> {
            client.closeClient();
            logger.error("'POST {}' request failed. Request body: {}", endpoint, recordData.encodePrettily(), t.getCause());
            future.completeExceptionally(t.getCause());
            return null;
        });
    } catch (Exception e) {
        logger.error("'POST {}' request failed. Request body: {}", endpoint, recordData.encodePrettily(), e);
        client.closeClient();
        future.completeExceptionally(e);
    }
    return future;
}
Also used : HelperUtils.verifyResponse(org.folio.orders.utils.HelperUtils.verifyResponse) ERROR_MESSAGE(org.folio.rest.RestConstants.ERROR_MESSAGE) HelperUtils(org.folio.orders.utils.HelperUtils) RequestEntry(org.folio.rest.core.models.RequestEntry) OKAPI_HEADER_TENANT(org.folio.rest.RestVerticle.OKAPI_HEADER_TENANT) CompletableFuture(java.util.concurrent.CompletableFuture) StringUtils(org.apache.commons.lang3.StringUtils) TenantTool(org.folio.rest.tools.utils.TenantTool) HttpClientFactory(org.folio.rest.tools.client.HttpClientFactory) NOT_FOUND(org.folio.rest.RestConstants.NOT_FOUND) HelperUtils.verifyAndExtractBody(org.folio.orders.utils.HelperUtils.verifyAndExtractBody) Logger(org.apache.logging.log4j.Logger) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) RequestContext(org.folio.rest.core.models.RequestContext) JsonObject(io.vertx.core.json.JsonObject) Objects.nonNull(java.util.Objects.nonNull) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) RestConstants(org.folio.rest.RestConstants) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) OKAPI_HEADER_TENANT(org.folio.rest.RestVerticle.OKAPI_HEADER_TENANT) JsonObject(io.vertx.core.json.JsonObject)

Example 97 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-orders by folio-org.

the class RestClient method delete.

public CompletableFuture<Void> delete(RequestEntry requestEntry, boolean skipThrowNorFoundException, RequestContext requestContext) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    String endpoint = requestEntry.buildEndpoint();
    if (logger.isDebugEnabled()) {
        logger.debug(CALLING_ENDPOINT_MSG, HttpMethod.DELETE, endpoint);
    }
    HttpClientInterface client = getHttpClient(requestContext.getHeaders());
    setDefaultHeaders(client);
    try {
        client.request(HttpMethod.DELETE, endpoint, requestContext.getHeaders()).thenAccept(response -> {
            client.closeClient();
            int code = response.getCode();
            if (code == NOT_FOUND && skipThrowNorFoundException) {
                String errorMessage = (response.getError() != null) ? response.getError().getString(ERROR_MESSAGE) : StringUtils.EMPTY;
                logger.error("The GET {} operation completed with {} error: {}", endpoint, code, errorMessage);
                future.complete(null);
            } else {
                verifyResponse(response);
                future.complete(null);
            }
        }).exceptionally(t -> {
            client.closeClient();
            logger.error(String.format(EXCEPTION_CALLING_ENDPOINT_MSG, HttpMethod.DELETE, endpoint, requestContext), t);
            future.completeExceptionally(t.getCause());
            return null;
        });
    } catch (Exception e) {
        client.closeClient();
        logger.error(String.format(EXCEPTION_CALLING_ENDPOINT_MSG, HttpMethod.DELETE, endpoint, requestContext), e);
        future.completeExceptionally(e);
    }
    return future;
}
Also used : HelperUtils.verifyResponse(org.folio.orders.utils.HelperUtils.verifyResponse) ERROR_MESSAGE(org.folio.rest.RestConstants.ERROR_MESSAGE) HelperUtils(org.folio.orders.utils.HelperUtils) RequestEntry(org.folio.rest.core.models.RequestEntry) OKAPI_HEADER_TENANT(org.folio.rest.RestVerticle.OKAPI_HEADER_TENANT) CompletableFuture(java.util.concurrent.CompletableFuture) StringUtils(org.apache.commons.lang3.StringUtils) TenantTool(org.folio.rest.tools.utils.TenantTool) HttpClientFactory(org.folio.rest.tools.client.HttpClientFactory) NOT_FOUND(org.folio.rest.RestConstants.NOT_FOUND) HelperUtils.verifyAndExtractBody(org.folio.orders.utils.HelperUtils.verifyAndExtractBody) Logger(org.apache.logging.log4j.Logger) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) RequestContext(org.folio.rest.core.models.RequestContext) JsonObject(io.vertx.core.json.JsonObject) Objects.nonNull(java.util.Objects.nonNull) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) RestConstants(org.folio.rest.RestConstants) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface)

Example 98 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-orders by folio-org.

the class RestClient method put.

public <T> CompletableFuture<Void> put(RequestEntry requestEntry, T entity, RequestContext requestContext) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    String endpoint = requestEntry.buildEndpoint();
    JsonObject recordData = JsonObject.mapFrom(entity);
    if (logger.isDebugEnabled()) {
        logger.debug("Sending 'PUT {}' with body: {}", endpoint, recordData.encodePrettily());
    }
    HttpClientInterface client = getHttpClient(requestContext.getHeaders());
    setDefaultHeaders(client);
    try {
        client.request(HttpMethod.PUT, recordData.toBuffer(), endpoint, requestContext.getHeaders()).thenAccept(HelperUtils::verifyResponse).thenAccept(avoid -> {
            client.closeClient();
            future.complete(null);
        }).exceptionally(t -> {
            client.closeClient();
            future.completeExceptionally(t.getCause());
            logger.error("'PUT {}' request failed. Request body: {}", endpoint, recordData.encodePrettily(), t.getCause());
            return null;
        });
    } catch (Exception e) {
        logger.error("'PUT {}' request failed. Request body: {}", endpoint, recordData.encodePrettily(), e);
        client.closeClient();
        future.completeExceptionally(e);
    }
    return future;
}
Also used : HelperUtils.verifyResponse(org.folio.orders.utils.HelperUtils.verifyResponse) ERROR_MESSAGE(org.folio.rest.RestConstants.ERROR_MESSAGE) HelperUtils(org.folio.orders.utils.HelperUtils) RequestEntry(org.folio.rest.core.models.RequestEntry) OKAPI_HEADER_TENANT(org.folio.rest.RestVerticle.OKAPI_HEADER_TENANT) CompletableFuture(java.util.concurrent.CompletableFuture) StringUtils(org.apache.commons.lang3.StringUtils) TenantTool(org.folio.rest.tools.utils.TenantTool) HttpClientFactory(org.folio.rest.tools.client.HttpClientFactory) NOT_FOUND(org.folio.rest.RestConstants.NOT_FOUND) HelperUtils.verifyAndExtractBody(org.folio.orders.utils.HelperUtils.verifyAndExtractBody) Logger(org.apache.logging.log4j.Logger) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) RequestContext(org.folio.rest.core.models.RequestContext) JsonObject(io.vertx.core.json.JsonObject) Objects.nonNull(java.util.Objects.nonNull) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) RestConstants(org.folio.rest.RestConstants) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HelperUtils(org.folio.orders.utils.HelperUtils) JsonObject(io.vertx.core.json.JsonObject)

Example 99 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-orders by folio-org.

the class TransactionService method getTransactionsByIds.

public CompletableFuture<List<Transaction>> getTransactionsByIds(List<String> trIds, RequestContext requestContext) {
    return collectResultsOnSuccess(ofSubLists(new ArrayList<>(trIds), MAX_IDS_FOR_GET_RQ).map(ids -> getTransactionsChunksByIds(ids, requestContext)).toList()).thenApply(lists -> lists.stream().flatMap(Collection::stream).collect(Collectors.toList())).thenApply(trList -> {
        if (trList.size() != trIds.size()) {
            List<Parameter> parameters = new ArrayList<>();
            parameters.add(new Parameter().withKey("trIds").withValue(trIds.toString()));
            throw new HttpException(500, ERROR_RETRIEVING_TRANSACTION.toError().withParameters(parameters));
        }
        return trList;
    });
}
Also used : RestClient(org.folio.rest.core.RestClient) Collection(java.util.Collection) HttpException(org.folio.rest.core.exceptions.HttpException) RequestEntry(org.folio.rest.core.models.RequestEntry) HelperUtils.collectResultsOnSuccess(org.folio.orders.utils.HelperUtils.collectResultsOnSuccess) CompletableFuture(java.util.concurrent.CompletableFuture) FolioVertxCompletableFuture(org.folio.completablefuture.FolioVertxCompletableFuture) Transaction(org.folio.rest.acq.model.finance.Transaction) Collectors(java.util.stream.Collectors) TransactionCollection(org.folio.rest.acq.model.finance.TransactionCollection) StreamEx.ofSubLists(one.util.streamex.StreamEx.ofSubLists) ArrayList(java.util.ArrayList) MAX_IDS_FOR_GET_RQ(org.folio.rest.RestConstants.MAX_IDS_FOR_GET_RQ) ERROR_RETRIEVING_TRANSACTION(org.folio.rest.core.exceptions.ErrorCodes.ERROR_RETRIEVING_TRANSACTION) List(java.util.List) HelperUtils.convertIdsToCqlQuery(org.folio.orders.utils.HelperUtils.convertIdsToCqlQuery) RequestContext(org.folio.rest.core.models.RequestContext) Parameter(org.folio.rest.jaxrs.model.Parameter) ArrayList(java.util.ArrayList) Parameter(org.folio.rest.jaxrs.model.Parameter) HttpException(org.folio.rest.core.exceptions.HttpException)

Example 100 with RequestContext

use of org.folio.rest.core.models.RequestContext in project mod-orders by folio-org.

the class InventoryManager method fetchHoldingsByFundIds.

private CompletableFuture<List<JsonObject>> fetchHoldingsByFundIds(List<String> holdingIds, RequestContext requestContext) {
    String query = convertIdsToCqlQuery(holdingIds);
    RequestEntry requestEntry = new RequestEntry(INVENTORY_LOOKUP_ENDPOINTS.get(HOLDINGS_RECORDS)).withQuery(query).withOffset(0).withLimit(MAX_IDS_FOR_GET_RQ);
    return restClient.getAsJsonObject(requestEntry, requestContext).thenApply(jsonHoldings -> jsonHoldings.getJsonArray(HOLDINGS_RECORDS).stream().map(o -> ((JsonObject) o)).collect(toList())).thenApply(holdings -> {
        if (holdings.size() == holdingIds.size()) {
            return holdings;
        }
        List<Parameter> parameters = holdingIds.stream().filter(id -> holdings.stream().noneMatch(holding -> holding.getString(ID).equals(id))).map(id -> new Parameter().withValue(id).withKey("holdings")).collect(Collectors.toList());
        throw new HttpException(404, PARTIALLY_RETURNED_COLLECTION.toError().withParameters(parameters));
    });
}
Also used : CheckInPiece(org.folio.rest.jaxrs.model.CheckInPiece) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) HelperUtils.collectResultsOnSuccess(org.folio.orders.utils.HelperUtils.collectResultsOnSuccess) StringUtils(org.apache.commons.lang3.StringUtils) Context(io.vertx.core.Context) StreamEx.ofSubLists(one.util.streamex.StreamEx.ofSubLists) MISSING_INSTANCE_TYPE(org.folio.rest.core.exceptions.ErrorCodes.MISSING_INSTANCE_TYPE) Collections.singletonList(java.util.Collections.singletonList) ISBN_NOT_VALID(org.folio.rest.core.exceptions.ErrorCodes.ISBN_NOT_VALID) PoLineCommonUtil(org.folio.orders.utils.PoLineCommonUtil) HelperUtils.convertIdsToCqlQuery(org.folio.orders.utils.HelperUtils.convertIdsToCqlQuery) Map(java.util.Map) ListUtils(org.apache.commons.collections4.ListUtils) HOLDINGS_BY_ID_NOT_FOUND(org.folio.rest.core.exceptions.ErrorCodes.HOLDINGS_BY_ID_NOT_FOUND) PARTIALLY_RETURNED_COLLECTION(org.folio.rest.core.exceptions.ErrorCodes.PARTIALLY_RETURNED_COLLECTION) JsonObject(io.vertx.core.json.JsonObject) ORDER_CONFIG_MODULE_NAME(org.folio.orders.utils.HelperUtils.ORDER_CONFIG_MODULE_NAME) PieceStorageService(org.folio.service.pieces.PieceStorageService) LANG(org.folio.orders.utils.HelperUtils.LANG) Location(org.folio.rest.jaxrs.model.Location) Collection(java.util.Collection) ErrorCodes(org.folio.rest.core.exceptions.ErrorCodes) CompletionException(java.util.concurrent.CompletionException) HelperUtils.handleGetRequest(org.folio.orders.utils.HelperUtils.handleGetRequest) Collectors(java.util.stream.Collectors) TenantTool(org.folio.rest.tools.utils.TenantTool) Collectors.joining(java.util.stream.Collectors.joining) ConfigurationEntriesService(org.folio.service.configuration.ConfigurationEntriesService) Objects(java.util.Objects) List(java.util.List) CollectionUtils.isNotEmpty(org.apache.commons.collections4.CollectionUtils.isNotEmpty) Logger(org.apache.logging.log4j.Logger) Response(javax.ws.rs.core.Response) PieceItemPair(org.folio.models.PieceItemPair) CompositePoLine(org.folio.rest.jaxrs.model.CompositePoLine) StreamEx(one.util.streamex.StreamEx) HelperUtils.getFirstObjectFromResponse(org.folio.orders.utils.HelperUtils.getFirstObjectFromResponse) Optional(java.util.Optional) Parameter(org.folio.rest.jaxrs.model.Parameter) IntStreamEx(one.util.streamex.IntStreamEx) ITEM_CREATION_FAILED(org.folio.rest.core.exceptions.ErrorCodes.ITEM_CREATION_FAILED) MISSING_INSTANCE_STATUS(org.folio.rest.core.exceptions.ErrorCodes.MISSING_INSTANCE_STATUS) ELECTRONIC_RESOURCE(org.folio.rest.jaxrs.model.CompositePoLine.OrderFormat.ELECTRONIC_RESOURCE) RestClient(org.folio.rest.core.RestClient) HttpException(org.folio.rest.core.exceptions.HttpException) ProductId(org.folio.rest.jaxrs.model.ProductId) CompletableFuture(java.util.concurrent.CompletableFuture) FolioVertxCompletableFuture(org.folio.completablefuture.FolioVertxCompletableFuture) Contributor(org.folio.rest.jaxrs.model.Contributor) CollectionUtils(org.apache.commons.collections4.CollectionUtils) SharedData(io.vertx.core.shareddata.SharedData) ArrayList(java.util.ArrayList) MAX_IDS_FOR_GET_RQ(org.folio.rest.RestConstants.MAX_IDS_FOR_GET_RQ) MISSING_LOAN_TYPE(org.folio.rest.core.exceptions.ErrorCodes.MISSING_LOAN_TYPE) PoLineUpdateHolder(org.folio.models.PoLineUpdateHolder) Title(org.folio.rest.jaxrs.model.Title) HelperUtils.extractId(org.folio.orders.utils.HelperUtils.extractId) CompletableFuture.allOf(java.util.concurrent.CompletableFuture.allOf) RequestContext(org.folio.rest.core.models.RequestContext) ReceivedItem(org.folio.rest.jaxrs.model.ReceivedItem) HelperUtils.isProductIdsExist(org.folio.orders.utils.HelperUtils.isProductIdsExist) Piece(org.folio.rest.jaxrs.model.Piece) HelperUtils(org.folio.orders.utils.HelperUtils) MISSING_CONTRIBUTOR_NAME_TYPE(org.folio.rest.core.exceptions.ErrorCodes.MISSING_CONTRIBUTOR_NAME_TYPE) RequestEntry(org.folio.rest.core.models.RequestEntry) PostResponseType(org.folio.rest.core.PostResponseType) InventoryException(org.folio.rest.core.exceptions.InventoryException) NOT_FOUND(org.folio.rest.RestConstants.NOT_FOUND) Error(org.folio.rest.jaxrs.model.Error) JsonArray(io.vertx.core.json.JsonArray) Collectors.toList(java.util.stream.Collectors.toList) Lock(io.vertx.core.shareddata.Lock) HelperUtils.encodeQuery(org.folio.orders.utils.HelperUtils.encodeQuery) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) Parameter(org.folio.rest.jaxrs.model.Parameter) HttpException(org.folio.rest.core.exceptions.HttpException) RequestEntry(org.folio.rest.core.models.RequestEntry)

Aggregations

RequestContext (org.folio.rest.core.models.RequestContext)165 JsonObject (io.vertx.core.json.JsonObject)109 CompletableFuture (java.util.concurrent.CompletableFuture)105 Map (java.util.Map)100 List (java.util.List)92 Logger (org.apache.logging.log4j.Logger)85 LogManager (org.apache.logging.log4j.LogManager)83 Collections (java.util.Collections)73 ArrayList (java.util.ArrayList)72 Context (io.vertx.core.Context)71 CompletableFuture.completedFuture (java.util.concurrent.CompletableFuture.completedFuture)69 Collectors.toList (java.util.stream.Collectors.toList)68 BeforeEach (org.junit.jupiter.api.BeforeEach)63 CompositePoLine (org.folio.rest.jaxrs.model.CompositePoLine)56 Optional (java.util.Optional)53 StringUtils (org.apache.commons.lang3.StringUtils)53 Autowired (org.springframework.beans.factory.annotation.Autowired)51 Piece (org.folio.rest.jaxrs.model.Piece)49 Error (org.folio.rest.jaxrs.model.Error)46 RequestEntry (org.folio.rest.core.models.RequestEntry)45