Search in sources :

Example 6 with AsyncResponse

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

the class HttpDestinationLookupv2Test method crossColoLookup.

@Test
public void crossColoLookup() throws Exception {
    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 asyncResponse = mock(AsyncResponse.class);
    destLookup.lookupDestinationAsync("myprop", "usc", "ns2", "topic1", false, asyncResponse);
    ArgumentCaptor<Throwable> arg = ArgumentCaptor.forClass(Throwable.class);
    verify(asyncResponse).resume(arg.capture());
    assertEquals(arg.getValue().getClass(), WebApplicationException.class);
    WebApplicationException wae = (WebApplicationException) arg.getValue();
    assertEquals(wae.getResponse().getStatus(), Status.TEMPORARY_REDIRECT.getStatusCode());
}
Also used : Field(java.lang.reflect.Field) WebApplicationException(javax.ws.rs.WebApplicationException) DestinationLookup(com.yahoo.pulsar.broker.lookup.DestinationLookup) AsyncResponse(javax.ws.rs.container.AsyncResponse) URI(java.net.URI) UriInfo(javax.ws.rs.core.UriInfo) Test(org.testng.annotations.Test)

Example 7 with AsyncResponse

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

the class Jersey2812ITCase method asyncSuspendedResourceDoesNotGetStuck.

/**
     * Tests whether the server-side thread that is processing a http request to the servlet-filter-based Jersey setup ends up
     * stuck or returned back to the pool of available threads.
     * <p/>
     * This test prevents a regression reported in JERSEY-2812.
     * <p/>
     * When the {@link javax.ws.rs.container.AsyncResponse} was left intact in the RESTful resource (as implemented in {@link
     * TestWaitResource#waitForEvent(AsyncResponse, HttpServletRequest, String)}), the server-side Jersey thread ended up in
     * {@link org.glassfish.jersey.servlet.internal.ResponseWriter#getResponseContext()} blocked because of the resolution of http
     * response status from {@link org.glassfish.jersey.servlet.ServletContainer#doFilter(HttpServletRequest, HttpServletResponse,
     * FilterChain, String, String, String)}
     * <p/>
     * This test uses a separate thread to call {@code /async/wait/{uuid}} resource which blocks until the {@code
     * /async/release/{uuid}} is called. In the meantime the JUnit thread calls {@code /async/await/{uuid}} to discover whether
     * the server-side thread processing the request to {@code /async/await/{uuid}/started} did start processing of the request.
     * Consecutively, the JUnit thread calls {@code /async/await/{uuid}/finished} with a timeout {@code #WAIT_TIMEOUT} to discover
     * whether the server-side thread got stuck (which is what JERSEY-2812 reported) or not.
     *
     * @throws Exception
     */
@Test
public void asyncSuspendedResourceDoesNotGetStuck() throws Exception {
    // [1] wait for the /async/wait request to be processed
    final Response startResponse = target("/asyncTest/async/await").path(uuid).path("started").queryParam("millis", WAIT_TIMEOUT).request().get();
    assertTrue("The server-side thread handling the request to /async/wait didn't start in timely fashion. " + "This error indicates this test is not executed / designed properly rather than a regression in " + "JERSEY-2812 fix.", startResponse.readEntity(Boolean.class));
    // [2] wait for the /async/wait request to finish
    final Response finishResponse = target("/asyncTest/async/await").path(uuid).path("finished").queryParam("millis", WAIT_TIMEOUT).request().get();
    assertTrue("The thread processing the /async/wait request did not respond in timely fashion. " + "Memory leak / thread got stuck detected!", finishResponse.readEntity(Boolean.class));
    // [3] release the blocked http call to /async/wait
    final String releaseResponse = target("/asyncTest/async/release").path(uuid).request().post(null, String.class);
    assertEquals("RELEASED", releaseResponse);
    // [4] test whether everything ended as expected
    executorService.shutdown();
    assertTrue("The test thread did not finish in timely fashion!", executorService.awaitTermination(WAIT_TIMEOUT, TimeUnit.MILLISECONDS));
    assertEquals("async-OK-" + uuid, asyncResult.get());
}
Also used : AsyncResponse(javax.ws.rs.container.AsyncResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) Test(org.junit.Test) AbstractAsyncJerseyTest(org.glassfish.jersey.tests.integration.async.AbstractAsyncJerseyTest)

Example 8 with AsyncResponse

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

the class FlowableAgentResource method flowable.

@GET
public void flowable(@Suspended final AsyncResponse async) {
    final long time = System.nanoTime();
    final Queue<String> errors = new ConcurrentLinkedQueue<>();
    Flowable.just(new AgentResponse()).zipWith(visited(errors), (agentResponse, visited) -> {
        agentResponse.setVisited(visited);
        return agentResponse;
    }).zipWith(recommended(errors), (agentResponse, recommendations) -> {
        agentResponse.setRecommended(recommendations);
        return agentResponse;
    }).observeOn(Schedulers.io()).subscribe(agentResponse -> {
        agentResponse.setProcessingTime((System.nanoTime() - time) / 1000000);
        async.resume(agentResponse);
    }, async::resume);
}
Also used : Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) AsyncResponse(javax.ws.rs.container.AsyncResponse) Path(javax.ws.rs.Path) Singleton(javax.inject.Singleton) Suspended(javax.ws.rs.container.Suspended) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) Uri(org.glassfish.jersey.server.Uri) Destination(org.glassfish.jersey.examples.rx.domain.Destination) GenericType(javax.ws.rs.core.GenericType) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) List(java.util.List) Flowable(io.reactivex.Flowable) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation) Schedulers(io.reactivex.schedulers.Schedulers) Queue(java.util.Queue) WebTarget(javax.ws.rs.client.WebTarget) RxFlowableInvoker(org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker) RxFlowableInvokerProvider(org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider) Collections(java.util.Collections) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) GET(javax.ws.rs.GET)

Example 9 with AsyncResponse

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

the class AsyncCancelTimeoutResource method setTimeout.

@POST
@Path("timeout")
public void setTimeout(final String stage) throws Exception {
    final AsyncResponse async = stages[Integer.parseInt(stage)].take();
    async.setTimeoutHandler(new TimeoutHandler() {

        @Override
        public void handleTimeout(final AsyncResponse response) {
            response.cancel();
        }
    });
    async.setTimeout(200L, TimeUnit.MILLISECONDS);
    stages[Integer.parseInt(stage) + 1].add(async);
}
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 10 with AsyncResponse

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

the class AsyncResumeTimeoutResource 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");
                }
            });
        }
    });
}
Also used : TimeoutHandler(javax.ws.rs.container.TimeoutHandler) AsyncResponse(javax.ws.rs.container.AsyncResponse) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

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