/
AtmosphereFramework.java
2932 lines (2573 loc) · 112 KB
/
AtmosphereFramework.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.cpr;
import org.atmosphere.annotation.Processor;
import org.atmosphere.cache.BroadcasterCacheInspector;
import org.atmosphere.cache.DefaultBroadcasterCache;
import org.atmosphere.cache.UUIDBroadcasterCache;
import org.atmosphere.config.ApplicationConfiguration;
import org.atmosphere.config.AtmosphereHandlerConfig;
import org.atmosphere.config.AtmosphereHandlerProperty;
import org.atmosphere.config.FrameworkConfiguration;
import org.atmosphere.container.BlockingIOCometSupport;
import org.atmosphere.container.Tomcat7BIOSupportWithWebSocket;
import org.atmosphere.handler.AbstractReflectorAtmosphereHandler;
import org.atmosphere.handler.ReflectorServletProcessor;
import org.atmosphere.interceptor.AndroidAtmosphereInterceptor;
import org.atmosphere.interceptor.CacheHeadersInterceptor;
import org.atmosphere.interceptor.CorsInterceptor;
import org.atmosphere.interceptor.HeartbeatInterceptor;
import org.atmosphere.interceptor.IdleResourceInterceptor;
import org.atmosphere.interceptor.InvokationOrder;
import org.atmosphere.interceptor.JSONPAtmosphereInterceptor;
import org.atmosphere.interceptor.JavaScriptProtocol;
import org.atmosphere.interceptor.OnDisconnectInterceptor;
import org.atmosphere.interceptor.PaddingAtmosphereInterceptor;
import org.atmosphere.interceptor.SSEAtmosphereInterceptor;
import org.atmosphere.interceptor.WebSocketMessageSuspendInterceptor;
import org.atmosphere.util.AtmosphereConfigReader;
import org.atmosphere.util.DefaultEndpointMapper;
import org.atmosphere.util.EndpointMapper;
import org.atmosphere.util.IOUtils;
import org.atmosphere.util.IntrospectionUtils;
import org.atmosphere.util.ServletContextFactory;
import org.atmosphere.util.ServletProxyFactory;
import org.atmosphere.util.Version;
import org.atmosphere.util.analytics.FocusPoint;
import org.atmosphere.util.analytics.JGoogleAnalyticsTracker;
import org.atmosphere.util.analytics.ModuleDetection;
import org.atmosphere.websocket.DefaultWebSocketProcessor;
import org.atmosphere.websocket.WebSocket;
import org.atmosphere.websocket.WebSocketHandler;
import org.atmosphere.websocket.WebSocketProcessor;
import org.atmosphere.websocket.WebSocketProtocol;
import org.atmosphere.websocket.protocol.SimpleHttpProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.atmosphere.cpr.ApplicationConfig.ALLOW_QUERYSTRING_AS_REQUEST;
import static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER;
import static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_MAPPING;
import static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_PATH;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CLASS;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_FACTORY;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_LIFECYCLE_POLICY;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_WAIT_TIME;
import static org.atmosphere.cpr.ApplicationConfig.BROADCAST_FILTER_CLASSES;
import static org.atmosphere.cpr.ApplicationConfig.DISABLE_ONSTATE_EVENT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ATMOSPHERE_XML;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_BLOCKING_COMETSUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_COMET_SUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_NATIVE_COMETSUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SERVLET_MAPPING;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_SUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_THROW_EXCEPTION_ON_CLONED_REQUEST;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM;
import static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROCESSOR;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_SUPPORT;
import static org.atmosphere.cpr.Broadcaster.ROOT_MASTER;
import static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_CONFIG;
import static org.atmosphere.cpr.FrameworkConfig.CDI_INJECTOR;
import static org.atmosphere.cpr.FrameworkConfig.GUICE_INJECTOR;
import static org.atmosphere.cpr.FrameworkConfig.HAZELCAST_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.JERSEY_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.JERSEY_CONTAINER;
import static org.atmosphere.cpr.FrameworkConfig.JGROUPS_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.JMS_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.RABBITMQ_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.REDIS_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.RMI_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.SPRING_INJECTOR;
import static org.atmosphere.cpr.FrameworkConfig.XMPP_BROADCASTER;
import static org.atmosphere.cpr.HeaderConfig.ATMOSPHERE_POST_BODY;
import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRACKING_ID;
import static org.atmosphere.util.IOUtils.realPath;
import static org.atmosphere.websocket.WebSocket.WEBSOCKET_SUSPEND;
/**
* The {@link AtmosphereFramework} is the entry point for the framework. This class can be used to from Servlet/filter
* to dispatch {@link AtmosphereRequest} and {@link AtmosphereResponse}. The framework can also be configured using
* the setXXX method. The life cycle of this class is
* <blockquote><pre>
* AtmosphereFramework f = new AtmosphereFramework();
* f.init();
* f.doCometSupport(AtmosphereRequest, AtmosphereResource);
* f.destroy();
* </pre></blockquote>
*
* @author Jeanfrancois Arcand
*/
public class AtmosphereFramework {
public static final String DEFAULT_ATMOSPHERE_CONFIG_PATH = "/META-INF/atmosphere.xml";
public static final String DEFAULT_LIB_PATH = "/WEB-INF/lib/";
public static final String DEFAULT_HANDLER_PATH = "/WEB-INF/classes/";
public static final String MAPPING_REGEX = "[a-zA-Z0-9-&.*_~=@;\\?]+";
protected static final Logger logger = LoggerFactory.getLogger(AtmosphereFramework.class);
protected final List<String> broadcasterFilters = new ArrayList<String>();
protected final List<AsyncSupportListener> asyncSupportListeners = new ArrayList<AsyncSupportListener>();
protected final ArrayList<String> possibleComponentsCandidate = new ArrayList<String>();
protected final HashMap<String, String> initParams = new HashMap<String, String>();
protected final AtmosphereConfig config;
protected final AtomicBoolean isCometSupportConfigured = new AtomicBoolean(false);
protected final boolean isFilter;
protected final Map<String, AtmosphereHandlerWrapper> atmosphereHandlers = new ConcurrentHashMap<String, AtmosphereHandlerWrapper>();
protected final ConcurrentLinkedQueue<String> broadcasterTypes = new ConcurrentLinkedQueue<String>();
protected final ConcurrentLinkedQueue<String> objectFactoryType = new ConcurrentLinkedQueue<String>();
protected final ConcurrentLinkedQueue<BroadcasterCacheInspector> inspectors = new ConcurrentLinkedQueue<BroadcasterCacheInspector>();
protected String mappingRegex = MAPPING_REGEX;
protected boolean useNativeImplementation = false;
protected boolean useBlockingImplementation = false;
protected boolean useStreamForFlushingComments = true;
protected boolean useServlet30 = true;
protected AsyncSupport asyncSupport;
protected String broadcasterClassName = DefaultBroadcaster.class.getName();
protected boolean isCometSupportSpecified = false;
protected boolean isBroadcasterSpecified = false;
protected boolean isSessionSupportSpecified = false;
protected boolean isThrowExceptionOnClonedRequestSpecified = false;
protected BroadcasterFactory broadcasterFactory;
protected String broadcasterFactoryClassName;
protected String broadcasterCacheClassName;
protected boolean webSocketEnabled = true;
protected String broadcasterLifeCyclePolicy = "NEVER";
protected String webSocketProtocolClassName = SimpleHttpProtocol.class.getName();
protected WebSocketProtocol webSocketProtocol;
protected String handlersPath = DEFAULT_HANDLER_PATH;
protected ServletConfig servletConfig;
protected boolean autoDetectHandlers = true;
private boolean hasNewWebSocketProtocol = false;
protected String atmosphereDotXmlPath = DEFAULT_ATMOSPHERE_CONFIG_PATH;
protected final LinkedList<AtmosphereInterceptor> interceptors = new LinkedList<AtmosphereInterceptor>();
protected boolean scanDone = false;
protected String annotationProcessorClassName = "org.atmosphere.cpr.DefaultAnnotationProcessor";
protected final List<BroadcasterListener> broadcasterListeners = new ArrayList<BroadcasterListener>();
protected String webSocketProcessorClassName = DefaultWebSocketProcessor.class.getName();
protected boolean webSocketProtocolInitialized = false;
protected EndpointMapper<AtmosphereHandlerWrapper> endpointMapper = new DefaultEndpointMapper<AtmosphereHandlerWrapper>();
protected String libPath = DEFAULT_LIB_PATH;
protected boolean isInit;
protected boolean sharedThreadPools = true;
protected final List<String> packages = new ArrayList<String>();
protected final LinkedList<String> annotationPackages = new LinkedList<String>();
protected boolean allowAllClassesScan = true;
protected boolean annotationFound = false;
protected boolean executeFirstSet = false;
protected AtmosphereObjectFactory objectFactory = new DefaultAtmosphereObjectFactory();
protected final AtomicBoolean isDestroyed = new AtomicBoolean();
protected boolean externalizeDestroy = false;
protected AnnotationProcessor annotationProcessor = null;
protected final List<String> excludedInterceptors = new ArrayList<String>();
protected final LinkedList<BroadcasterCacheListener> broadcasterCacheListeners = new LinkedList<BroadcasterCacheListener>();
protected final List<BroadcasterConfig.FilterManipulator> filterManipulators = new ArrayList<BroadcasterConfig.FilterManipulator>();
protected AtmosphereResourceFactory arFactory;
protected MetaBroadcaster metaBroadcaster;
protected final Class<? extends AtmosphereInterceptor>[] defaultInterceptors = new Class[]{
// Add CORS support
CorsInterceptor.class,
// Default Interceptor
CacheHeadersInterceptor.class,
// WebKit & IE Padding
PaddingAtmosphereInterceptor.class,
// Android 2.3.x streaming support
AndroidAtmosphereInterceptor.class,
// Heartbeat
HeartbeatInterceptor.class,
// Add SSE support
SSEAtmosphereInterceptor.class,
// ADD JSONP support
JSONPAtmosphereInterceptor.class,
// ADD Tracking ID Handshake
JavaScriptProtocol.class,
// WebSocket and suspend
WebSocketMessageSuspendInterceptor.class,
// OnDisconnect
OnDisconnectInterceptor.class,
// Idle connection
IdleResourceInterceptor.class
};
/**
* An implementation of {@link AbstractReflectorAtmosphereHandler}.
*/
public final static AtmosphereHandler REFLECTOR_ATMOSPHEREHANDLER = new AbstractReflectorAtmosphereHandler() {
@Override
public void onRequest(AtmosphereResource resource) throws IOException {
logger.trace("VoidHandler", resource.uuid());
}
@Override
public void destroy() {
logger.trace("VoidHandler");
}
};
public static final class AtmosphereHandlerWrapper {
public final AtmosphereHandler atmosphereHandler;
public Broadcaster broadcaster;
public String mapping;
public LinkedList<AtmosphereInterceptor> interceptors = new LinkedList<AtmosphereInterceptor>();
public boolean create;
public AtmosphereHandlerWrapper(BroadcasterFactory broadcasterFactory, AtmosphereHandler atmosphereHandler, String mapping) {
this.atmosphereHandler = atmosphereHandler;
try {
if (broadcasterFactory != null) {
this.broadcaster = broadcasterFactory.lookup(mapping, true);
} else {
this.mapping = mapping;
}
} catch (Exception t) {
throw new RuntimeException(t);
}
}
public AtmosphereHandlerWrapper(AtmosphereHandler atmosphereHandler, Broadcaster broadcaster) {
this.atmosphereHandler = atmosphereHandler;
this.broadcaster = broadcaster;
}
@Override
public String toString() {
return "AtmosphereHandlerWrapper{ atmosphereHandler=" + atmosphereHandler + ", broadcaster=" +
broadcaster + " }";
}
}
/**
* <p>
* This enumeration represents all possible actions to specify in a meta service file.
* </p>
*
* @author Guillaume DROUET
* @version 1.0
* @since 2.2.0
*/
public static enum MetaServiceAction {
/**
* Install service.
*/
INSTALL(new InstallMetaServiceProcedure()),
/**
* Exclude service.
*/
EXCLUDE(new ExcludeMetaServiceProcedure());
/**
* The procedure to apply.
*/
private MetaServiceProcedure procedure;
/**
* <p>
* Builds a new instance.
* </p>
*
* @param p the enum procedure
*/
private MetaServiceAction(final MetaServiceProcedure p) {
procedure = p;
}
/**
* <p>
* Applies this action to given class.
* </p>
*
* @param fwk the framework
* @param clazz the class
* @throws Exception if procedure fails
*/
public void apply(final AtmosphereFramework fwk, final Class<?> clazz) throws Exception {
procedure.apply(fwk, clazz);
}
/**
* <p>
* This interface defined a method with a signature like a procedure to process an action.
* </p>
*
* @author Guillaume DROUET
* @version 1.0
* @since 2.2.0
*/
private static interface MetaServiceProcedure {
/**
* <p>
* Processes an action.
* </p>
*
* @param fwk the framework
* @param clazz the class to use during processing
* @throws Exception if procedure fails
*/
void apply(final AtmosphereFramework fwk, final Class<?> clazz) throws Exception;
}
/**
* <p>
* Install the classes.
* </p>
*
* @author Guillaume DROUET
* @version 1.0
* @since 2.2.0
*/
private static class InstallMetaServiceProcedure implements MetaServiceProcedure {
/**
* {@inheritDoc}
*/
@Override
public void apply(final AtmosphereFramework fwk, final Class c) throws Exception {
if (AtmosphereInterceptor.class.isAssignableFrom(c)) {
fwk.interceptor(fwk.newClassInstance(AtmosphereInterceptor.class, c));
} else if (Broadcaster.class.isAssignableFrom(c)) {
fwk.setDefaultBroadcasterClassName(c.getName());
} else if (BroadcasterListener.class.isAssignableFrom(c)) {
fwk.addBroadcasterListener(fwk.newClassInstance(BroadcasterListener.class, c));
} else if (BroadcasterCache.class.isAssignableFrom(c)) {
fwk.setBroadcasterCacheClassName(c.getName());
} else if (BroadcastFilter.class.isAssignableFrom(c)) {
fwk.broadcasterFilters.add(c.getName());
} else if (BroadcasterCacheInspector.class.isAssignableFrom(c)) {
fwk.inspectors.add(fwk.newClassInstance(BroadcasterCacheInspector.class, c));
} else if (AsyncSupportListener.class.isAssignableFrom(c)) {
fwk.asyncSupportListeners.add(fwk.newClassInstance(AsyncSupportListener.class, c));
} else if (AsyncSupport.class.isAssignableFrom(c)) {
fwk.setAsyncSupport(fwk.newClassInstance(AsyncSupport.class, c));
} else if (BroadcasterCacheListener.class.isAssignableFrom(c)) {
fwk.broadcasterCacheListeners.add(fwk.newClassInstance(BroadcasterCacheListener.class, c));
} else if (BroadcasterConfig.FilterManipulator.class.isAssignableFrom(c)) {
fwk.filterManipulators.add(fwk.newClassInstance(BroadcasterConfig.FilterManipulator.class, c));
} else if (WebSocketProtocol.class.isAssignableFrom(c)) {
fwk.webSocketProtocolClassName = WebSocketProtocol.class.getName();
} else if (WebSocketProcessor.class.isAssignableFrom(c)) {
fwk.webSocketProcessorClassName = WebSocketProcessor.class.getName();
} else {
logger.warn("{} is not a framework service that could be installed", c.getName());
}
}
}
/**
* <p>
* Exclude the services.
* </p>
*
* @author Guillaume DROUET
* @version 1.0
* @since 2.2.0
*/
private static class ExcludeMetaServiceProcedure implements MetaServiceProcedure {
/**
* {@inheritDoc}
*/
@Override
public void apply(final AtmosphereFramework fwk, final Class<?> c) {
if (AtmosphereInterceptor.class.isAssignableFrom(c)) {
fwk.excludeInterceptor(c.getName());
} else {
logger.warn("{} is not a framework service that could be excluded, pull request is welcome ;-)", c.getName());
}
}
}
}
public static class DefaultAtmosphereObjectFactory implements AtmosphereObjectFactory {
public String toString() {
return "DefaultAtmosphereObjectFactory";
}
@Override
public <T, U extends T> U newClassInstance(AtmosphereFramework framework,
Class<T> classType,
Class<U> defaultType) throws InstantiationException, IllegalAccessException {
return defaultType.newInstance();
}
}
/**
* Create an AtmosphereFramework.
*/
public AtmosphereFramework() {
this(false, true);
}
/**
* Create an AtmosphereFramework and initialize it via {@link AtmosphereFramework#init(javax.servlet.ServletConfig)}.
*/
public AtmosphereFramework(ServletConfig sc) throws ServletException {
this(false, true);
// TODO: What?
init(sc);
}
/**
* Create an AtmosphereFramework.
*
* @param isFilter true if this instance is used as an {@link AtmosphereFilter}
*/
public AtmosphereFramework(boolean isFilter, boolean autoDetectHandlers) {
this.isFilter = isFilter;
this.autoDetectHandlers = autoDetectHandlers;
config = new AtmosphereConfig(this);
}
/**
* The order of addition is quite important here.
*/
private void populateBroadcasterType() {
broadcasterTypes.add(HAZELCAST_BROADCASTER);
broadcasterTypes.add(XMPP_BROADCASTER);
broadcasterTypes.add(REDIS_BROADCASTER);
broadcasterTypes.add(JGROUPS_BROADCASTER);
broadcasterTypes.add(JMS_BROADCASTER);
broadcasterTypes.add(RMI_BROADCASTER);
broadcasterTypes.add(RABBITMQ_BROADCASTER);
}
/**
* The order of addition is quite important here.
*/
private void populateObjectFactoryType() {
objectFactoryType.add(CDI_INJECTOR);
objectFactoryType.add(SPRING_INJECTOR);
objectFactoryType.add(GUICE_INJECTOR);
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param l An array of {@link AtmosphereInterceptor}.
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, List<AtmosphereInterceptor> l) {
if (!mapping.startsWith("/")) {
mapping = "/" + mapping;
}
AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(broadcasterFactory, h, mapping);
w.interceptors = LinkedList.class.isAssignableFrom(l.getClass()) ? LinkedList.class.cast(l) : new LinkedList<AtmosphereInterceptor>(l);
addMapping(mapping, w);
if (isInit) {
try {
if (h instanceof AtmosphereServletProcessor) {
((AtmosphereServletProcessor) h).init(config);
}
} catch (ServletException e) {
throw new RuntimeException(e);
}
initHandlerInterceptors(w.interceptors);
} else {
logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", h.getClass().getName(), mapping);
logger.info("Installed the following AtmosphereInterceptor mapped to AtmosphereHandler {}", h.getClass().getName());
if (l.size() > 0) {
for (AtmosphereInterceptor s : l) {
logger.info("\t{} : {}", s.getClass().getName(), s);
}
}
}
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h) {
addAtmosphereHandler(mapping, h, Collections.<AtmosphereInterceptor>emptyList());
return this;
}
private AtmosphereFramework addMapping(String path, AtmosphereHandlerWrapper w) {
// We are using JAXRS mapping algorithm.
if (path.contains("*")) {
path = path.replace("*", mappingRegex);
}
if (path.endsWith("/")) {
path = path + mappingRegex;
}
atmosphereHandlers.put(path, w);
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcasterId The {@link Broadcaster#getID} value.
* @param l An attay of {@link AtmosphereInterceptor}
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId, List<AtmosphereInterceptor> l) {
if (!mapping.startsWith("/")) {
mapping = "/" + mapping;
}
AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(broadcasterFactory, h, mapping);
w.broadcaster.setID(broadcasterId);
w.interceptors = LinkedList.class.isAssignableFrom(l.getClass()) ? LinkedList.class.cast(l) : new LinkedList<AtmosphereInterceptor>(l);
addMapping(mapping, w);
logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", h.getClass().getName(), mapping);
if (l.size() > 0) {
logger.info("Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}", l, h.getClass().getName());
}
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcasterId The {@link Broadcaster#getID} value
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId) {
addAtmosphereHandler(mapping, h, broadcasterId, Collections.<AtmosphereInterceptor>emptyList());
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler
* @param l A list of {@link AtmosphereInterceptor}s
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster, List<AtmosphereInterceptor> l) {
if (!mapping.startsWith("/")) {
mapping = "/" + mapping;
}
AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(h, broadcaster);
w.interceptors = LinkedList.class.isAssignableFrom(l.getClass()) ? LinkedList.class.cast(l) : new LinkedList<AtmosphereInterceptor>(l);
addMapping(mapping, w);
if (!isInit) {
logger.info("Installed AtmosphereHandler {} mapped to context-path {} and Broadcaster Class {}",
new String[]{h.getClass().getName(), mapping, broadcaster.getClass().getName()});
} else {
logger.debug("Installed AtmosphereHandler {} mapped to context-path {} and Broadcaster Class {}",
new String[]{h.getClass().getName(), mapping, broadcaster.getClass().getName()});
}
if (l.size() > 0) {
logger.info("Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}", l, h.getClass().getName());
}
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler.
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster) {
addAtmosphereHandler(mapping, h, broadcaster, Collections.<AtmosphereInterceptor>emptyList());
return this;
}
/**
* Remove an {@link AtmosphereHandler}.
*
* @param mapping the mapping used when invoking {@link #addAtmosphereHandler(String, AtmosphereHandler)};
* @return true if removed
*/
public AtmosphereFramework removeAtmosphereHandler(String mapping) {
if (mapping.endsWith("/")) {
mapping += mappingRegex;
}
atmosphereHandlers.remove(mapping);
return this;
}
/**
* Remove all {@link AtmosphereHandler}s.
*/
public AtmosphereFramework removeAllAtmosphereHandler() {
atmosphereHandlers.clear();
return this;
}
/**
* Remove all init parameters.
*/
public AtmosphereFramework removeAllInitParams() {
initParams.clear();
return this;
}
/**
* Add init-param like if they were defined in web.xml
*
* @param name The name
* @param value The value
*/
public AtmosphereFramework addInitParameter(String name, String value) {
initParams.put(name, value);
return this;
}
protected void readSystemProperties() {
if (System.getProperty(PROPERTY_NATIVE_COMETSUPPORT) != null) {
useNativeImplementation = Boolean
.parseBoolean(System.getProperty(PROPERTY_NATIVE_COMETSUPPORT));
isCometSupportSpecified = true;
}
if (System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT) != null) {
useBlockingImplementation = Boolean
.parseBoolean(System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT));
isCometSupportSpecified = true;
}
atmosphereDotXmlPath = System.getProperty(PROPERTY_ATMOSPHERE_XML, atmosphereDotXmlPath);
if (System.getProperty(DISABLE_ONSTATE_EVENT) != null) {
initParams.put(DISABLE_ONSTATE_EVENT, System.getProperty(DISABLE_ONSTATE_EVENT));
}
}
/**
* Path specific container using their own property.
*/
public void patchContainer() {
System.setProperty("org.apache.catalina.STRICT_SERVLET_COMPLIANCE", "false");
}
/**
* Initialize the AtmosphereFramework. Invoke this method after having properly configured this class using the setters.
*/
public AtmosphereFramework init() {
try {
init(servletConfig == null ? new ServletConfig() {
@Override
public String getServletName() {
return "AtmosphereFramework";
}
@Override
public ServletContext getServletContext() {
return (ServletContext) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ServletContext.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return ServletProxyFactory.getDefault().proxy(proxy, method, args);
}
}
);
}
@Override
public String getInitParameter(String name) {
return initParams.get(name);
}
@Override
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(initParams.values());
}
} : servletConfig, false);
} catch (ServletException e) {
logger.error("", e);
}
return this;
}
/**
* Initialize the AtmosphereFramework using the {@link ServletContext}.
*
* @param sc the {@link ServletContext}
*/
public AtmosphereFramework init(final ServletConfig sc) throws ServletException {
return init(sc, true);
}
/**
* Prevent Atmosphere from scanning the entire class path.
*/
protected void preventOOM() {
String s = config.getInitParameter(ApplicationConfig.SCAN_CLASSPATH);
if (s != null) {
allowAllClassesScan = Boolean.parseBoolean(s);
}
try {
Class.forName("org.testng.Assert");
allowAllClassesScan = false;
} catch (ClassNotFoundException e) {
}
}
/**
* Initialize the AtmosphereFramework using the {@link ServletContext}.
*
* @param sc the {@link ServletContext}
*/
public AtmosphereFramework init(final ServletConfig sc, boolean wrap) throws ServletException {
if (isInit) return this;
readSystemProperties();
populateBroadcasterType();
populateObjectFactoryType();
loadMetaService();
try {
ServletConfig scFacade;
if (wrap) {
scFacade = new ServletConfig() {
AtomicBoolean done = new AtomicBoolean();
public String getServletName() {
return sc.getServletName();
}
public ServletContext getServletContext() {
return sc.getServletContext();
}
public String getInitParameter(String name) {
String param = initParams.get(name);
if (param == null) {
return sc.getInitParameter(name);
}
return param;
}
public Enumeration<String> getInitParameterNames() {
if (!done.getAndSet(true)) {
Enumeration en = sc.getInitParameterNames();
if (en != null) {
while (en.hasMoreElements()) {
String name = (String) en.nextElement();
if (!initParams.containsKey(name)) {
initParams.put(name, sc.getInitParameter(name));
}
}
}
}
return Collections.enumeration(initParams.keySet());
}
};
} else {
scFacade = sc;
}
this.servletConfig = scFacade;
ServletContextFactory.getDefault().init(sc.getServletContext());
preventOOM();
doInitParams(scFacade);
doInitParamsForWebSocket(scFacade);
objectFactory = lookupDefaultObjectFactoryType();
asyncSupportListener(newClassInstance(AsyncSupportListener.class, AsyncSupportListenerAdapter.class));
configureObjectFactory();
configureAnnotationPackages();
configureBroadcasterFactory();
configureScanningPackage(scFacade, ApplicationConfig.ANNOTATION_PACKAGE);
configureScanningPackage(scFacade, FrameworkConfig.JERSEY2_SCANNING_PACKAGE);
configureScanningPackage(scFacade, FrameworkConfig.JERSEY_SCANNING_PACKAGE);
// Force scanning of the packages defined.
defaultPackagesToScan();
installAnnotationProcessor(scFacade);
autoConfigureService(scFacade.getServletContext());
// Reconfigure in case an annotation changed the default.
configureBroadcasterFactory();
configureMetaBroadcaster();
patchContainer();
configureBroadcaster();
loadConfiguration(scFacade);
initWebSocket();
initEndpointMapper();
autoDetectContainer();
configureWebDotXmlAtmosphereHandler(scFacade);
asyncSupport.init(scFacade);
initAtmosphereHandler(scFacade);
configureAtmosphereInterceptor(scFacade);
analytics();
// http://java.net/jira/browse/ATMOSPHERE-157
if (sc.getServletContext() != null) {
sc.getServletContext().setAttribute(BroadcasterFactory.class.getName(), broadcasterFactory);
}
String s = config.getInitParameter(ApplicationConfig.BROADCASTER_SHARABLE_THREAD_POOLS);
if (s != null) {
sharedThreadPools = Boolean.parseBoolean(s);
}
info();
} catch (Throwable t) {
logger.error("Failed to initialize Atmosphere Framework", t);
if (t instanceof ServletException) {
throw (ServletException) t;
}
throw new ServletException(t);
}
isInit = true;
config.initComplete();
return this;
}
public void reconfigureInitParams(boolean reconfigureInitParams) {
if (reconfigureInitParams) {
doInitParams(servletConfig, reconfigureInitParams);
doInitParamsForWebSocket(servletConfig);
}
}
private void info() {
logger.info("Using EndpointMapper {}", endpointMapper.getClass());
for (String i : broadcasterFilters) {
logger.info("Using BroadcastFilter: {}", i);
}
if (broadcasterCacheClassName == null || DefaultBroadcasterCache.class.getName().equals(broadcasterCacheClassName)) {
logger.warn("No BroadcasterCache configured. Broadcasted message between client reconnection will be LOST. " +
"It is recommended to configure the {}", UUIDBroadcasterCache.class.getName());
} else {
logger.info("Using BroadcasterCache: {}", broadcasterCacheClassName);
}
String s = config.getInitParameter(BROADCASTER_WAIT_TIME);
logger.info("Default Broadcaster Class: {}", broadcasterClassName);
logger.info("Broadcaster Polling Wait Time {}", s == null ? DefaultBroadcaster.POLLING_DEFAULT : s);
logger.info("Shared ExecutorService supported: {}", sharedThreadPools);
BroadcasterConfig bc = broadcasterFactory.lookup(Broadcaster.ROOT_MASTER, true).getBroadcasterConfig();
if (bc.getAsyncWriteService() != null) {
long max = ThreadPoolExecutor.class.cast(bc.getExecutorService()).getMaximumPoolSize();
logger.info("Messaging Thread Pool Size: {}",
ThreadPoolExecutor.class.cast(bc.getExecutorService()).getMaximumPoolSize() == 2147483647 ? "Unlimited" : max);
logger.info("Async I/O Thread Pool Size: {}",
ThreadPoolExecutor.class.cast(bc.getAsyncWriteService()).getMaximumPoolSize());
}
logger.info("Using BroadcasterFactory: {}", broadcasterFactory.getClass().getName());
logger.info("Using WebSocketProcessor: {}", webSocketProcessorClassName);
WebSocketProcessor wp = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(this);
boolean b = false;
if (DefaultWebSocketProcessor.class.isAssignableFrom(wp.getClass())) {
b = DefaultWebSocketProcessor.class.cast(wp).invokeInterceptors();
}
logger.info("Invoke AtmosphereInterceptor on WebSocket message {}", b);
logger.info("HttpSession supported: {}", config.isSupportSession());
logger.info("Atmosphere is using {} for dependency injection and object creation", objectFactory);
logger.info("Atmosphere is using async support: {} running under container: {}",
getAsyncSupport().getClass().getName(), asyncSupport.getContainerName());
logger.info("Atmosphere Framework {} started.", Version.getRawVersion());
logger.info("\n\n\tFor Atmosphere Framework Commercial Support, visit \n\t{} " +
"or send an email to {}\n", "http://www.async-io.org/", "support@async-io.org");
}
private void configureAnnotationPackages() {
// We must scan the default annotation set.
annotationPackages.add(Processor.class.getPackage().getName());
String s = config.getInitParameter(ApplicationConfig.CUSTOM_ANNOTATION_PACKAGE);
if (s != null) {
String[] l = s.split(",");
for (String p : l) {
annotationPackages.addLast(p);
}
}
}
protected void analytics() {
final String container = getServletContext().getServerInfo();
if (allowAllClassesScan) {
Thread t = new Thread() {
public void run() {
try {
HttpURLConnection urlConnection = (HttpURLConnection)
URI.create("http://async-io.org/version.html").toURL().openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setRequestProperty("Connection", "keep-alive");
urlConnection.setRequestProperty("Cache-Control", "max-age=0");
urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
urlConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
urlConnection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
urlConnection.setRequestProperty("If-Modified-Since", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
urlConnection.setInstanceFollowRedirects(true);
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
String newVersion = Version.getRawVersion();
String clientVersion = "2.1.2";
try {
while ((inputLine = in.readLine().trim()) != null) {
if (inputLine.startsWith("ATMO21_VERSION=")) {
newVersion = inputLine.substring("ATMO21_VERSION=".length());
} else if (inputLine.startsWith("CLIENT2_VERSION=")) {