Search in sources :

Example 31 with WebTarget

use of javax.ws.rs.client.WebTarget 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 32 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class Main method runClient.

/**
     * Client - business logic.
     *
     * @param args command-line arguments.
     * @return exit code of the utility. {@code 0} if everything completed without errors, {@code -1} otherwise.
     */
static int runClient(final String[] args) {
    // Parsing command-line arguments
    final Config config = Config.parse(args);
    System.out.println(String.format("\nStarting to execute %d requests:\n", config.requests));
    // Creating JAX-RS client
    final Client client = ClientBuilder.newClient();
    // Targeting echo resource at URI "<baseUri>/long-running/(sync|async)/{echo}"
    final WebTarget echoResource = client.target(config.baseUri).path("long-running/{mode}/{echo}").resolveTemplate("mode", (config.sync) ? "sync" : "async");
    final CountDownLatch latch = new CountDownLatch(config.requests);
    final Queue<String> errors = new ConcurrentLinkedQueue<String>();
    final AtomicInteger requestCounter = new AtomicInteger(0);
    final long tic = System.currentTimeMillis();
    for (int i = 0; i < config.requests; i++) {
        final int reqId = i;
        echoResource.resolveTemplate("echo", reqId).request().async().get(new InvocationCallback<String>() {

            private final AtomicInteger retries = new AtomicInteger(0);

            @Override
            public void completed(String response) {
                final String requestId = Integer.toString(reqId);
                if (requestId.equals(response)) {
                    System.out.print("*");
                    requestCounter.incrementAndGet();
                } else {
                    System.out.print("!");
                    errors.offer(String.format("Echo response '%s' not equal to request '%s'", response, requestId));
                }
                latch.countDown();
            }

            @Override
            public void failed(Throwable error) {
                if (error.getCause() instanceof IOException && retries.getAndIncrement() < 3) {
                    // resend
                    echoResource.resolveTemplate("echo", reqId).request().async().get(this);
                } else {
                    System.out.print("!");
                    errors.offer(String.format("Request '%d' has failed: %s", reqId, error.toString()));
                    latch.countDown();
                }
            }
        });
    }
    try {
        if (!latch.await(60, TimeUnit.SECONDS)) {
            errors.offer("Waiting for requests to complete has timed out.");
        }
    } catch (InterruptedException e) {
        errors.offer("Waiting for requests to complete has been interrupted.");
    }
    final long toc = System.currentTimeMillis();
    System.out.println(String.format("\n\nExecution finished in %d ms.\nSuccess rate: %6.2f %%", toc - tic, ((double) requestCounter.get() / config.requests) * 100));
    if (errors.size() > 0) {
        System.out.println("Following errors occurred during the request execution");
        for (String error : errors) {
            System.out.println("\t" + error);
        }
    }
    client.close();
    return errors.size() > 0 ? -1 : 0;
}
Also used : IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue)

Example 33 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class ItemStoreResourceTest method testItemsStore.

/**
     * Test the item addition, addition event broadcasting and item retrieval from {@link ItemStoreResource}.
     *
     * @throws Exception in case of a test failure.
     */
