Search in sources :

Example 16 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project presto by prestodb.

the class ResourceManagerProxy method performRequest.

public void performRequest(HttpServletRequest servletRequest, AsyncResponse asyncResponse, URI remoteUri) {
    try {
        BodyGenerator bodyGenerator = new InputStreamBodyGenerator(servletRequest.getInputStream());
        Request request = createRequest(servletRequest, servletRequest.getMethod(), remoteUri, bodyGenerator);
        ListenableFuture<ProxyResponse> proxyResponse = httpClient.executeAsync(request, new ResponseHandler());
        ListenableFuture<Response> future = transform(proxyResponse, this::toResponse, executor);
        setupAsyncResponse(servletRequest, asyncResponse, future);
    } catch (IOException e) {
        asyncResponse.resume(e);
    }
}
Also used : AsyncResponseHandler.bindAsyncResponse(com.facebook.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) BodyGenerator(com.facebook.airlift.http.client.BodyGenerator) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(com.facebook.airlift.http.client.Request) IOException(java.io.IOException)

Example 17 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project javaee7-samples by javaee-samples.

the class MyResource method getList.

// @Resource(name = "DefaultManagedThreadFactory")
// ManagedThreadFactory threadFactory;
@GET
public void getList(@Suspended final AsyncResponse ar) throws NamingException {
    ar.setTimeoutHandler(new TimeoutHandler() {

        @Override
        public void handleTimeout(AsyncResponse ar) {
            ar.resume("Operation timed out");
        }
    });
    ar.setTimeout(4000, TimeUnit.MILLISECONDS);
    ar.register(new MyCompletionCallback());
    ar.register(new MyConnectionCallback());
    ManagedThreadFactory threadFactory = (ManagedThreadFactory) new InitialContext().lookup("java:comp/DefaultManagedThreadFactory");
    Executors.newSingleThreadExecutor(threadFactory).submit(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                ar.resume(response[0]);
            } catch (InterruptedException ex) {
            }
        }
    });
}
Also used : TimeoutHandler(javax.ws.rs.container.TimeoutHandler) AsyncResponse(javax.ws.rs.container.AsyncResponse) InitialContext(javax.naming.InitialContext) ManagedThreadFactory(javax.enterprise.concurrent.ManagedThreadFactory) GET(javax.ws.rs.GET)

Example 18 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project bisq-api by mrosseel.

the class OfferResource method createOffer.

@ApiOperation(value = "Create offer", response = OfferDetail.class)
@POST
public void createOffer(@Suspended final AsyncResponse asyncResponse, @Valid OfferToCreate offer) {
    final OfferPayload.Direction direction = OfferPayload.Direction.valueOf(offer.direction);
    final PriceType priceType = PriceType.valueOf(offer.priceType);
    final Double marketPriceMargin = null == offer.percentageFromMarketPrice ? null : offer.percentageFromMarketPrice.doubleValue();
    final CompletableFuture<Offer> completableFuture = bisqProxy.offerMake(offer.fundUsingBisqWallet, offer.offerId, offer.accountId, direction, offer.amount, offer.minAmount, PriceType.PERCENTAGE.equals(priceType), marketPriceMargin, offer.marketPair, offer.fixedPrice, offer.buyerSecurityDeposit);
    completableFuture.thenApply(response -> asyncResponse.resume(new OfferDetail(response))).exceptionally(e -> {
        final Throwable cause = e.getCause();
        final Response.ResponseBuilder responseBuilder;
        if (cause instanceof ValidationException) {
            final int status = 422;
            responseBuilder = toValidationErrorResponse(cause, status);
        } else if (cause instanceof IncompatiblePaymentAccountException) {
            responseBuilder = toValidationErrorResponse(cause, 423);
        } else if (cause instanceof NoAcceptedArbitratorException) {
            responseBuilder = toValidationErrorResponse(cause, 424);
        } else if (cause instanceof PaymentAccountNotFoundException) {
            responseBuilder = toValidationErrorResponse(cause, 425);
        } else if (cause instanceof AmountTooHighException) {
            responseBuilder = toValidationErrorResponse(cause, 426);
        } else if (cause instanceof InsufficientMoneyException) {
            responseBuilder = toValidationErrorResponse(cause, 427);
        } else {
            final String message = cause.getMessage();
            responseBuilder = Response.status(500);
            if (null != message)
                responseBuilder.entity(new ValidationErrorMessage(ImmutableList.of(message)));
            log.error("Unable to create offer: " + Json.pretty(offer), cause);
        }
        return asyncResponse.resume(responseBuilder.build());
    });
}
Also used : network.bisq.api.model(network.bisq.api.model) Offer(bisq.core.offer.Offer) Trade(bisq.core.trade.Trade) AsyncResponse(javax.ws.rs.container.AsyncResponse) Json(io.swagger.util.Json) ResourceHelper.toValidationErrorResponse(network.bisq.api.service.ResourceHelper.toValidationErrorResponse) CompletableFuture(java.util.concurrent.CompletableFuture) Suspended(javax.ws.rs.container.Suspended) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) Slf4j(lombok.extern.slf4j.Slf4j) MediaType(javax.ws.rs.core.MediaType) Collectors.toList(java.util.stream.Collectors.toList) OfferPayload(bisq.core.offer.OfferPayload) ImmutableList(com.google.common.collect.ImmutableList) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) ValidationException(javax.validation.ValidationException) NotEmpty(org.hibernate.validator.constraints.NotEmpty) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage) Api(io.swagger.annotations.Api) Authorization(io.swagger.annotations.Authorization) network.bisq.api(network.bisq.api) NotFoundException(network.bisq.api.NotFoundException) ValidationException(javax.validation.ValidationException) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage) AsyncResponse(javax.ws.rs.container.AsyncResponse) ResourceHelper.toValidationErrorResponse(network.bisq.api.service.ResourceHelper.toValidationErrorResponse) Response(javax.ws.rs.core.Response) Offer(bisq.core.offer.Offer) OfferPayload(bisq.core.offer.OfferPayload) ApiOperation(io.swagger.annotations.ApiOperation)

