Search in sources :

Example 1 with EventSource

use of org.glassfish.jersey.media.sse.EventSource in project jersey by jersey.

the class ItemStoreResourceITCase 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() {

            @Override
            @SuppressWarnings("MagicNumber")
            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 (ProcessingException 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) ProcessingException(javax.ws.rs.ProcessingException) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 2 with EventSource

use of org.glassfish.jersey.media.sse.EventSource in project jersey by jersey.

the class ItemStoreResourceITCase method open.

private static void open(final EventSource[] sources) {
    int i = 0;
    for (EventSource source : sources) {
        source.open();
        LOGGER.info("[-->] SOURCE " + i++ + " opened.");
    }
}
Also used : EventSource(org.glassfish.jersey.media.sse.EventSource)

Example 3 with EventSource

use of org.glassfish.jersey.media.sse.EventSource in project jersey by jersey.

the class SseTest method testSse.

@Test
public void testSse() throws Exception {
    final ResourceConfig resourceConfig = new ResourceConfig(SseResource.class, SseFeature.class);
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);
    Client c = ClientBuilder.newClient();
    c.register(SseFeature.class);
    final List<String> data = new LinkedList<String>();
    final CountDownLatch latch = new CountDownLatch(2);
    final EventSource eventSource = new EventSource(c.target(baseUri).path("/sse")) {

        @Override
        public void onEvent(InboundEvent event) {
            try {
                data.add(event.readData());
                latch.countDown();
            } catch (ProcessingException e) {
            // ignore
            }
        }
    };
    assertTrue(latch.await(2, TimeUnit.SECONDS));
    eventSource.close();
    assertEquals(2, data.size());
    server.shutdownNow();
}
Also used : EventSource(org.glassfish.jersey.media.sse.EventSource) InboundEvent(org.glassfish.jersey.media.sse.InboundEvent) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) Client(javax.ws.rs.client.Client) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test)

Example 4 with EventSource

use of org.glassfish.jersey.media.sse.EventSource 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 5 with EventSource

use of org.glassfish.jersey.media.sse.EventSource in project jersey by jersey.

the class ItemStoreResourceTest method close.

private static void close(final EventSource[] sources) {
    int i = 0;
    for (EventSource source : sources) {
        if (source.isOpen()) {
            assertTrue("Waiting to close a source has timed out.", source.close(1, TimeUnit.SECONDS));
            //                    source.close(100, TimeUnit.MILLISECONDS);
            LOGGER.info("[<--] SOURCE " + i++ + " closed.");
        }
    }
}
Also used : EventSource(org.glassfish.jersey.media.sse.EventSource)

Aggregations

EventSource (org.glassfish.jersey.media.sse.EventSource)15 CountDownLatch (java.util.concurrent.CountDownLatch)11 Test (org.junit.Test)11 InboundEvent (org.glassfish.jersey.media.sse.InboundEvent)10 JerseyTest (org.glassfish.jersey.test.JerseyTest)10 WebTarget (javax.ws.rs.client.WebTarget)9 EventListener (org.glassfish.jersey.media.sse.EventListener)9 ProcessingException (javax.ws.rs.ProcessingException)6 ArrayList (java.util.ArrayList)5 Queue (java.util.Queue)4 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)4 Client (javax.ws.rs.client.Client)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 ClientConfig (org.glassfish.jersey.client.ClientConfig)2 GrizzlyConnectorProvider (org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider)2 ResourceConfig (org.glassfish.jersey.server.ResourceConfig)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2 LinkedList (java.util.LinkedList)1