Search in sources :

Example 6 with ThreadFactoryBuilder

use of org.glassfish.jersey.internal.guava.ThreadFactoryBuilder in project jersey by jersey.

the class ManagedAsyncResourceTest method testLongRunningResource.

@Test
public void testLongRunningResource() throws InterruptedException {
    final WebTarget resourceTarget = target().path(App.ASYNC_LONG_RUNNING_MANAGED_OP_PATH);
    final String expectedResponse = SimpleJerseyExecutorManagedLongRunningResource.NOTIFICATION_RESPONSE;
    final int MAX_MESSAGES = 100;
    final int LATCH_WAIT_TIMEOUT = 10 * getAsyncTimeoutMultiplier();
    final boolean debugMode = false;
    final boolean sequentialGet = false;
    final Object sequentialGetLock = new Object();
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
    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 || sequentialGet) {
                        synchronized (sequentialGetLock) {
                            get();
                        }
                    } else {
                        get();
                    }
                }

                private void get() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final String response = resourceTarget.queryParam("id", requestId).request().get(String.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) {
            getRequestLatch.await();
        } else {
            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("GET responses received: ").append(getResponses.size()).append("\n");
    for (Map.Entry<Integer, String> 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, String> entry : getResponses.entrySet()) {
        assertTrue("Unexpected GET notification response for message " + entry.getKey(), entry.getValue().contains(expectedResponse));
    }
    assertEquals(MAX_MESSAGES, getResponses.size());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) WebTarget(javax.ws.rs.client.WebTarget) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 7 with ThreadFactoryBuilder

use of org.glassfish.jersey.internal.guava.ThreadFactoryBuilder in project jersey by jersey.

the class AsyncResourceTest method testLongRunningResource.

@Test
public void testLongRunningResource() throws InterruptedException {
    final WebTarget resourceTarget = target().path(App.ASYNC_LONG_RUNNING_OP_PATH);
    final String expectedResponse = SimpleLongRunningResource.NOTIFICATION_RESPONSE;
    final int MAX_MESSAGES = 100;
    final int LATCH_WAIT_TIMEOUT = 25 * getAsyncTimeoutMultiplier();
    final boolean debugMode = false;
    final boolean sequentialGet = false;
    final Object sequentialGetLock = new Object();
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%02d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
    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 || sequentialGet) {
                        synchronized (sequentialGetLock) {
                            get();
                        }
                    } else {
                        get();
                    }
                }

                private void get() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final String response = resourceTarget.request().get(String.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) {
            getRequestLatch.await();
        } else {
            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();
    }
    final ArrayList<Map.Entry<Integer, String>> responseEntryList = new ArrayList<Map.Entry<Integer, String>>(getResponses.entrySet());
    Collections.sort(responseEntryList, new Comparator<Map.Entry<Integer, String>>() {

        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });
    StringBuilder messageBuilder = new StringBuilder("GET responses received: ").append(responseEntryList.size()).append("\n");
    for (Map.Entry<Integer, String> getResponseEntry : responseEntryList) {
        messageBuilder.append(String.format("GET response for message %02d: ", getResponseEntry.getKey())).append(getResponseEntry.getValue()).append('\n');
    }
    LOGGER.info(messageBuilder.toString());
    for (Map.Entry<Integer, String> entry : responseEntryList) {
        assertEquals(String.format("Unexpected GET notification response for message %02d", entry.getKey()), expectedResponse, entry.getValue());
    }
    assertEquals(MAX_MESSAGES, getResponses.size());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) WebTarget(javax.ws.rs.client.WebTarget) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 8 with ThreadFactoryBuilder

use of org.glassfish.jersey.internal.guava.ThreadFactoryBuilder in project jersey by jersey.

the class JdkHttpServerFactory method createHttpServer.