Example 19 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project pravega by pravega.

the class StreamMetadataResourceImpl method listScopes.

/**
 * Implementation of listScopes REST API.
 *
 * @param securityContext     The security for API access.
 * @param asyncResponse       AsyncResponse provides means for asynchronous server side response processing.
 */
@Override
public void listScopes(final SecurityContext securityContext, final AsyncResponse asyncResponse) {
    long traceId = LoggerHelpers.traceEnter(log, "listScopes");
    long requestId = requestIdGenerator.nextLong();
    final Principal principal;
    final List<String> authHeader = getAuthorizationHeader();
    try {
        principal = restAuthHelper.authenticate(authHeader);
        restAuthHelper.authorize(authHeader, authorizationResource.ofScopes(), principal, READ);
    } catch (AuthException e) {
        log.warn(requestId, "Get scopes failed due to authentication failure.", e);
        asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
        LoggerHelpers.traceLeave(log, "listScopes", traceId);
        return;
    }
    controllerService.listScopes(requestId).thenApply(scopesList -> {
        ScopesList scopes = new ScopesList();
        scopesList.forEach(scope -> {
            try {
                if (restAuthHelper.isAuthorized(authHeader, authorizationResource.ofScope(scope), principal, READ)) {
                    scopes.addScopesItem(new ScopeProperty().scopeName(scope));
                }
            } catch (AuthException e) {
                log.warn(requestId, e.getMessage(), e);
            // Ignore. This exception occurs under abnormal circumstances and not to determine
            // whether the user is authorized. In case it does occur, we assume that the user
            // is unauthorized.
            }
        });
        return Response.status(Status.OK).entity(scopes).build();
    }).exceptionally(exception -> {
        log.warn(requestId, "listScopes failed with exception: ", exception);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }).thenApply(response -> {
        asyncResponse.resume(response);
        LoggerHelpers.traceLeave(log, "listScopes", traceId);
        return response;
    });
}
Also used : ApiV1(io.pravega.controller.server.rest.v1.ApiV1) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamsList(io.pravega.controller.server.rest.generated.model.StreamsList) SecurityContext(javax.ws.rs.core.SecurityContext) LoggerFactory(org.slf4j.LoggerFactory) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Random(java.util.Random) ReaderGroup(io.pravega.client.stream.ReaderGroup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ReaderGroupNotFoundException(io.pravega.client.stream.ReaderGroupNotFoundException) TagLogger(io.pravega.common.tracing.TagLogger) RESTAuthHelper(io.pravega.shared.rest.security.RESTAuthHelper) LocalController(io.pravega.controller.server.eventProcessor.LocalController) StoreException(io.pravega.controller.store.stream.StoreException) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) ReaderGroupProperty(io.pravega.controller.server.rest.generated.model.ReaderGroupProperty) INTERNAL_NAME_PREFIX(io.pravega.shared.NameUtils.INTERNAL_NAME_PREFIX) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) CreateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateStreamStatus) AuthorizationResource(io.pravega.shared.security.auth.AuthorizationResource) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) CreateScopeRequest(io.pravega.controller.server.rest.generated.model.CreateScopeRequest) Collectors(java.util.stream.Collectors) CreateStreamRequest(io.pravega.controller.server.rest.generated.model.CreateStreamRequest) READER_GROUP_STREAM_PREFIX(io.pravega.shared.NameUtils.READER_GROUP_STREAM_PREFIX) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) StreamState(io.pravega.controller.server.rest.generated.model.StreamState) Response(javax.ws.rs.core.Response) ScopesList(io.pravega.controller.server.rest.generated.model.ScopesList) Futures(io.pravega.common.concurrent.Futures) AuthException(io.pravega.auth.AuthException) CreateScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateScopeStatus) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) CompletableFuture(java.util.concurrent.CompletableFuture) UpdateStreamRequest(io.pravega.controller.server.rest.generated.model.UpdateStreamRequest) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) ScaleMetadata(io.pravega.controller.store.stream.ScaleMetadata) DeleteStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteStreamStatus) Status(javax.ws.rs.core.Response.Status) AuthorizationResourceImpl(io.pravega.shared.security.auth.AuthorizationResourceImpl) LoggerHelpers(io.pravega.common.LoggerHelpers) ControllerService(io.pravega.controller.server.ControllerService) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) ScopeProperty(io.pravega.controller.server.rest.generated.model.ScopeProperty) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ModelHelper(io.pravega.controller.server.rest.ModelHelper) ReaderGroupsList(io.pravega.controller.server.rest.generated.model.ReaderGroupsList) AuthHandlerManager(io.pravega.shared.rest.security.AuthHandlerManager) ReaderGroupsListReaderGroups(io.pravega.controller.server.rest.generated.model.ReaderGroupsListReaderGroups) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) ClientConfig(io.pravega.client.ClientConfig) ScopesList(io.pravega.controller.server.rest.generated.model.ScopesList) ScopeProperty(io.pravega.controller.server.rest.generated.model.ScopeProperty) AuthException(io.pravega.auth.AuthException) Principal(java.security.Principal)

