Search in sources :

Example 1 with JerseyProcessingUncaughtExceptionHandler

use of org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler in project jersey by jersey.

the class GrizzlyHttpServerFactory method createHttpServer.

/**
     * Create new {@link HttpServer} instance.
     *
     * @param uri                   uri on which the {@link ApplicationHandler} will be deployed. Only first path
     *                              segment will be used as context path, the rest will be ignored.
     * @param handler               {@link HttpHandler} instance.
     * @param secure                used for call {@link NetworkListener#setSecure(boolean)}.
     * @param sslEngineConfigurator Ssl settings to be passed to {@link NetworkListener#setSSLEngineConfig}.
     * @param start                 if set to false, server will not get started, this allows end users to set
     *                              additional properties on the underlying listener.
     * @return newly created {@code HttpServer}.
     * @throws ProcessingException in case of any failure when creating a new {@code HttpServer} instance.
     * @see GrizzlyHttpContainer
     */
public static HttpServer createHttpServer(final URI uri, final GrizzlyHttpContainer handler, final boolean secure, final SSLEngineConfigurator sslEngineConfigurator, final boolean start) {
    final String host = (uri.getHost() == null) ? NetworkListener.DEFAULT_NETWORK_HOST : uri.getHost();
    final int port = (uri.getPort() == -1) ? (secure ? Container.DEFAULT_HTTPS_PORT : Container.DEFAULT_HTTP_PORT) : uri.getPort();
    final NetworkListener listener = new NetworkListener("grizzly", host, port);
    listener.getTransport().getWorkerThreadPoolConfig().setThreadFactory(new ThreadFactoryBuilder().setNameFormat("grizzly-http-server-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    listener.setSecure(secure);
    if (sslEngineConfigurator != null) {
        listener.setSSLEngineConfig(sslEngineConfigurator);
    }
    final HttpServer server = new HttpServer();
    server.addListener(listener);
    // Map the path to the processor.
    final ServerConfiguration config = server.getServerConfiguration();
    if (handler != null) {
        final String path = uri.getPath().replaceAll("/{2,}", "/");
        final String contextPath = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
        config.addHttpHandler(handler, HttpHandlerRegistration.bulder().contextPath(contextPath).build());
    }
    config.setPassTraceRequest(true);
    config.setDefaultQueryEncoding(Charsets.UTF8_CHARSET);
    if (start) {
        try {
            // Start the server.
            server.start();
        } catch (final IOException ex) {
            server.shutdownNow();
            throw new ProcessingException(LocalizationMessages.FAILED_TO_START_SERVER(ex.getMessage()), ex);
        }
    }
    return server;
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ServerConfiguration(org.glassfish.grizzly.http.server.ServerConfiguration) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) IOException(java.io.IOException) NetworkListener(org.glassfish.grizzly.http.server.NetworkListener) ProcessingException(javax.ws.rs.ProcessingException)

Example 2 with JerseyProcessingUncaughtExceptionHandler

use of org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler in project jersey by jersey.

the class JerseyCompletionStageRxInvokerTest method setUp.

@Before
public void setUp() throws Exception {
    client = ClientBuilder.newClient().register(TerminalClientRequestFilter.class);
    executor = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().setNameFormat("jersey-rx-client-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) Before(org.junit.Before)

Example 3 with JerseyProcessingUncaughtExceptionHandler

use of org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler in project jersey by jersey.

the class AbstractThreadPoolProvider method createThreadFactory.

private ThreadFactory createThreadFactory() {
    final ThreadFactoryBuilder factoryBuilder = new ThreadFactoryBuilder().setNameFormat(name + "-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler());
    final ThreadFactory backingThreadFactory = getBackingThreadFactory();
    if (backingThreadFactory != null) {
        factoryBuilder.setThreadFactory(backingThreadFactory);
    }
    return factoryBuilder.build();
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder)

Example 4 with JerseyProcessingUncaughtExceptionHandler

use of org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler in project jersey by jersey.

the class RxObservableTest method setUp.

@Before
public void setUp() throws Exception {
    client = ClientBuilder.newClient().register(TerminalClientRequestFilter.class);
    client.register(RxObservableInvokerProvider.class);
    executor = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().setNameFormat("jersey-rx-client-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) Before(org.junit.Before)

Example 5 with JerseyProcessingUncaughtExceptionHandler

use of org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler in project jersey by jersey.

the class ManagedAsyncResourceTest method testChatResource.

@Test
public void testChatResource() throws InterruptedException {
    final WebTarget resourceTarget = target().path("chat");
    final int MAX_MESSAGES = 100;
    final int LATCH_WAIT_TIMEOUT = 10 * getAsyncTimeoutMultiplier();
    final boolean debugMode = false;
    final boolean sequentialGet = false;
    final boolean sequentialPost = false;
    final Object sequentialGetLock = new Object();
    final Object sequentialPostLock = new Object();
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, Integer> postResponses = new ConcurrentHashMap<Integer, Integer>();
    final Map<Integer, Message> getResponses = new ConcurrentHashMap<Integer, Message>();
    final CountDownLatch postRequestLatch = new CountDownLatch(MAX_MESSAGES);
    final CountDownLatch getRequestLatch = new CountDownLatch(MAX_MESSAGES);
    try {
        for (int i = 0; i < MAX_MESSAGES; i++) {
            final int requestId = i;
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialPost) {
                        synchronized (sequentialPostLock) {
                            post();
                        }
                    } else {
                        post();
                    }
                }

                private void post() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final Response response = resourceTarget.request().post(Entity.json(new Message("" + requestId, "" + requestId)));
                                postResponses.put(requestId, response.getStatus());
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.WARNING, String.format("Error POSTING message <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error POSTING message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        postRequestLatch.countDown();
                    }
                }
            });
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialGet) {
                        synchronized (sequentialGetLock) {
                            get();
                        }
                    } else {
                        get();
                    }
                }

                private void get() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final Message response = resourceTarget.request("application/json").get(Message.class);
                                getResponses.put(requestId, response);
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.SEVERE, String.format("Error sending GET request <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error sending GET message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        getRequestLatch.countDown();
                    }
                }
            });
        }
        if (debugMode) {
            postRequestLatch.await();
            getRequestLatch.await();
        } else {
            if (!postRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all POST requests to complete has timed out.");
            }
            if (!getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all GET requests to complete has timed out.");
            }
        }
    } finally {
        executor.shutdownNow();
    }
    StringBuilder messageBuilder = new StringBuilder("POST responses received: ").append(postResponses.size()).append("\n");
    for (Map.Entry<Integer, Integer> postResponseEntry : postResponses.entrySet()) {
        messageBuilder.append("POST response for message ").append(postResponseEntry.getKey()).append(": ").append(postResponseEntry.getValue()).append('\n');
    }
    messageBuilder.append('\n');
    messageBuilder.append("GET responses received: ").append(getResponses.size()).append("\n");
    for (Map.Entry<Integer, Message> getResponseEntry : getResponses.entrySet()) {
        messageBuilder.append("GET response for message ").append(getResponseEntry.getKey()).append(": ").append(getResponseEntry.getValue()).append('\n');
    }
    LOGGER.info(messageBuilder.toString());
    for (Map.Entry<Integer, Integer> postResponseEntry : postResponses.entrySet()) {
        assertEquals("Unexpected POST notification response for message " + postResponseEntry.getKey(), 200, postResponseEntry.getValue().intValue());
    }
    final List<Integer> lost = new LinkedList<Integer>();
    final Collection<Message> getResponseValues = getResponses.values();
    for (int i = 0; i < MAX_MESSAGES; i++) {
        if (!getResponseValues.contains(new Message("" + i, "" + i))) {
            lost.add(i);
        }
    }
    if (!lost.isEmpty()) {
        fail("Detected a posted message loss(es): " + lost.toString());
    }
    assertEquals(MAX_MESSAGES, postResponses.size());
    assertEquals(MAX_MESSAGES, getResponses.size());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) Response(javax.ws.rs.core.Response) ExecutorService(java.util.concurrent.ExecutorService) WebTarget(javax.ws.rs.client.WebTarget) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Aggregations

ThreadFactoryBuilder (org.glassfish.jersey.internal.guava.ThreadFactoryBuilder)15 JerseyProcessingUncaughtExceptionHandler (org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler)15 Map (java.util.Map)8 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)8 CountDownLatch (java.util.concurrent.CountDownLatch)8 ExecutorService (java.util.concurrent.ExecutorService)8 WebTarget (javax.ws.rs.client.WebTarget)7 JerseyTest (org.glassfish.jersey.test.JerseyTest)7 Test (org.junit.Test)7 Response (javax.ws.rs.core.Response)5 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)4 ProcessingException (javax.ws.rs.ProcessingException)4 Before (org.junit.Before)4 IOException (java.io.IOException)2 LinkedList (java.util.LinkedList)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 HttpServer (com.sun.net.httpserver.HttpServer)1 HttpsConfigurator (com.sun.net.httpserver.HttpsConfigurator)1 HttpsServer (com.sun.net.httpserver.HttpsServer)1 InetSocketAddress (java.net.InetSocketAddress)1