final AsyncContext asyncContext = request.startAsync();
asyncContext.setTimeout(getSSETimeout());
queue.setTimeout(getSSETimeout() + 5000);
asyncContext.addListener(new AsyncListener() {
@Override
public void onComplete(final AsyncEvent event) throws IOException {
synchronized (queue.getActivationLock()) {
queue.setActivationCallback(null);
asyncContext.complete();
}
}
@Override
public void onTimeout(final AsyncEvent event) throws IOException {
onComplete(event);
}
@Override
public void onError(final AsyncEvent event) throws IOException {
queue.setActivationCallback(null);
}
@Override
public void onStartAsync(final AsyncEvent event) throws IOException {
}
});
synchronized (queue.getActivationLock()) {
if (queue.messagesWaiting()) {
queue.poll(writer);
writer.write(SSE_TERMINATION_BYTES);
}
queue.setActivationCallback(new QueueActivationCallback() {
@Override
public void activate(final MessageQueue queue) {
try {
queue.setActivationCallback(null);
queue.poll(writer);
writer.write(SSE_TERMINATION_BYTES);
queue.heartBeat();
writer.flush();
prepareSSEContinue(response);
}
catch (final Throwable t) {
try {
writeExceptionToOutputStream((HttpServletResponse) asyncContext.getResponse(), t);
}
catch (IOException e) {
throw new RuntimeException("Failed to write exception to output stream", e);
}
}
}
});
writer.flush();
}
}
else {
final AsyncContext asyncContext = request.startAsync();
asyncContext.setTimeout(60000);
queue.setTimeout(65000);
asyncContext.addListener(new AsyncListener() {
@Override
public void onComplete(final AsyncEvent event) throws IOException {
synchronized (queue.getActivationLock()) {
queue.setActivationCallback(null);
asyncContext.complete();