Search in sources :

Example 11 with InboundEvent

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

the class ItemStoreResourceITCase method testEventSourceReconnect.

/**
     * Test the {@link EventSource} reconnect feature.
     *
     * @throws Exception in case of a test failure.
     */
@Test
public void testEventSourceReconnect() throws Exception {
    final WebTarget itemsTarget = target("items");
    // countdown only on new item events
    final CountDownLatch latch = new CountDownLatch(MAX_ITEMS * MAX_LISTENERS * 2);
    final List<Queue<String>> receivedQueues = new ArrayList<Queue<String>>(MAX_LISTENERS);
    final EventSource[] sources = new EventSource[MAX_LISTENERS];
    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<String> received = new ConcurrentLinkedQueue<String>();
        receivedQueues.add(received);
        es.register(new EventListener() {

            @Override
            public void onEvent(InboundEvent inboundEvent) {
                try {
                    if (inboundEvent.getName() == null) {
                        latch.countDown();
                        final String data = inboundEvent.readData();
                        LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data=" + data);
                        received.add(data);
                    }
                } catch (ProcessingException ex) {
                    LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
                    received.add("[data processing error]");
                }
            }
        });
    }
    final String[] postedItems = new String[MAX_ITEMS * 2];
    try {
        open(sources);
        for (int i = 0; i < MAX_ITEMS; i++) {
            final String item = String.format("round-1-%02d", i);
            postItem(itemsTarget, item);
            postedItems[i] = item;
            sendCommand(itemsTarget, "disconnect");
            Thread.sleep(100);
        }
        final int reconnectDelay = 1;
        sendCommand(itemsTarget, "reconnect " + reconnectDelay);
        sendCommand(itemsTarget, "disconnect");
        Thread.sleep(reconnectDelay * 1000);
        for (int i = 0; i < MAX_ITEMS; i++) {
            final String item = String.format("round-2-%02d", i);
            postedItems[i + MAX_ITEMS] = item;
            postItem(itemsTarget, item);
        }
        sendCommand(itemsTarget, "reconnect now");
        assertTrue("Waiting to receive all events has timed out.", latch.await((1 + MAX_LISTENERS * (MAX_ITEMS + 1) * reconnectDelay) * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
        // need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection
        sendCommand(itemsTarget, "disconnect");
    } finally {
        close(sources);
    }
    final String storedItems = itemsTarget.request().get(String.class);
    for (String item : postedItems) {
        assertThat("Posted item '" + item + "' stored on server", storedItems, containsString(item));
    }
    int sourceId = 0;
    for (Queue<String> queue : receivedQueues) {
        assertThat("Received events in source " + sourceId, queue, describedAs("Collection containing %0", hasItems(postedItems), Arrays.asList(postedItems).toString()));
        assertThat("Size of received queue for source " + sourceId, queue.size(), equalTo(postedItems.length));
        sourceId++;
    }
}
Also used : ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) 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) 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 12 with InboundEvent

use of org.glassfish.jersey.media.sse.InboundEvent in project Hystrix by Netflix.

the class HystricsMetricsControllerTest method validateStream.

private void validateStream(EventInput eventInput, long waitTime) {
    long timeElapsed = System.currentTimeMillis();
    while (!eventInput.isClosed() && System.currentTimeMillis() - timeElapsed < waitTime) {
        final InboundEvent inboundEvent = eventInput.read();
        if (inboundEvent == null) {
            Assert.fail("Failed while verifying stream. Looks like connection has been closed.");
            break;
        }
        String data = inboundEvent.readData(String.class);
        System.out.println(data);
        if (isStreamValid(data)) {
            return;
        }
    }
    Assert.fail("Failed while verifying stream");
}
Also used : InboundEvent(org.glassfish.jersey.media.sse.InboundEvent)

Aggregations

InboundEvent (org.glassfish.jersey.media.sse.InboundEvent)12 CountDownLatch (java.util.concurrent.CountDownLatch)11 Test (org.junit.Test)11 EventSource (org.glassfish.jersey.media.sse.EventSource)10 JerseyTest (org.glassfish.jersey.test.JerseyTest)10 WebTarget (javax.ws.rs.client.WebTarget)8 EventListener (org.glassfish.jersey.media.sse.EventListener)8 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 SseFeature (org.glassfish.jersey.media.sse.SseFeature)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2 LinkedList (java.util.LinkedList)1