use of org.glassfish.jersey.media.sse.InboundEvent 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());
}
use of org.glassfish.jersey.media.sse.InboundEvent 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();
}
use of org.glassfish.jersey.media.sse.InboundEvent 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());
}
use of org.glassfish.jersey.media.sse.InboundEvent in project jersey by jersey.
the class ServerSentEventsTest method testEventSource.
/**
* Test consuming a single SSE event via event source.
*
* @throws Exception in case of a failure during the test execution.
*/
@Test
public void testEventSource() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<String> message = new AtomicReference<String>();
final EventSource eventSource = new EventSource(target().path(App.ROOT_PATH)) {
@Override
public void onEvent(InboundEvent inboundEvent) {
try {
final String value = inboundEvent.readData();
message.set(value);
latch.countDown();
} catch (ProcessingException e) {
e.printStackTrace();
}
}
};
target().path(App.ROOT_PATH).request().post(Entity.text("message"));
try {
assertTrue("Waiting for message to be delivered has timed out.", latch.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
} finally {
eventSource.close();
}
assertThat("Unexpected SSE event data value.", message.get(), equalTo("message"));
}
use of org.glassfish.jersey.media.sse.InboundEvent 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);
}
Aggregations