Search in sources :

Example 31 with AsyncResponse

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

the class AsyncTimeoutResource method setTimeOut.

@POST
@Path("timeout")
public void setTimeOut(final Integer millis) throws InterruptedException {
    final AsyncResponse asyncResponse = queue.take();
    final boolean timeout1 = asyncResponse.setTimeout(millis, TimeUnit.MILLISECONDS);
    asyncResponse.setTimeoutHandler(new TimeoutHandler() {

        @Override
        public void handleTimeout(final AsyncResponse asyncResponse) {
            final boolean timeout2 = asyncResponse.setTimeout(millis, TimeUnit.MILLISECONDS);
            asyncResponse.setTimeoutHandler(new TimeoutHandler() {

                @Override
                public void handleTimeout(final AsyncResponse asyncResponse) {
                    asyncResponse.resume("timeout1=" + timeout1 + "_timeout2=" + timeout2 + "_handled");
                    asyncResponse.cancel();
                }
            });
        }
    });
}
Also used : TimeoutHandler(javax.ws.rs.container.TimeoutHandler) AsyncResponse(javax.ws.rs.container.AsyncResponse) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 32 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project pulsar by yahoo.

the class DestinationLookup method lookupDestinationAsync.

@GET
@Path("persistent/{property}/{cluster}/{namespace}/{dest}")
@Produces(MediaType.APPLICATION_JSON)
public void lookupDestinationAsync(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("dest") @Encoded String dest, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative, @Suspended AsyncResponse asyncResponse) {
    dest = Codec.decode(dest);
    DestinationName topic = DestinationName.get("persistent", property, cluster, namespace, dest);
    if (!pulsar().getBrokerService().getLookupRequestSemaphore().tryAcquire()) {
        log.warn("No broker was found available for topic {}", topic);
        asyncResponse.resume(new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
        return;
    }
    try {
        validateClusterOwnership(topic.getCluster());
        checkConnect(topic);
        validateReplicationSettingsOnNamespace(pulsar(), topic.getNamespaceObject());
    } catch (WebApplicationException we) {
        // Validation checks failed
        log.error("Validation check failed: {}", we.getMessage());
        completeLookupResponseExceptionally(asyncResponse, we);
        return;
    } catch (Throwable t) {
        // Validation checks failed with unknown error
        log.error("Validation check failed: {}", t.getMessage(), t);
        completeLookupResponseExceptionally(asyncResponse, new RestException(t));
        return;
    }
    CompletableFuture<LookupResult> lookupFuture = pulsar().getNamespaceService().getBrokerServiceUrlAsync(topic, authoritative);
    lookupFuture.thenAccept(result -> {
        if (result == null) {
            log.warn("No broker was found available for topic {}", topic);
            completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
            return;
        }
        if (result.isRedirect()) {
            boolean newAuthoritative = this.isLeaderBroker();
            URI redirect;
            try {
                String redirectUrl = isRequestHttps() ? result.getLookupData().getHttpUrlTls() : result.getLookupData().getHttpUrl();
                redirect = new URI(String.format("%s%s%s?authoritative=%s", redirectUrl, "/lookup/v2/destination/", topic.getLookupName(), newAuthoritative));
            } catch (URISyntaxException e) {
                log.error("Error in preparing redirect url for {}: {}", topic, e.getMessage(), e);
                completeLookupResponseExceptionally(asyncResponse, e);
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("Redirect lookup for topic {} to {}", topic, redirect);
            }
            completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.temporaryRedirect(redirect).build()));
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Lookup succeeded for topic {} -- broker: {}", topic, result.getLookupData());
            }
            completeLookupResponseSuccessfully(asyncResponse, result.getLookupData());
        }
    }).exceptionally(exception -> {
        log.warn("Failed to lookup broker for topic {}: {}", topic, exception.getMessage(), exception);
        completeLookupResponseExceptionally(asyncResponse, exception);
        return null;
    });
}
Also used : PathParam(javax.ws.rs.PathParam) RestException(com.yahoo.pulsar.broker.web.RestException) ServerError(com.yahoo.pulsar.common.api.proto.PulsarApi.ServerError) Encoded(javax.ws.rs.Encoded) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) LookupData(com.yahoo.pulsar.common.lookup.data.LookupData) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) ByteBuf(io.netty.buffer.ByteBuf) DefaultValue(javax.ws.rs.DefaultValue) PulsarService(com.yahoo.pulsar.broker.PulsarService) URI(java.net.URI) Codec(com.yahoo.pulsar.common.util.Codec) LookupType(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandLookupTopicResponse.LookupType) Status(javax.ws.rs.core.Response.Status) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) Logger(org.slf4j.Logger) AsyncResponse(javax.ws.rs.container.AsyncResponse) NoSwaggerDocumentation(com.yahoo.pulsar.broker.web.NoSwaggerDocumentation) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Commands.newLookupResponse(com.yahoo.pulsar.common.api.Commands.newLookupResponse) Suspended(javax.ws.rs.container.Suspended) PulsarWebResource(com.yahoo.pulsar.broker.web.PulsarWebResource) Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) WebApplicationException(javax.ws.rs.WebApplicationException) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) RestException(com.yahoo.pulsar.broker.web.RestException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 33 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project pulsar by yahoo.

the class HttpDestinationLookupv2Test method testNotEnoughLookupPermits.

@Test
public void testNotEnoughLookupPermits() throws Exception {
    BrokerService brokerService = pulsar.getBrokerService();
    doReturn(new Semaphore(0)).when(brokerService).getLookupRequestSemaphore();
    DestinationLookup destLookup = spy(new DestinationLookup());
    doReturn(false).when(destLookup).isRequestHttps();
    destLookup.setPulsar(pulsar);
    doReturn("null").when(destLookup).clientAppId();
    Field uriField = PulsarWebResource.class.getDeclaredField("uri");
    uriField.setAccessible(true);
    UriInfo uriInfo = mock(UriInfo.class);
    uriField.set(destLookup, uriInfo);
    URI uri = URI.create("http://localhost:8080/lookup/v2/destination/topic/myprop/usc/ns2/topic1");
    doReturn(uri).when(uriInfo).getRequestUri();
    doReturn(true).when(config).isAuthorizationEnabled();
    AsyncResponse asyncResponse1 = mock(AsyncResponse.class);
    destLookup.lookupDestinationAsync("myprop", "usc", "ns2", "topic1", false, asyncResponse1);
    ArgumentCaptor<Throwable> arg = ArgumentCaptor.forClass(Throwable.class);
    verify(asyncResponse1).resume(arg.capture());
    assertEquals(arg.getValue().getClass(), WebApplicationException.class);
    WebApplicationException wae = (WebApplicationException) arg.getValue();
    assertEquals(wae.getResponse().getStatus(), Status.SERVICE_UNAVAILABLE.getStatusCode());
}
Also used : Field(java.lang.reflect.Field) WebApplicationException(javax.ws.rs.WebApplicationException) DestinationLookup(com.yahoo.pulsar.broker.lookup.DestinationLookup) Semaphore(java.util.concurrent.Semaphore) AsyncResponse(javax.ws.rs.container.AsyncResponse) BrokerService(com.yahoo.pulsar.broker.service.BrokerService) URI(java.net.URI) UriInfo(javax.ws.rs.core.UriInfo) Test(org.testng.annotations.Test)

Example 34 with AsyncResponse

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

the class OfferResource method takeOffer.

@ApiOperation(value = "Take offer", response = TradeDetails.class)
@POST
@Path("/{id}/take")
public void takeOffer(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id, @Valid TakeOffer data) {
    // TODO how do we go about not blocking this REST thread?
    final CompletableFuture<Trade> completableFuture = bisqProxy.offerTake(id, data.paymentAccountId, data.amount, true);
    completableFuture.thenApply(trade -> asyncResponse.resume(new TradeDetails(trade))).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 InsufficientMoneyException) {
            responseBuilder = toValidationErrorResponse(cause, 427);
        } else if (cause instanceof NotFoundException) {
            responseBuilder = toValidationErrorResponse(cause, 404);
        } else {
            final String message = cause.getMessage();
            responseBuilder = Response.status(500);
            if (null != message)
                responseBuilder.entity(new ValidationErrorMessage(ImmutableList.of(message)));
            log.error("Unable to take offer: " + id + " " + Json.pretty(data), cause);
        }
        return asyncResponse.resume(responseBuilder.build());
    });
}
Also used : io.bisq.api(io.bisq.api) AsyncResponse(javax.ws.rs.container.AsyncResponse) Json(io.swagger.util.Json) CompletableFuture(java.util.concurrent.CompletableFuture) Suspended(javax.ws.rs.container.Suspended) Offer(io.bisq.core.offer.Offer) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) ResourceHelper(io.bisq.api.service.ResourceHelper) Slf4j(lombok.extern.slf4j.Slf4j) MediaType(javax.ws.rs.core.MediaType) Collectors.toList(java.util.stream.Collectors.toList) Trade(io.bisq.core.trade.Trade) ImmutableList(com.google.common.collect.ImmutableList) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) ValidationException(javax.validation.ValidationException) NotFoundException(io.bisq.api.NotFoundException) io.bisq.api.model(io.bisq.api.model) NotEmpty(org.hibernate.validator.constraints.NotEmpty) ResourceHelper.toValidationErrorResponse(io.bisq.api.service.ResourceHelper.toValidationErrorResponse) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage) Api(io.swagger.annotations.Api) ValidationException(javax.validation.ValidationException) NotFoundException(io.bisq.api.NotFoundException) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) ResourceHelper.toValidationErrorResponse(io.bisq.api.service.ResourceHelper.toValidationErrorResponse) Trade(io.bisq.core.trade.Trade) ApiOperation(io.swagger.annotations.ApiOperation)

Example 35 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project cxf by apache.

the class AsyncResource method takeAsyncResponse.

protected static AsyncResponse takeAsyncResponse(int stageId) {
    AsyncResponse asyncResponse = null;
    asyncResponse = ASYNC_RESPONSES[stageId].take();
    return asyncResponse;
}
Also used : AsyncResponse(javax.ws.rs.container.AsyncResponse)

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