Search in sources :

Example 1 with EventListener

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

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

the class EventOutputTest method testGrizzlyConnectorWithEventSource.

@Test
public void testGrizzlyConnectorWithEventSource() throws InterruptedException {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 15000);
    clientConfig.property(ClientProperties.READ_TIMEOUT, 0);
    clientConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    clientConfig.connectorProvider(new GrizzlyConnectorProvider());
    Client client = ClientBuilder.newBuilder().withConfig(clientConfig).build();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> eventData = new AtomicReference<String>();
    final AtomicInteger counter = new AtomicInteger(0);
    WebTarget single = client.target(getBaseUri()).path("test/single");
    EventSource es = EventSource.target(single).build();
    es.register(new EventListener() {

        @Override
        public void onEvent(InboundEvent inboundEvent) {
            final int i = counter.incrementAndGet();
            if (i == 1) {
                eventData.set(inboundEvent.readData());
            }
            latch.countDown();
        }
    });
    boolean latchTimedOut;
    boolean closeTimedOut;
    try {
        es.open();
        latchTimedOut = latch.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS);
    } finally {
        closeTimedOut = es.close(5, TimeUnit.SECONDS);
    }
    assertEquals("Unexpected event count", 1, counter.get());
    assertEquals("Unexpected event data", "single", eventData.get());
    assertTrue("Event latch has timed out", latchTimedOut);
    assertTrue("EventSource.close() has timed out", closeTimedOut);
}
Also used : GrizzlyConnectorProvider(org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) 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) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 3 with EventListener

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

the class EventOutputTest method testReadCommentsOnlySseEvents.

/**
     * Reproducer for JERSEY-2912: Sending and receiving comments-only events.
     *
     * @throws Exception
     */
@Test
public void testReadCommentsOnlySseEvents() throws Exception {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 15000);
    clientConfig.property(ClientProperties.READ_TIMEOUT, 0);
    clientConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    clientConfig.connectorProvider(new GrizzlyConnectorProvider());
    Client client = ClientBuilder.newBuilder().withConfig(clientConfig).build();
    final CountDownLatch latch = new CountDownLatch(2);
    final Queue<String> eventComments = new ArrayBlockingQueue<>(2);
    WebTarget single = client.target(getBaseUri()).path("test/comments-only");
    EventSource es = EventSource.target(single).build();
    es.register(new EventListener() {

        @Override
        public void onEvent(InboundEvent inboundEvent) {
            eventComments.add(inboundEvent.getComment());
            latch.countDown();
        }
    });
    boolean latchTimedOut;
    boolean closeTimedOut;
    try {
        es.open();
        latchTimedOut = latch.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS);
    } finally {
        closeTimedOut = es.close(5, TimeUnit.SECONDS);
    }
    assertEquals("Unexpected event count", 2, eventComments.size());
    for (int i = 1; i <= 2; i++) {
        assertEquals("Unexpected comment data on event #" + i, "No comment #" + i, eventComments.poll());
    }
    assertTrue("Event latch has timed out", latchTimedOut);
    assertTrue("EventSource.close() has timed out", closeTimedOut);
}
Also used : GrizzlyConnectorProvider(org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) EventSource(org.glassfish.jersey.media.sse.EventSource) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) InboundEvent(org.glassfish.jersey.media.sse.InboundEvent) WebTarget(javax.ws.rs.client.WebTarget) EventListener(org.glassfish.jersey.media.sse.EventListener) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 4 with EventListener

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

the class EventSourceWithNamedEventsTest method testWithEventSource.