Example 20 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project pravega by pravega.

the class StreamMetadataResourceImpl method updateStream.

/**
 * Implementation of updateStream REST API.
 *
 * @param scopeName           The scope name of stream.
 * @param streamName          The name of stream.
 * @param updateStreamRequest The object conforming to updateStreamConfig request json.
 * @param securityContext     The security for API access.
 * @param asyncResponse       AsyncResponse provides means for asynchronous server side response processing.
 */
@Override
public void updateStream(final String scopeName, final String streamName, final UpdateStreamRequest updateStreamRequest, final SecurityContext securityContext, final AsyncResponse asyncResponse) {
    long traceId = LoggerHelpers.traceEnter(log, "updateStream");
    long requestId = requestIdGenerator.nextLong();
    try {
        restAuthHelper.authenticateAuthorize(getAuthorizationHeader(), authorizationResource.ofStreamInScope(scopeName, streamName), READ_UPDATE);
    } catch (AuthException e) {
        log.warn(requestId, "Update stream for {} failed due to authentication failure.", scopeName + "/" + streamName);
        asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
        LoggerHelpers.traceLeave(log, "Update stream", traceId);
        return;
    }
    StreamConfiguration streamConfiguration = ModelHelper.getUpdateStreamConfig(updateStreamRequest);
    controllerService.updateStream(scopeName, streamName, streamConfiguration, requestId).thenApply(streamStatus -> {
        if (streamStatus.getStatus() == UpdateStreamStatus.Status.SUCCESS) {
            log.info(requestId, "Successfully updated stream config for: {}/{}", scopeName, streamName);
            return Response.status(Status.OK).entity(ModelHelper.encodeStreamResponse(scopeName, streamName, streamConfiguration)).build();
        } else if (streamStatus.getStatus() == UpdateStreamStatus.Status.STREAM_NOT_FOUND || streamStatus.getStatus() == UpdateStreamStatus.Status.SCOPE_NOT_FOUND) {
            log.warn(requestId, "Stream: {}/{} not found", scopeName, streamName);
            return Response.status(Status.NOT_FOUND).build();
        } else {
            log.warn(requestId, "updateStream failed for {}/{}", scopeName, streamName);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }).exceptionally(exception -> {
        log.warn(requestId, "updateStream for {}/{} failed with exception: {}", scopeName, streamName, exception);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }).thenApply(asyncResponse::resume).thenAccept(x -> LoggerHelpers.traceLeave(log, "updateStream", traceId));
}
Also used : ApiV1(io.pravega.controller.server.rest.v1.ApiV1) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamsList(io.pravega.controller.server.rest.generated.model.StreamsList) SecurityContext(javax.ws.rs.core.SecurityContext) LoggerFactory(org.slf4j.LoggerFactory) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Random(java.util.Random) ReaderGroup(io.pravega.client.stream.ReaderGroup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ReaderGroupNotFoundException(io.pravega.client.stream.ReaderGroupNotFoundException) TagLogger(io.pravega.common.tracing.TagLogger) RESTAuthHelper(io.pravega.shared.rest.security.RESTAuthHelper) LocalController(io.pravega.controller.server.eventProcessor.LocalController) StoreException(io.pravega.controller.store.stream.StoreException) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) ReaderGroupProperty(io.pravega.controller.server.rest.generated.model.ReaderGroupProperty) INTERNAL_NAME_PREFIX(io.pravega.shared.NameUtils.INTERNAL_NAME_PREFIX) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) CreateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateStreamStatus) AuthorizationResource(io.pravega.shared.security.auth.AuthorizationResource) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) CreateScopeRequest(io.pravega.controller.server.rest.generated.model.CreateScopeRequest) Collectors(java.util.stream.Collectors) CreateStreamRequest(io.pravega.controller.server.rest.generated.model.CreateStreamRequest) READER_GROUP_STREAM_PREFIX(io.pravega.shared.NameUtils.READER_GROUP_STREAM_PREFIX) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) StreamState(io.pravega.controller.server.rest.generated.model.StreamState) Response(javax.ws.rs.core.Response) ScopesList(io.pravega.controller.server.rest.generated.model.ScopesList) Futures(io.pravega.common.concurrent.Futures) AuthException(io.pravega.auth.AuthException) CreateScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateScopeStatus) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) CompletableFuture(java.util.concurrent.CompletableFuture) UpdateStreamRequest(io.pravega.controller.server.rest.generated.model.UpdateStreamRequest) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) ScaleMetadata(io.pravega.controller.store.stream.ScaleMetadata) DeleteStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteStreamStatus) Status(javax.ws.rs.core.Response.Status) AuthorizationResourceImpl(io.pravega.shared.security.auth.AuthorizationResourceImpl) LoggerHelpers(io.pravega.common.LoggerHelpers) ControllerService(io.pravega.controller.server.ControllerService) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) ScopeProperty(io.pravega.controller.server.rest.generated.model.ScopeProperty) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ModelHelper(io.pravega.controller.server.rest.ModelHelper) ReaderGroupsList(io.pravega.controller.server.rest.generated.model.ReaderGroupsList) AuthHandlerManager(io.pravega.shared.rest.security.AuthHandlerManager) ReaderGroupsListReaderGroups(io.pravega.controller.server.rest.generated.model.ReaderGroupsListReaderGroups) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) ClientConfig(io.pravega.client.ClientConfig) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) AuthException(io.pravega.auth.AuthException)

Aggregations

AsyncResponse (javax.ws.rs.container.AsyncResponse)58 Response (javax.ws.rs.core.Response)22 Test (org.junit.Test)15 CompletableFuture (java.util.concurrent.CompletableFuture)12 Path (javax.ws.rs.Path)11 List (java.util.List)10 GET (javax.ws.rs.GET)10 WebApplicationException (javax.ws.rs.WebApplicationException)10 Suspended (javax.ws.rs.container.Suspended)10 Status (javax.ws.rs.core.Response.Status)9 ArrayList (java.util.ArrayList)8 Context (javax.ws.rs.core.Context)8 MediaType (javax.ws.rs.core.MediaType)8 LoggerFactory (org.slf4j.LoggerFactory)8 AuthException (io.pravega.auth.AuthException)6 READ (io.pravega.auth.AuthHandler.Permissions.READ)6 READ_UPDATE (io.pravega.auth.AuthHandler.Permissions.READ_UPDATE)6 ClientConfig (io.pravega.client.ClientConfig)6 ReaderGroupManager (io.pravega.client.admin.ReaderGroupManager)6 ReaderGroupManagerImpl (io.pravega.client.admin.impl.ReaderGroupManagerImpl)6