Search in sources :

Example 1 with ChunkedOutput

use of org.glassfish.jersey.server.ChunkedOutput in project Gaffer by gchq.

the class OperationServiceV2 method executeChunkedChain.

@SuppressFBWarnings
@Override
public Response executeChunkedChain(final OperationChain opChain) {
    // Create chunked output instance
    final Throwable[] threadException = new Throwable[1];
    final ChunkedOutput<String> output = new ChunkedOutput<>(String.class, "\r\n");
    final Context context = userFactory.createContext();
    // create thread to write chunks to the chunked output object
    Thread thread = new Thread(() -> {
        try {
            final Object result = _execute(opChain, context).getFirst();
            chunkResult(result, output);
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            CloseableUtil.close(output);
            CloseableUtil.close(opChain);
        }
    });
    // By default threads throw nothing, so set the ExceptionHandler
    thread.setUncaughtExceptionHandler((thread1, exception) -> threadException[0] = exception.getCause());
    thread.start();
    // Sleep to check exception will be caught
    try {
        Thread.sleep(1000);
    } catch (final InterruptedException e) {
        return Response.status(INTERNAL_SERVER_ERROR).entity(new Error.ErrorBuilder().status(Status.INTERNAL_SERVER_ERROR).statusCode(500).simpleMessage(e.getMessage()).build()).header(GAFFER_MEDIA_TYPE_HEADER, GAFFER_MEDIA_TYPE).build();
    }
    // If there was an UnauthorisedException thrown return 403, else return a 500
    if (null != threadException[0]) {
        if (threadException.getClass().equals(UnauthorisedException.class)) {
            return Response.status(INTERNAL_SERVER_ERROR).entity(new Error.ErrorBuilder().status(Status.FORBIDDEN).statusCode(403).simpleMessage(threadException[0].getMessage()).build()).header(GAFFER_MEDIA_TYPE_HEADER, GAFFER_MEDIA_TYPE).build();
        } else {
            return Response.status(INTERNAL_SERVER_ERROR).entity(new Error.ErrorBuilder().status(Status.INTERNAL_SERVER_ERROR).statusCode(500).simpleMessage(threadException[0].getMessage()).build()).header(GAFFER_MEDIA_TYPE_HEADER, GAFFER_MEDIA_TYPE).build();
        }
    }
    // Return ok output
    return Response.ok(output).header(GAFFER_MEDIA_TYPE_HEADER, GAFFER_MEDIA_TYPE).build();
}
Also used : Context(uk.gov.gchq.gaffer.store.Context) Error(uk.gov.gchq.gaffer.core.exception.Error) ChunkedOutput(org.glassfish.jersey.server.ChunkedOutput) IOException(java.io.IOException) UnauthorisedException(uk.gov.gchq.gaffer.commonutil.exception.UnauthorisedException) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 2 with ChunkedOutput

use of org.glassfish.jersey.server.ChunkedOutput in project jersey by jersey.

the class BroadcasterTest method testBroadcaster.

@Test
public void testBroadcaster() throws IOException {
    InputStream is1 = getChunkStream();
    InputStream is2 = getChunkStream();
    InputStream is3 = getChunkStream();
    InputStream is4 = getChunkStream();
    target("test").request().post(Entity.text("text1"));
    checkClosed(0);
    checkStream("firstChunktext1", is1, is2, is3, is4);
    outputs.remove(0).close();
    target("test").request().post(Entity.text("text2"));
    checkStream("text2", is2, is3, is4);
    checkClosed(1);
    outputs.remove(0).close();
    BroadcasterListener<String> bl = new BroadcasterListener<String>() {

        @Override
        public void onException(ChunkedOutput<String> stringChunkedResponse, Exception exception) {
        }

        @Override
        public void onClose(ChunkedOutput<String> stringChunkedResponse) {
            listenerClosed++;
        }
    };
    broadcaster.add(bl);
    target("test").request().post(Entity.text("text3"));
    checkClosed(2);
    assertEquals(1, listenerClosed);
    broadcaster.remove(bl);
    broadcaster.closeAll();
    checkClosed(4);
    assertEquals(1, listenerClosed);
    checkStream("text3", is3, is4);
}
Also used : InputStream(java.io.InputStream) BroadcasterListener(org.glassfish.jersey.server.BroadcasterListener) ChunkedOutput(org.glassfish.jersey.server.ChunkedOutput) IOException(java.io.IOException) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 3 with ChunkedOutput

use of org.glassfish.jersey.server.ChunkedOutput in project jersey by jersey.

the class TestResource method closeBeforeReturn.

/**
     * {@link org.glassfish.jersey.server.ChunkedOutput#close()} is called before method returns it's entity. Resource reproduces
     * JERSEY-2558 issue.
     *
     * @return (closed) chunk stream.
     */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("close-before-return")
public ChunkedOutput<Message> closeBeforeReturn() {
    final ChunkedOutput<Message> output = new ChunkedOutput<>(Message.class, "\r\n");
    final CountDownLatch latch = new CountDownLatch(1);
    new Thread() {

        @Override
        public void run() {
            try {
                for (int i = 0; i < 3; i++) {
                    output.write(new Message(i, "test"));
                    Thread.sleep(200);
                }
            } catch (final IOException e) {
                LOGGER.log(Level.SEVERE, "Error writing chunk.", e);
            } catch (final InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Sleep interrupted.", e);
                Thread.currentThread().interrupt();
            } finally {
                try {
                    output.close();
                    // Worker thread can continue.
                    latch.countDown();
                } catch (final IOException e) {
                    LOGGER.log(Level.INFO, "Error closing chunked output.", e);
                }
            }
        }
    }.start();
    try {
        // Wait till new thread closes the chunked output.
        latch.await();
        return output;
    } catch (final InterruptedException e) {
        throw new InternalServerErrorException(e);
    }
}
Also used : InternalServerErrorException(javax.ws.rs.InternalServerErrorException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ChunkedOutput(org.glassfish.jersey.server.ChunkedOutput) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

IOException (java.io.IOException)3 ChunkedOutput (org.glassfish.jersey.server.ChunkedOutput)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 InputStream (java.io.InputStream)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 GET (javax.ws.rs.GET)1 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 BroadcasterListener (org.glassfish.jersey.server.BroadcasterListener)1 JerseyTest (org.glassfish.jersey.test.JerseyTest)1 Test (org.junit.Test)1 UnauthorisedException (uk.gov.gchq.gaffer.commonutil.exception.UnauthorisedException)1 Error (uk.gov.gchq.gaffer.core.exception.Error)1 Context (uk.gov.gchq.gaffer.store.Context)1