Search in sources :

Example 11 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 12 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 13 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)

Aggregations

AsyncResponse (javax.ws.rs.container.AsyncResponse)13 Path (javax.ws.rs.Path)7 GET (javax.ws.rs.GET)5 POST (javax.ws.rs.POST)5 Produces (javax.ws.rs.Produces)4 Suspended (javax.ws.rs.container.Suspended)4 DestinationLookup (com.yahoo.pulsar.broker.lookup.DestinationLookup)3 Field (java.lang.reflect.Field)3 List (java.util.List)3 TimeoutHandler (javax.ws.rs.container.TimeoutHandler)3 UriInfo (javax.ws.rs.core.UriInfo)3 URI (java.net.URI)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 Response (javax.ws.rs.core.Response)2 Test (org.testng.annotations.Test)2 OutputBufferId (com.facebook.presto.OutputBuffers.OutputBufferId)1 PRESTO_PAGES (com.facebook.presto.PrestoMediaTypes.PRESTO_PAGES)1 Session (com.facebook.presto.Session)1 PRESTO_BUFFER_COMPLETE (com.facebook.presto.client.PrestoHeaders.PRESTO_BUFFER_COMPLETE)1 PRESTO_CURRENT_STATE (com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE)1