/
AtmosphereResourceImpl.java
438 lines (377 loc) · 14.3 KB
/
AtmosphereResourceImpl.java
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package org.atmosphere.cpr;
import org.atmosphere.cpr.AtmosphereServlet.Action;
import org.atmosphere.cpr.AtmosphereServlet.AtmosphereConfig;
import org.atmosphere.util.LoggerUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
/**
* {@link AtmosphereResource} implementation for supporting {@link HttpServletRequest}
* and {@link HttpServletResponse}.
*
* @author Jeanfrancois Arcand
*/
public class AtmosphereResourceImpl implements
AtmosphereResource<HttpServletRequest, HttpServletResponse>, AtmosphereEventLifecycle {
public final static String PRE_SUSPEND = AtmosphereResourceImpl.class.getName() + ".preSuspend";
// The {@link HttpServletRequest}
private final HttpServletRequest req;
// The {@link HttpServletResponse}
private final HttpServletResponse res;
// The upcoming Action.
protected final AtmosphereServlet.Action action = new AtmosphereServlet.Action();
// The Broadcaster
protected Broadcaster broadcaster;
// ServletContext
private final AtmosphereConfig config;
protected final CometSupport cometSupport;
private Serializer serializer;
private boolean isInScope = true;
private final AtmosphereResourceEventImpl event;
private final static String beginCompatibleData = createCompatibleStringJunk();
private boolean useWriter = true;
private final ConcurrentLinkedQueue<AtmosphereResourceEventListener> listeners =
new ConcurrentLinkedQueue<AtmosphereResourceEventListener>();
private final AtomicBoolean isSuspendEvent = new AtomicBoolean(false);
/**
* Create an {@link AtmosphereResource}.
*
* @param config The {@link AtmosphereConfig}
* @param broadcaster The {@link Broadcaster}.
* @param req The {@link HttpServletRequest}
* @param res The {@link HttpServletResponse}
* @param cometSupport The {@link CometSupport}
*/
public AtmosphereResourceImpl(AtmosphereConfig config, Broadcaster broadcaster,
HttpServletRequest req, HttpServletResponse res,
CometSupport cometSupport) {
this.req = req;
this.res = res;
this.broadcaster = broadcaster;
this.config = config;
this.cometSupport = cometSupport;
this.event = new AtmosphereResourceEventImpl(this);
}
/**
* {@inheritDoc}
*/
public AtmosphereResourceEventImpl getAtmosphereResourceEvent() {
return event;
}
/**
* {@inheritDoc}
*/
public void resume() {
if (!event.isResuming() && !event.isResumedOnTimeout() && event.isSuspended() && isInScope) {
action.type = AtmosphereServlet.Action.TYPE.RESUME;
notifyListeners();
listeners.clear();
broadcaster.removeAtmosphereResource(this);
try {
req.setAttribute(AtmosphereServlet.RESUMED_ON_TIMEOUT, Boolean.FALSE);
} catch (Exception ex) {
if (LoggerUtils.getLogger().isLoggable(Level.FINE)){
LoggerUtils.getLogger().fine("Cannot resume an already resumed/cancelled request ");
}
}
cometSupport.action(this);
} else {
if (LoggerUtils.getLogger().isLoggable(Level.FINE)){
LoggerUtils.getLogger().fine("Cannot resume an already resumed/cancelled request ");
}
}
}
/**
* {@inheritDoc}
*/
public void suspend() {
suspend(-1);
}
/**
* {@inheritDoc}
*/
public void suspend(long timeout) {
suspend(timeout, true);
}
public void suspend(long timeout, boolean flushComment) {
if (req.getSession(false) != null && req.getSession().getMaxInactiveInterval() != -1 && req.getSession().getMaxInactiveInterval() < timeout) {
throw new IllegalStateException("Cannot suspend a " +
"response longer than the session timeout. Increase the value of session-timeout in web.xml");
}
if (!event.isResumedOnTimeout()) {
String upgrade = req.getHeader("Connection");
if (upgrade != null && upgrade.equalsIgnoreCase("Upgrade")) {
if (!cometSupport.supportWebSocket()) {
res.addHeader("X-Atmosphere-error","Websocket protocol not supported");
} else {
flushComment = false;
}
}
// Set to expire far in the past.
res.setHeader("Expires", "-1");
// Set standard HTTP/1.1 no-cache headers.
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set standard HTTP/1.0 no-cache header.
res.setHeader("Pragma", "no-cache");
if (flushComment) {
write();
}
req.setAttribute(PRE_SUSPEND, "true");
action.type = AtmosphereServlet.Action.TYPE.SUSPEND;
action.timeout = timeout;
// TODO: We can possibly optimize that call by avoiding creating a Broadcaster if we are sure the Broadcaster
// is unique.
if (broadcaster.getScope() == Broadcaster.SCOPE.REQUEST) {
String id = broadcaster.getID();
Class<? extends Broadcaster> clazz = broadcaster.getClass();
broadcaster = BroadcasterFactory.getDefault().lookup(clazz, id, false);
if (broadcaster == null) {
broadcaster = BroadcasterFactory.getDefault().lookup(clazz, id + "/" + UUID.randomUUID(), true);
}
}
broadcaster.addAtmosphereResource(this);
req.removeAttribute(PRE_SUSPEND);
notifyListeners();
}
}
void write() {
try {
if (useWriter && !((Boolean) req.getAttribute(AtmosphereServlet.PROPERTY_USE_STREAM))) {
try {
res.getWriter();
} catch (IllegalStateException e) {
return;
}
res.getWriter().write(beginCompatibleData);
res.getWriter().flush();
} else {
try {
res.getOutputStream();
} catch (IllegalStateException e) {
return;
}
res.getOutputStream().write(beginCompatibleData.getBytes());
res.getOutputStream().flush();
}
} catch (Throwable ex) {
LoggerUtils.getLogger().log(Level.WARNING, "", ex);
}
}
/**
* {@inheritDoc}
*/
public HttpServletRequest getRequest() {
if (!isInScope)
throw new IllegalStateException("Request object no longer" +
" valid. This object has been cancelled");
return req;
}
/**
* {@inheritDoc}
*/
public HttpServletResponse getResponse() {
if (!isInScope)
throw new IllegalStateException("Response object no longer" +
" valid. This object has been cancelled");
return res;
}
/**
* {@inheritDoc}
*/
public Broadcaster getBroadcaster() {
return broadcaster;
}
/**
* {@inheritDoc}
*/
public void setBroadcaster(Broadcaster broadcaster) {
this.broadcaster = broadcaster;
}
/**
* {@inheritDoc}
*/
public AtmosphereConfig getAtmosphereConfig() {
return config;
}
/**
* Return the {@link Action} which represent the state of the response,
* e.g. suspended, resumed or timedout.
*
* @return the {@link Action}
*/
public Action action() {
return action;
}
/**
* Protect the object for being used after it got cancelled.
*
* @param isInScope
*/
protected void setIsInScope(boolean isInScope) {
this.isInScope = isInScope;
}
/**
* Is the {@link HttpServletRequest} still valid.
* @return true if the {@link HttpServletRequest} still vali
*/
public boolean isInScope(){
return isInScope;
}
/**
* Set the {@link Serializer} used to write broadcasted object.
*
* @param s
*/
public void setSerializer(Serializer s) {
serializer = s;
}
/**
* Write the broadcasted object using the {@link OutputStream}. If a
* {@link Serializer} is defined, the operation will be delagated to it. If
* not, the <F> (Response) OutputStream will be used by calling
* Object.toString.getBytes()
*
* @param os an {@link OutputStream}
* @param o an Object
* @throws IOException
*/
public void write(OutputStream os, Object o) throws IOException {
if (o == null) throw new IllegalStateException("Object cannot be null");
if (serializer != null) {
serializer.write(os, o);
} else {
res.getOutputStream().write(o.toString().getBytes());
}
}
/**
* {@inheritDoc}
*/
public Serializer getSerializer() {
return serializer;
}
/**
* Output message when Atmosphere suspend a connection.
*
* @return message when Atmosphere suspend a connection.
*/
public static String createCompatibleStringJunk() {
StringBuilder s = new StringBuilder();
s.append("<!-- ----------------------------------------------------------" +
"---------------------------------------------------------------" +
"-------------------------------------------- -->\n");
s.append("<!-- Welcome to the Atmosphere Framework. To work with all the" +
" browsers when suspending connection, Atmosphere must output some" +
" data to makes WebKit based browser working.-->\n");
for (int i = 0; i < 10; i++) {
s.append("<!-- ----------------------------------------------------------" +
"---------------------------------------------------------------" +
"-------------------------------------------- -->\n");
}
return s.toString();
}
/**
* Add a {@link AtmosphereResourceEventListener}.
*
* @param e an instance of AtmosphereResourceEventListener
*/
public void addEventListener(AtmosphereResourceEventListener e) {
if (listeners.contains(e)) return;
listeners.add(e);
}
/**
* Add a {@link AtmosphereResourceEventListener}.
*
* @param e an instance of AtmosphereResourceEventListener
*/
public void removeEventListener(AtmosphereResourceEventListener e) {
listeners.remove(e);
}
/**
* Remove all {@link AtmosphereResourceEventListener}.
*/
public void removeEventListeners() {
listeners.clear();
}
/**
* Notify {@link AtmosphereResourceEventListener}.
*/
public void notifyListeners() {
notifyListeners(event);
}
/**
* Notify {@link AtmosphereResourceEventListener}.
*/
public void notifyListeners(AtmosphereResourceEvent event) {
if (event.isResuming() || event.isResumedOnTimeout()) {
onResume(event);
} else if (event.isCancelled()) {
onDisconnect(event);
} else if (!isSuspendEvent.getAndSet(true) && event.isSuspended()){
onSuspend(event);
} else {
onBroadcast(event);
}
}
void onSuspend(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> e) {
for (AtmosphereResourceEventListener r : listeners) {
r.onSuspend(e);
}
}
void onResume(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> e) {
for (AtmosphereResourceEventListener r : listeners) {
r.onResume(e);
}
}
void onDisconnect(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> e) {
for (AtmosphereResourceEventListener r : listeners) {
r.onDisconnect(e);
}
}
void onBroadcast(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> e) {
for (AtmosphereResourceEventListener r : listeners) {
r.onBroadcast(e);
}
}
}