private static HttpServer createHttpServer(final URI uri, final JdkHttpHandlerContainer handler, final SSLContext sslContext, final boolean start) {
    if (uri == null) {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_NULL());
    }
    final String scheme = uri.getScheme();
    final boolean isHttp = "http".equalsIgnoreCase(scheme);
    final boolean isHttps = "https".equalsIgnoreCase(scheme);
    final HttpsConfigurator httpsConfigurator = sslContext != null ? new HttpsConfigurator(sslContext) : null;
    if (isHttp) {
        if (httpsConfigurator != null) {
            // attempt to use https with http scheme
            LOG.warning(LocalizationMessages.WARNING_CONTAINER_URI_SCHEME_SECURED());
        }
    } else if (isHttps) {
        if (httpsConfigurator == null) {
            if (start) {
                // Starting https server w/o SSL is invalid, it will lead to error anyway.
                throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_HTTPS_NO_SSL());
            } else {
                // Creating the https server w/o SSL context, but not starting it is valid.
                // However, server.setHttpsConfigurator() must be called before the start.
                LOG.info(LocalizationMessages.INFO_CONTAINER_HTTPS_NO_SSL());
            }
        }
    } else {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_SCHEME_UNKNOWN(uri));
    }
    final String path = uri.getPath();
    if (path == null) {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_PATH_NULL(uri));
    } else if (path.isEmpty()) {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_PATH_EMPTY(uri));
    } else if (path.charAt(0) != '/') {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_PATH_START(uri));
    }
    final int port = (uri.getPort() == -1) ? (isHttp ? Container.DEFAULT_HTTP_PORT : Container.DEFAULT_HTTPS_PORT) : uri.getPort();
    final HttpServer server;
    try {
        server = isHttp ? HttpServer.create(new InetSocketAddress(port), 0) : HttpsServer.create(new InetSocketAddress(port), 0);
    } catch (final IOException ioe) {
        throw new ProcessingException(LocalizationMessages.ERROR_CONTAINER_EXCEPTION_IO(), ioe);
    }
    if (isHttps && httpsConfigurator != null) {
        ((HttpsServer) server).setHttpsConfigurator(httpsConfigurator);
    }
    server.setExecutor(Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("jdk-http-server-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build()));
    server.createContext(path, handler);
    final HttpServer wrapper = isHttp ? createHttpServerWrapper(server, handler) : createHttpsServerWrapper((HttpsServer) server, handler);
    if (start) {
        wrapper.start();
    }
    return wrapper;
}
Also used : HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) IOException(java.io.IOException) HttpsServer(com.sun.net.httpserver.HttpsServer) ProcessingException(javax.ws.rs.ProcessingException)

Example 9 with ThreadFactoryBuilder

use of org.glassfish.jersey.internal.guava.ThreadFactoryBuilder in project jersey by jersey.

the class ClientRxTest method testRxInvokerWithExecutor.

@Test
public void testRxInvokerWithExecutor() {
    // implicit register (not saying that the contract is RxInvokerProvider).
    client.register(TestRxInvokerProvider.class);
    ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("rxTest-%d").build());
    String s = target(client).request().rx(TestRxInvoker.class, EXECUTOR_SERVICE).get();
    assertTrue("Provided RxInvoker was not used.", s.startsWith("rxTestInvoker"));
    assertTrue("Executor Service was not passed to RxInvoker", s.contains("rxTest-"));
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) Test(org.junit.Test)

Example 10 with ThreadFactoryBuilder

use of org.glassfish.jersey.internal.guava.ThreadFactoryBuilder in project jersey by jersey.

the class AsyncResourceTest method executeChatTest.

private void executeChatTest(final WebTarget resourceTarget, final String expectedPostResponse) throws InterruptedException {
    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-%02d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, String> postResponses = new ConcurrentHashMap<Integer, String>();
    final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
    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 String response = resourceTarget.request().post(Entity.text(String.format("%02d", requestId)), String.class);
                                postResponses.put(requestId, response);
                                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 String response = resourceTarget.queryParam("id", requestId).request().get(String.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, String> postResponseEntry : postResponses.entrySet()) {
        messageBuilder.append(String.format("POST response for message %02d: ", postResponseEntry.getKey())).append(postResponseEntry.getValue()).append('\n');
    }
    messageBuilder.append('\n');
    messageBuilder.append("GET responses received: ").append(getResponses.size()).append("\n");
    for (Map.Entry<Integer, String> getResponseEntry : getResponses.entrySet()) {
        messageBuilder.append(String.format("GET response for message %02d: ", getResponseEntry.getKey())).append(getResponseEntry.getValue()).append('\n');
    }
    LOGGER.info(messageBuilder.toString());
    for (Map.Entry<Integer, String> postResponseEntry : postResponses.entrySet()) {
        assertEquals(String.format("Unexpected POST notification response for message %02d", postResponseEntry.getKey()), expectedPostResponse, postResponseEntry.getValue());
    }
    final List<Integer> lost = new LinkedList<Integer>();
    final Collection<String> getResponseValues = getResponses.values();
    for (int i = 0; i < MAX_MESSAGES; i++) {
        if (!getResponseValues.contains(String.format("%02d", 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) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map)

Aggregations

ThreadFactoryBuilder (org.glassfish.jersey.internal.guava.ThreadFactoryBuilder)16 JerseyProcessingUncaughtExceptionHandler (org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler)15 ExecutorService (java.util.concurrent.ExecutorService)9 Map (java.util.Map)8 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)8 CountDownLatch (java.util.concurrent.CountDownLatch)8 Test (org.junit.Test)8 WebTarget (javax.ws.rs.client.WebTarget)7 JerseyTest (org.glassfish.jersey.test.JerseyTest)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