@Test
public void testWithEventSource() throws IOException, NoSuchAlgorithmException, InterruptedException {
    final WebTarget endpoint = target().register(SseFeature.class).path("events");
    EventSource eventSource = EventSource.target(endpoint).build();
    final CountDownLatch count = new CountDownLatch(MSG_COUNT);
    final EventListener listener = new EventListener() {

        @Override
        public void onEvent(InboundEvent inboundEvent) {
            try {
                final Integer data = inboundEvent.readData(Integer.class);
                System.out.println(inboundEvent.getName() + "; " + data);
                Assert.assertEquals(SSE_NAME, inboundEvent.getName());
                Assert.assertEquals(MSG_COUNT - count.getCount(), data.intValue());
                count.countDown();
            } catch (ProcessingException ex) {
                throw new RuntimeException("Error when deserializing of data.", ex);
            }
        }
    };
    eventSource.register(listener, "message-to-client");
    eventSource.open();
    final boolean sent = latch.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS);
    Assert.assertTrue("Awaiting for SSE message has timeout. Not all message were sent.", sent);
    final boolean handled = count.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS);
    Assert.assertTrue("Awaiting for SSE message has timeout. Not all message were handled by the listener.", handled);
}
Also used : EventSource(org.glassfish.jersey.media.sse.EventSource) InboundEvent(org.glassfish.jersey.media.sse.InboundEvent) WebTarget(javax.ws.rs.client.WebTarget) EventListener(org.glassfish.jersey.media.sse.EventListener) CountDownLatch(java.util.concurrent.CountDownLatch) SseFeature(org.glassfish.jersey.media.sse.SseFeature) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 5 with EventListener

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

the class SseEventSinkToEventSourceTest method testWithJerseyApi.

@Test
public void testWithJerseyApi() throws InterruptedException {
    final WebTarget endpoint = target().path("events");
    final EventSource eventSource = EventSource.target(endpoint).build();
    transmitLatch = new CountDownLatch(MSG_COUNT);
    final CountDownLatch receiveLatch = new CountDownLatch(MSG_COUNT);
    final List<Integer> results = new ArrayList<>();
    final EventListener listener = inboundEvent -> {
        try {
            results.add(inboundEvent.readData(Integer.class));
            receiveLatch.countDown();
            Assert.assertEquals(INTEGER_SSE_NAME, inboundEvent.getName());
        } catch (ProcessingException ex) {
            throw new RuntimeException("Error when deserializing of data.", ex);
        }
    };
    eventSource.register(listener, INTEGER_SSE_NAME);
    eventSource.open();
    Assert.assertTrue(transmitLatch.await(5000, TimeUnit.MILLISECONDS));
    Assert.assertTrue(receiveLatch.await(5000, TimeUnit.MILLISECONDS));
    Assert.assertEquals(10, results.size());
}
Also used : SseEventSource(javax.ws.rs.sse.SseEventSource) SseEventSink(javax.ws.rs.sse.SseEventSink) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) Application(javax.ws.rs.core.Application) Singleton(javax.inject.Singleton) ArrayList(java.util.ArrayList) MediaType(javax.ws.rs.core.MediaType) JerseyTest(org.glassfish.jersey.test.JerseyTest) Sse(javax.ws.rs.sse.Sse) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ExecutorService(java.util.concurrent.ExecutorService) Context(javax.ws.rs.core.Context) EventListener(org.glassfish.jersey.media.sse.EventListener) EventSource(org.glassfish.jersey.media.sse.EventSource) Test(org.junit.Test) Logger(java.util.logging.Logger) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) InboundSseEvent(javax.ws.rs.sse.InboundSseEvent) ProcessingException(javax.ws.rs.ProcessingException) WebTarget(javax.ws.rs.client.WebTarget) Assert(org.junit.Assert) SseEventSource(javax.ws.rs.sse.SseEventSource) EventSource(org.glassfish.jersey.media.sse.EventSource) ArrayList(java.util.ArrayList) WebTarget(javax.ws.rs.client.WebTarget) EventListener(org.glassfish.jersey.media.sse.EventListener) CountDownLatch(java.util.concurrent.CountDownLatch) ProcessingException(javax.ws.rs.ProcessingException) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Aggregations

CountDownLatch (java.util.concurrent.CountDownLatch)9 WebTarget (javax.ws.rs.client.WebTarget)9 EventListener (org.glassfish.jersey.media.sse.EventListener)9 EventSource (org.glassfish.jersey.media.sse.EventSource)9 JerseyTest (org.glassfish.jersey.test.JerseyTest)9 Test (org.junit.Test)9 InboundEvent (org.glassfish.jersey.media.sse.InboundEvent)8 ArrayList (java.util.ArrayList)5 Queue (java.util.Queue)4 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 ProcessingException (javax.ws.rs.ProcessingException)4 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)4 Client (javax.ws.rs.client.Client)2 ClientConfig (org.glassfish.jersey.client.ClientConfig)2 GrizzlyConnectorProvider (org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2 List (java.util.List)1 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1