@Test
public void testItemsStore() throws Exception {
    final List<String> items = Collections.unmodifiableList(Arrays.asList("foo", "bar", "baz"));
    final WebTarget itemsTarget = target("items");
    // countdown on all events
    final CountDownLatch latch = new CountDownLatch(items.size() * MAX_LISTENERS * 2);
    final List<Queue<Integer>> indexQueues = new ArrayList<Queue<Integer>>(MAX_LISTENERS);
    final EventSource[] sources = new EventSource[MAX_LISTENERS];
    final AtomicInteger sizeEventsCount = new AtomicInteger(0);
    for (int i = 0; i < MAX_LISTENERS; i++) {
        final int id = i;
        final EventSource es = EventSource.target(itemsTarget.path("events")).named("SOURCE " + id).build();
        sources[id] = es;
        final Queue<Integer> indexes = new ConcurrentLinkedQueue<Integer>();
        indexQueues.add(indexes);
        es.register(new EventListener() {

            @SuppressWarnings("MagicNumber")
            @Override
            public void onEvent(InboundEvent inboundEvent) {
                try {
                    if (inboundEvent.getName() == null) {
                        final String data = inboundEvent.readData();
                        LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data=" + data);
                        indexes.add(items.indexOf(data));
                    } else if ("size".equals(inboundEvent.getName())) {
                        sizeEventsCount.incrementAndGet();
                    }
                } catch (Exception ex) {
                    LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
                    indexes.add(-999);
                } finally {
                    latch.countDown();
                }
            }
        });
    }
    try {
        open(sources);
        for (String item : items) {
            postItem(itemsTarget, item);
        }
        assertTrue("Waiting to receive all events has timed out.", latch.await((1000 + MAX_LISTENERS * EventSource.RECONNECT_DEFAULT) * getAsyncTimeoutMultiplier(), TimeUnit.MILLISECONDS));
        // need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection
        sendCommand(itemsTarget, "disconnect");
    } finally {
        close(sources);
    }
    String postedItems = itemsTarget.request().get(String.class);
    for (String item : items) {
        assertTrue("Item '" + item + "' not stored on server.", postedItems.contains(item));
    }
    int queueId = 0;
    for (Queue<Integer> indexes : indexQueues) {
        for (int i = 0; i < items.size(); i++) {
            assertTrue("Event for '" + items.get(i) + "' not received in queue " + queueId, indexes.contains(i));
        }
        assertEquals("Not received the expected number of events in queue " + queueId, items.size(), indexes.size());
        queueId++;
    }
    assertEquals("Number of received 'size' events does not match.", items.size() * MAX_LISTENERS, sizeEventsCount.get());
}
Also used : ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EventSource(org.glassfish.jersey.media.sse.EventSource) InboundEvent(org.glassfish.jersey.media.sse.InboundEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WebTarget(javax.ws.rs.client.WebTarget) EventListener(org.glassfish.jersey.media.sse.EventListener) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Queue(java.util.Queue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 34 with WebTarget

use of javax.ws.rs.client.WebTarget 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 35 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class MainWindow method sendMessages.

private void sendMessages(final Main.Config config) {
    // Creating JAX-RS client
    final Client client = ClientBuilder.newClient();
    // Targeting echo resource at URI "<baseUri>/long-running/(sync|async)/{echo}"
    final WebTarget echoResource = client.target(config.baseUri).path("long-running/{mode}/{echo}").resolveTemplate("mode", (config.sync) ? "sync" : "async");
    final CountDownLatch latch = new CountDownLatch(config.requests);
    final AtomicInteger requestCounter = new AtomicInteger(0);
    final long tic = System.currentTimeMillis();
    for (int i = 0; i < config.requests; i++) {
        final int reqId = i;
        final JLabel requestStatusLabel = createRequestStatusLabel();
        echoResource.resolveTemplate("echo", reqId).request().async().get(new InvocationCallback<String>() {

            private final AtomicInteger retries = new AtomicInteger(0);

            @Override
            public void completed(final String response) {
                invokeAndWait(new Runnable() {

                    @Override
                    public void run() {
                        final String requestId = Integer.toString(reqId);
                        if (requestId.equals(response)) {
                            requestStatusLabel.setBackground(SUCCESS_COLOR);
                            requestStatusLabel.setToolTipText(requestId);
                            requestCounter.incrementAndGet();
                        } else {
                            requestStatusLabel.setBackground(ERROR_COLOR);
                            requestStatusLabel.setToolTipText(String.format("Echo response '%s' not equal to request '%s'", response, requestId));
                        }
                        latch.countDown();
                    }
                });
            }

            @Override
            public void failed(final Throwable error) {
                if (error.getCause() instanceof IOException && retries.getAndIncrement() < 3) {
                    // resend
                    echoResource.resolveTemplate("echo", reqId).request().async().get(this);
                } else {
                    invokeAndWait(new Runnable() {

                        @Override
                        public void run() {
                            requestStatusLabel.setBackground(ERROR_COLOR);
                            requestStatusLabel.setToolTipText(String.format("Request '%d' has failed: %s", reqId, error.toString()));
                            latch.countDown();
                        }
                    });
                }
            }
        });
    }
    try {
        if (!latch.await(60, TimeUnit.SECONDS)) {
            System.out.println("Waiting for requests to complete has timed out.");
        }
    } catch (InterruptedException e) {
        System.out.println("Waiting for requests to complete has been interrupted.");
    }
    final long toc = System.currentTimeMillis();
    invokeAndWait(new Runnable() {

        @Override
        public void run() {
            finishStatusLabel.setText(String.format("Execution finished in %d ms.", toc - tic));
            successRateStatusLabel.setText(String.format("Success rate: %6.2f %%", ((double) requestCounter.get() / config.requests) * 100));
        }
    });
    client.close();
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            runButton.setEnabled(true);
        }
    });
}
Also used : JLabel(javax.swing.JLabel) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client)

Aggregations

WebTarget (javax.ws.rs.client.WebTarget)688 Test (org.junit.Test)529 Response (javax.ws.rs.core.Response)354 JerseyTest (org.glassfish.jersey.test.JerseyTest)297 Client (javax.ws.rs.client.Client)122 ClientConfig (org.glassfish.jersey.client.ClientConfig)50 GenericType (javax.ws.rs.core.GenericType)39 Invocation (javax.ws.rs.client.Invocation)36 ClientBuilder (javax.ws.rs.client.ClientBuilder)30 ArrayList (java.util.ArrayList)29 List (java.util.List)28 InputStream (java.io.InputStream)26 IOException (java.io.IOException)25 CountDownLatch (java.util.concurrent.CountDownLatch)25 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)25 ProcessingException (javax.ws.rs.ProcessingException)22 Builder (javax.ws.rs.client.Invocation.Builder)22 Map (java.util.Map)21 URI (java.net.URI)19 Properties (java.util.Properties)19