-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathEventSourceChannelHandler.java
More file actions
172 lines (155 loc) · 6.48 KB
/
EventSourceChannelHandler.java
File metadata and controls
172 lines (155 loc) · 6.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package com.github.eventsource.client.impl.netty;
import com.github.eventsource.client.EventSourceException;
import com.github.eventsource.client.EventSourceHandler;
import com.github.eventsource.client.impl.ConnectionHandler;
import com.github.eventsource.client.impl.EventStreamParser;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EventSourceChannelHandler extends SimpleChannelUpstreamHandler implements ConnectionHandler {
private static final Pattern STATUS_PATTERN = Pattern.compile("HTTP/1.1 (\\d+) (.*)");
private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile("Content-Type: text/event-stream");
private final EventSourceHandler eventSourceHandler;
private final ClientBootstrap bootstrap;
private final URI uri;
private final EventStreamParser messageDispatcher;
private final Timer timer = new HashedWheelTimer();
private Channel channel;
private boolean reconnectOnClose = true;
private long reconnectionTimeMillis;
private String lastEventId;
private boolean eventStreamOk;
private boolean headerDone;
private Integer status;
private AtomicBoolean reconnecting = new AtomicBoolean(false);
public EventSourceChannelHandler(EventSourceHandler eventSourceHandler, long reconnectionTimeMillis, ClientBootstrap bootstrap, URI uri) {
this.eventSourceHandler = eventSourceHandler;
this.reconnectionTimeMillis = reconnectionTimeMillis;
this.bootstrap = bootstrap;
this.uri = uri;
this.messageDispatcher = new EventStreamParser(uri.toString(), eventSourceHandler, this);
}
@Override
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
super.handleUpstream(ctx, e);
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toString());
request.addHeader(Names.ACCEPT, "text/event-stream");
request.addHeader(Names.HOST, uri.getHost());
request.addHeader(Names.ORIGIN, uri.getScheme()+"://" + uri.getHost());
request.addHeader(Names.CACHE_CONTROL, "no-cache");
if (lastEventId != null) {
request.addHeader("Last-Event-ID", lastEventId);
}
e.getChannel().write(request);
channel = e.getChannel();
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channel = null;
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
eventSourceHandler.onClosed(reconnectOnClose);
if (reconnectOnClose) {
reconnect();
}
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
String line = (String) e.getMessage();
if (status == null) {
Matcher statusMatcher = STATUS_PATTERN.matcher(line);
if (statusMatcher.matches()) {
status = Integer.parseInt(statusMatcher.group(1));
if (status != 200) {
eventSourceHandler.onError(new EventSourceException("Bad status from " + uri + ": " + status));
reconnect();
}
return;
} else {
eventSourceHandler.onError(new EventSourceException("Not HTTP? " + uri + ": " + line));
reconnect();
}
}
if (!headerDone) {
if (CONTENT_TYPE_PATTERN.matcher(line).matches()) {
eventStreamOk = true;
}
if (line.isEmpty()) {
headerDone = true;
if (eventStreamOk) {
eventSourceHandler.onConnect();
} else {
eventSourceHandler.onError(new EventSourceException("Not event stream: " + uri + " (expected Content-Type: text/event-stream"));
reconnect();
}
}
} else {
messageDispatcher.line(line);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
Throwable error = e.getCause();
if(error instanceof ConnectException) {
error = new EventSourceException("Failed to connect to " + uri, error);
}
eventSourceHandler.onError(error);
ctx.getChannel().close();
}
public void setReconnectionTimeMillis(long reconnectionTimeMillis) {
this.reconnectionTimeMillis = reconnectionTimeMillis;
}
@Override
public void setLastEventId(String lastEventId) {
this.lastEventId = lastEventId;
}
public EventSourceChannelHandler close() {
reconnectOnClose = false;
if (channel != null) {
channel.close();
}
return this;
}
public EventSourceChannelHandler join() throws InterruptedException {
if (channel != null) {
channel.getCloseFuture().await();
}
return this;
}
private void reconnect() {
if(!reconnecting.get()) {
reconnecting.set(true);
timer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
reconnecting.set(false);
int port = uri.getPort();
if (port==-1) {
port = (uri.getScheme().equals("https"))?443:80;
}
bootstrap.setOption("remoteAddress", new InetSocketAddress(uri.getHost(), port));
bootstrap.connect().await();
}
}, reconnectionTimeMillis, TimeUnit.MILLISECONDS);
}
}
}