sonixlabs-eventmachine-java 1.0.0.rc.4-java

Sign up to get free protection for your applications and to get access to all the features.
Files changed (162) hide show
  1. data/.gitignore +22 -0
  2. data/.yardopts +7 -0
  3. data/GNU +281 -0
  4. data/Gemfile +3 -0
  5. data/LICENSE +60 -0
  6. data/README.md +109 -0
  7. data/Rakefile +20 -0
  8. data/docs/DocumentationGuidesIndex.md +27 -0
  9. data/docs/GettingStarted.md +521 -0
  10. data/docs/old/ChangeLog +211 -0
  11. data/docs/old/DEFERRABLES +246 -0
  12. data/docs/old/EPOLL +141 -0
  13. data/docs/old/INSTALL +13 -0
  14. data/docs/old/KEYBOARD +42 -0
  15. data/docs/old/LEGAL +25 -0
  16. data/docs/old/LIGHTWEIGHT_CONCURRENCY +130 -0
  17. data/docs/old/PURE_RUBY +75 -0
  18. data/docs/old/RELEASE_NOTES +94 -0
  19. data/docs/old/SMTP +4 -0
  20. data/docs/old/SPAWNED_PROCESSES +148 -0
  21. data/docs/old/TODO +8 -0
  22. data/eventmachine.gemspec +34 -0
  23. data/examples/guides/getting_started/01_eventmachine_echo_server.rb +18 -0
  24. data/examples/guides/getting_started/02_eventmachine_echo_server_that_recognizes_exit_command.rb +22 -0
  25. data/examples/guides/getting_started/03_simple_chat_server.rb +149 -0
  26. data/examples/guides/getting_started/04_simple_chat_server_step_one.rb +27 -0
  27. data/examples/guides/getting_started/05_simple_chat_server_step_two.rb +43 -0
  28. data/examples/guides/getting_started/06_simple_chat_server_step_three.rb +98 -0
  29. data/examples/guides/getting_started/07_simple_chat_server_step_four.rb +121 -0
  30. data/examples/guides/getting_started/08_simple_chat_server_step_five.rb +141 -0
  31. data/examples/old/ex_channel.rb +43 -0
  32. data/examples/old/ex_queue.rb +2 -0
  33. data/examples/old/ex_tick_loop_array.rb +15 -0
  34. data/examples/old/ex_tick_loop_counter.rb +32 -0
  35. data/examples/old/helper.rb +2 -0
  36. data/ext/binder.cpp +124 -0
  37. data/ext/binder.h +46 -0
  38. data/ext/cmain.cpp +876 -0
  39. data/ext/ed.cpp +1973 -0
  40. data/ext/ed.h +422 -0
  41. data/ext/em.cpp +2353 -0
  42. data/ext/em.h +239 -0
  43. data/ext/eventmachine.h +127 -0
  44. data/ext/extconf.rb +176 -0
  45. data/ext/fastfilereader/extconf.rb +103 -0
  46. data/ext/fastfilereader/mapper.cpp +214 -0
  47. data/ext/fastfilereader/mapper.h +59 -0
  48. data/ext/fastfilereader/rubymain.cpp +127 -0
  49. data/ext/kb.cpp +79 -0
  50. data/ext/page.cpp +107 -0
  51. data/ext/page.h +51 -0
  52. data/ext/pipe.cpp +347 -0
  53. data/ext/project.h +156 -0
  54. data/ext/rubymain.cpp +1297 -0
  55. data/ext/ssl.cpp +468 -0
  56. data/ext/ssl.h +94 -0
  57. data/java/.classpath +8 -0
  58. data/java/.project +17 -0
  59. data/java/src/com/rubyeventmachine/EmReactor.java +588 -0
  60. data/java/src/com/rubyeventmachine/EmReactorException.java +40 -0
  61. data/java/src/com/rubyeventmachine/EventableChannel.java +70 -0
  62. data/java/src/com/rubyeventmachine/EventableDatagramChannel.java +195 -0
  63. data/java/src/com/rubyeventmachine/EventableSocketChannel.java +364 -0
  64. data/lib/em/buftok.rb +110 -0
  65. data/lib/em/callback.rb +58 -0
  66. data/lib/em/channel.rb +64 -0
  67. data/lib/em/completion.rb +304 -0
  68. data/lib/em/connection.rb +712 -0
  69. data/lib/em/deferrable.rb +210 -0
  70. data/lib/em/deferrable/pool.rb +2 -0
  71. data/lib/em/file_watch.rb +73 -0
  72. data/lib/em/future.rb +61 -0
  73. data/lib/em/iterator.rb +270 -0
  74. data/lib/em/messages.rb +66 -0
  75. data/lib/em/pool.rb +151 -0
  76. data/lib/em/process_watch.rb +45 -0
  77. data/lib/em/processes.rb +123 -0
  78. data/lib/em/protocols.rb +36 -0
  79. data/lib/em/protocols/header_and_content.rb +138 -0
  80. data/lib/em/protocols/httpclient.rb +279 -0
  81. data/lib/em/protocols/httpclient2.rb +600 -0
  82. data/lib/em/protocols/line_and_text.rb +125 -0
  83. data/lib/em/protocols/line_protocol.rb +29 -0
  84. data/lib/em/protocols/linetext2.rb +161 -0
  85. data/lib/em/protocols/memcache.rb +331 -0
  86. data/lib/em/protocols/object_protocol.rb +46 -0
  87. data/lib/em/protocols/postgres3.rb +246 -0
  88. data/lib/em/protocols/saslauth.rb +175 -0
  89. data/lib/em/protocols/smtpclient.rb +365 -0
  90. data/lib/em/protocols/smtpserver.rb +640 -0
  91. data/lib/em/protocols/socks4.rb +66 -0
  92. data/lib/em/protocols/stomp.rb +202 -0
  93. data/lib/em/protocols/tcptest.rb +54 -0
  94. data/lib/em/pure_ruby.rb +1017 -0
  95. data/lib/em/queue.rb +71 -0
  96. data/lib/em/resolver.rb +192 -0
  97. data/lib/em/spawnable.rb +84 -0
  98. data/lib/em/streamer.rb +118 -0
  99. data/lib/em/threaded_resource.rb +90 -0
  100. data/lib/em/tick_loop.rb +85 -0
  101. data/lib/em/timers.rb +61 -0
  102. data/lib/em/version.rb +3 -0
  103. data/lib/eventmachine.rb +1532 -0
  104. data/lib/jeventmachine.rb +284 -0
  105. data/lib/sonixlabs-eventmachine-java.rb +1 -0
  106. data/rakelib/cpp.rake_example +77 -0
  107. data/rakelib/package.rake +98 -0
  108. data/rakelib/test.rake +8 -0
  109. data/tests/client.crt +31 -0
  110. data/tests/client.key +51 -0
  111. data/tests/em_test_helper.rb +64 -0
  112. data/tests/test_attach.rb +126 -0
  113. data/tests/test_basic.rb +294 -0
  114. data/tests/test_channel.rb +62 -0
  115. data/tests/test_completion.rb +177 -0
  116. data/tests/test_connection_count.rb +33 -0
  117. data/tests/test_defer.rb +18 -0
  118. data/tests/test_deferrable.rb +35 -0
  119. data/tests/test_epoll.rb +130 -0
  120. data/tests/test_error_handler.rb +38 -0
  121. data/tests/test_exc.rb +28 -0
  122. data/tests/test_file_watch.rb +65 -0
  123. data/tests/test_futures.rb +170 -0
  124. data/tests/test_get_sock_opt.rb +37 -0
  125. data/tests/test_handler_check.rb +35 -0
  126. data/tests/test_hc.rb +155 -0
  127. data/tests/test_httpclient.rb +190 -0
  128. data/tests/test_httpclient2.rb +128 -0
  129. data/tests/test_idle_connection.rb +23 -0
  130. data/tests/test_inactivity_timeout.rb +54 -0
  131. data/tests/test_kb.rb +34 -0
  132. data/tests/test_ltp.rb +138 -0
  133. data/tests/test_ltp2.rb +288 -0
  134. data/tests/test_next_tick.rb +104 -0
  135. data/tests/test_object_protocol.rb +36 -0
  136. data/tests/test_pause.rb +78 -0
  137. data/tests/test_pending_connect_timeout.rb +52 -0
  138. data/tests/test_pool.rb +194 -0
  139. data/tests/test_process_watch.rb +48 -0
  140. data/tests/test_processes.rb +128 -0
  141. data/tests/test_proxy_connection.rb +180 -0
  142. data/tests/test_pure.rb +88 -0
  143. data/tests/test_queue.rb +50 -0
  144. data/tests/test_resolver.rb +55 -0
  145. data/tests/test_running.rb +14 -0
  146. data/tests/test_sasl.rb +47 -0
  147. data/tests/test_send_file.rb +217 -0
  148. data/tests/test_servers.rb +33 -0
  149. data/tests/test_set_sock_opt.rb +37 -0
  150. data/tests/test_shutdown_hooks.rb +23 -0
  151. data/tests/test_smtpclient.rb +55 -0
  152. data/tests/test_smtpserver.rb +57 -0
  153. data/tests/test_spawn.rb +293 -0
  154. data/tests/test_ssl_args.rb +78 -0
  155. data/tests/test_ssl_methods.rb +48 -0
  156. data/tests/test_ssl_verify.rb +82 -0
  157. data/tests/test_threaded_resource.rb +53 -0
  158. data/tests/test_tick_loop.rb +59 -0
  159. data/tests/test_timers.rb +123 -0
  160. data/tests/test_ud.rb +8 -0
  161. data/tests/test_unbind_reason.rb +48 -0
  162. metadata +301 -0
@@ -0,0 +1,94 @@
1
+ /*****************************************************************************
2
+
3
+ $Id$
4
+
5
+ File: ssl.h
6
+ Date: 30Apr06
7
+
8
+ Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
9
+ Gmail: blackhedd
10
+
11
+ This program is free software; you can redistribute it and/or modify
12
+ it under the terms of either: 1) the GNU General Public License
13
+ as published by the Free Software Foundation; either version 2 of the
14
+ License, or (at your option) any later version; or 2) Ruby's License.
15
+
16
+ See the file COPYING for complete licensing information.
17
+
18
+ *****************************************************************************/
19
+
20
+
21
+ #ifndef __SslBox__H_
22
+ #define __SslBox__H_
23
+
24
+
25
+
26
+
27
+ #ifdef WITH_SSL
28
+
29
+ /******************
30
+ class SslContext_t
31
+ ******************/
32
+
33
+ class SslContext_t
34
+ {
35
+ public:
36
+ SslContext_t (bool is_server, const string &privkeyfile, const string &certchainfile);
37
+ virtual ~SslContext_t();
38
+
39
+ private:
40
+ static bool bLibraryInitialized;
41
+
42
+ private:
43
+ bool bIsServer;
44
+ SSL_CTX *pCtx;
45
+
46
+ EVP_PKEY *PrivateKey;
47
+ X509 *Certificate;
48
+
49
+ friend class SslBox_t;
50
+ };
51
+
52
+
53
+ /**************
54
+ class SslBox_t
55
+ **************/
56
+
57
+ class SslBox_t
58
+ {
59
+ public:
60
+ SslBox_t (bool is_server, const string &privkeyfile, const string &certchainfile, bool verify_peer, const unsigned long binding);
61
+ virtual ~SslBox_t();
62
+
63
+ int PutPlaintext (const char*, int);
64
+ int GetPlaintext (char*, int);
65
+
66
+ bool PutCiphertext (const char*, int);
67
+ bool CanGetCiphertext();
68
+ int GetCiphertext (char*, int);
69
+ bool IsHandshakeCompleted() {return bHandshakeCompleted;}
70
+
71
+ X509 *GetPeerCert();
72
+
73
+ void Shutdown();
74
+
75
+ protected:
76
+ SslContext_t *Context;
77
+
78
+ bool bIsServer;
79
+ bool bHandshakeCompleted;
80
+ bool bVerifyPeer;
81
+ SSL *pSSL;
82
+ BIO *pbioRead;
83
+ BIO *pbioWrite;
84
+
85
+ PageList OutboundQ;
86
+ };
87
+
88
+ extern "C" int ssl_verify_wrapper(int, X509_STORE_CTX*);
89
+
90
+ #endif // WITH_SSL
91
+
92
+
93
+ #endif // __SslBox__H_
94
+
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <classpath>
3
+ <classpathentry kind="src" path="src"/>
4
+ <classpathentry excluding="src/" kind="src" path=""/>
5
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
6
+ <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
7
+ <classpathentry kind="output" path="src"/>
8
+ </classpath>
@@ -0,0 +1,17 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <projectDescription>
3
+ <name>em_reactor</name>
4
+ <comment></comment>
5
+ <projects>
6
+ </projects>
7
+ <buildSpec>
8
+ <buildCommand>
9
+ <name>org.eclipse.jdt.core.javabuilder</name>
10
+ <arguments>
11
+ </arguments>
12
+ </buildCommand>
13
+ </buildSpec>
14
+ <natures>
15
+ <nature>org.eclipse.jdt.core.javanature</nature>
16
+ </natures>
17
+ </projectDescription>
@@ -0,0 +1,588 @@
1
+ /**
2
+ * $Id$
3
+ *
4
+ * Author:: Francis Cianfrocca (gmail: blackhedd)
5
+ * Homepage:: http://rubyeventmachine.com
6
+ * Date:: 15 Jul 2007
7
+ *
8
+ * See EventMachine and EventMachine::Connection for documentation and
9
+ * usage examples.
10
+ *
11
+ *
12
+ *----------------------------------------------------------------------------
13
+ *
14
+ * Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
15
+ * Gmail: blackhedd
16
+ *
17
+ * This program is free software; you can redistribute it and/or modify
18
+ * it under the terms of either: 1) the GNU General Public License
19
+ * as published by the Free Software Foundation; either version 2 of the
20
+ * License, or (at your option) any later version; or 2) Ruby's License.
21
+ *
22
+ * See the file COPYING for complete licensing information.
23
+ *
24
+ *---------------------------------------------------------------------------
25
+ *
26
+ *
27
+ */
28
+
29
+ package com.rubyeventmachine;
30
+
31
+ import java.io.*;
32
+ import java.nio.channels.*;
33
+ import java.util.*;
34
+ import java.nio.*;
35
+ import java.net.*;
36
+ import java.util.concurrent.atomic.*;
37
+ import java.security.*;
38
+ import java.lang.reflect.UndeclaredThrowableException;
39
+
40
+ public class EmReactor {
41
+ public final int EM_TIMER_FIRED = 100;
42
+ public final int EM_CONNECTION_READ = 101;
43
+ public final int EM_CONNECTION_UNBOUND = 102;
44
+ public final int EM_CONNECTION_ACCEPTED = 103;
45
+ public final int EM_CONNECTION_COMPLETED = 104;
46
+ public final int EM_LOOPBREAK_SIGNAL = 105;
47
+ public final int EM_CONNECTION_NOTIFY_READABLE = 106;
48
+ public final int EM_CONNECTION_NOTIFY_WRITABLE = 107;
49
+ public final int EM_SSL_HANDSHAKE_COMPLETED = 108;
50
+ public final int EM_SSL_VERIFY = 109;
51
+ public final int EM_PROXY_TARGET_UNBOUND = 110;
52
+ public final int EM_PROXY_COMPLETED = 111;
53
+
54
+ private Selector mySelector;
55
+ private TreeMap<Long, ArrayList<Long>> Timers;
56
+ private HashMap<Long, EventableChannel> Connections;
57
+ private HashMap<Long, ServerSocketChannel> Acceptors;
58
+ private ArrayList<Long> NewConnections;
59
+ private ArrayList<Long> UnboundConnections;
60
+ private ArrayList<EventableSocketChannel> DetachedConnections;
61
+
62
+ private boolean bRunReactor;
63
+ private long BindingIndex;
64
+ private AtomicBoolean loopBreaker;
65
+ private ByteBuffer myReadBuffer;
66
+ private int timerQuantum;
67
+
68
+ public EmReactor() {
69
+ Timers = new TreeMap<Long, ArrayList<Long>>();
70
+ Connections = new HashMap<Long, EventableChannel>();
71
+ Acceptors = new HashMap<Long, ServerSocketChannel>();
72
+ NewConnections = new ArrayList<Long>();
73
+ UnboundConnections = new ArrayList<Long>();
74
+ DetachedConnections = new ArrayList<EventableSocketChannel>();
75
+
76
+ BindingIndex = 0;
77
+ loopBreaker = new AtomicBoolean();
78
+ loopBreaker.set(false);
79
+ myReadBuffer = ByteBuffer.allocate(32*1024); // don't use a direct buffer. Ruby doesn't seem to like them.
80
+ timerQuantum = 98;
81
+ }
82
+
83
+ /**
84
+ * This is a no-op stub, intended to be overridden in user code.
85
+ */
86
+ public void eventCallback (long sig, int eventType, ByteBuffer data, long data2) {
87
+ System.out.println ("Default callback: "+sig+" "+eventType+" "+data+" "+data2);
88
+ }
89
+ public void eventCallback (long sig, int eventType, ByteBuffer data) {
90
+ eventCallback (sig, eventType, data, 0);
91
+ }
92
+
93
+
94
+ public void run() {
95
+ try {
96
+ mySelector = Selector.open();
97
+ bRunReactor = true;
98
+ } catch (IOException e) {
99
+ throw new RuntimeException ("Could not open selector", e);
100
+ }
101
+
102
+ while (bRunReactor) {
103
+ runLoopbreaks();
104
+ if (!bRunReactor) break;
105
+
106
+ runTimers();
107
+ if (!bRunReactor) break;
108
+
109
+ removeUnboundConnections();
110
+ checkIO();
111
+ addNewConnections();
112
+ processIO();
113
+ }
114
+
115
+ close();
116
+ }
117
+
118
+ void addNewConnections() {
119
+ ListIterator<EventableSocketChannel> iter = DetachedConnections.listIterator(0);
120
+ while (iter.hasNext()) {
121
+ EventableSocketChannel ec = iter.next();
122
+ ec.cleanup();
123
+ }
124
+ DetachedConnections.clear();
125
+
126
+ ListIterator<Long> iter2 = NewConnections.listIterator(0);
127
+ while (iter2.hasNext()) {
128
+ long b = iter2.next();
129
+
130
+ EventableChannel ec = Connections.get(b);
131
+ if (ec != null) {
132
+ try {
133
+ ec.register();
134
+ } catch (ClosedChannelException e) {
135
+ UnboundConnections.add (ec.getBinding());
136
+ }
137
+ }
138
+ }
139
+ NewConnections.clear();
140
+ }
141
+
142
+ void removeUnboundConnections() {
143
+ ListIterator<Long> iter = UnboundConnections.listIterator(0);
144
+ while (iter.hasNext()) {
145
+ long b = iter.next();
146
+
147
+ EventableChannel ec = Connections.remove(b);
148
+ if (ec != null) {
149
+ eventCallback (b, EM_CONNECTION_UNBOUND, null);
150
+ ec.close();
151
+
152
+ EventableSocketChannel sc = (EventableSocketChannel) ec;
153
+ if (sc != null && sc.isAttached())
154
+ DetachedConnections.add (sc);
155
+ }
156
+ }
157
+ UnboundConnections.clear();
158
+ }
159
+
160
+ void checkIO() {
161
+ long timeout;
162
+
163
+ if (NewConnections.size() > 0) {
164
+ timeout = -1;
165
+ } else if (!Timers.isEmpty()) {
166
+ long now = new Date().getTime();
167
+ long k = Timers.firstKey();
168
+ long diff = k-now;
169
+
170
+ if (diff <= 0)
171
+ timeout = -1; // don't wait, just poll once
172
+ else
173
+ timeout = diff;
174
+ } else {
175
+ timeout = 0; // wait indefinitely
176
+ }
177
+
178
+ try {
179
+ if (timeout == -1)
180
+ mySelector.selectNow();
181
+ else
182
+ mySelector.select(timeout);
183
+ } catch (IOException e) {
184
+ e.printStackTrace();
185
+ }
186
+ }
187
+
188
+ void processIO() {
189
+ Iterator<SelectionKey> it = mySelector.selectedKeys().iterator();
190
+ while (it.hasNext()) {
191
+ SelectionKey k = it.next();
192
+ it.remove();
193
+
194
+ if (k.isConnectable())
195
+ isConnectable(k);
196
+
197
+ else if (k.isAcceptable())
198
+ isAcceptable(k);
199
+
200
+ else {
201
+ if (k.isWritable())
202
+ isWritable(k);
203
+
204
+ if (k.isReadable())
205
+ isReadable(k);
206
+ }
207
+ }
208
+ }
209
+
210
+ void isAcceptable (SelectionKey k) {
211
+ ServerSocketChannel ss = (ServerSocketChannel) k.channel();
212
+ SocketChannel sn;
213
+ long b;
214
+
215
+ for (int n = 0; n < 10; n++) {
216
+ try {
217
+ sn = ss.accept();
218
+ if (sn == null)
219
+ break;
220
+ } catch (IOException e) {
221
+ e.printStackTrace();
222
+ k.cancel();
223
+
224
+ ServerSocketChannel server = Acceptors.remove(k.attachment());
225
+ if (server != null)
226
+ try{ server.close(); } catch (IOException ex) {};
227
+ break;
228
+ }
229
+
230
+ try {
231
+ sn.configureBlocking(false);
232
+ } catch (IOException e) {
233
+ e.printStackTrace();
234
+ continue;
235
+ }
236
+
237
+ b = createBinding();
238
+ EventableSocketChannel ec = new EventableSocketChannel (sn, b, mySelector);
239
+ Connections.put (b, ec);
240
+ NewConnections.add (b);
241
+
242
+ eventCallback (((Long)k.attachment()).longValue(), EM_CONNECTION_ACCEPTED, null, b);
243
+ }
244
+ }
245
+
246
+ void isReadable (SelectionKey k) {
247
+ EventableChannel ec = (EventableChannel) k.attachment();
248
+ long b = ec.getBinding();
249
+
250
+ if (ec.isWatchOnly()) {
251
+ if (ec.isNotifyReadable())
252
+ eventCallback (b, EM_CONNECTION_NOTIFY_READABLE, null);
253
+ } else {
254
+ myReadBuffer.clear();
255
+
256
+ try {
257
+ ec.readInboundData (myReadBuffer);
258
+ myReadBuffer.flip();
259
+ if (myReadBuffer.limit() > 0)
260
+ eventCallback (b, EM_CONNECTION_READ, myReadBuffer);
261
+ } catch (IOException e) {
262
+ UnboundConnections.add (b);
263
+ }
264
+ }
265
+ }
266
+
267
+ void isWritable (SelectionKey k) {
268
+ EventableChannel ec = (EventableChannel) k.attachment();
269
+ long b = ec.getBinding();
270
+
271
+ if (ec.isWatchOnly()) {
272
+ if (ec.isNotifyWritable())
273
+ eventCallback (b, EM_CONNECTION_NOTIFY_WRITABLE, null);
274
+ }
275
+ else {
276
+ try {
277
+ if (!ec.writeOutboundData())
278
+ UnboundConnections.add (b);
279
+ } catch (IOException e) {
280
+ UnboundConnections.add (b);
281
+ }
282
+ }
283
+ }
284
+
285
+ void isConnectable (SelectionKey k) {
286
+ EventableSocketChannel ec = (EventableSocketChannel) k.attachment();
287
+ long b = ec.getBinding();
288
+
289
+ try {
290
+ if (ec.finishConnecting())
291
+ eventCallback (b, EM_CONNECTION_COMPLETED, null);
292
+ else
293
+ UnboundConnections.add (b);
294
+ } catch (IOException e) {
295
+ UnboundConnections.add (b);
296
+ }
297
+ }
298
+
299
+ void close() {
300
+ try {
301
+ if (mySelector != null)
302
+ mySelector.close();
303
+ } catch (IOException e) {}
304
+ mySelector = null;
305
+
306
+ // run down open connections and sockets.
307
+ Iterator<ServerSocketChannel> i = Acceptors.values().iterator();
308
+ while (i.hasNext()) {
309
+ try {
310
+ i.next().close();
311
+ } catch (IOException e) {}
312
+ }
313
+
314
+ // 29Sep09: We create an ArrayList of the existing connections, then iterate over
315
+ // that to call unbind on them. This is because an unbind can trigger a reconnect,
316
+ // which will add to the Connections HashMap, causing a ConcurrentModificationException.
317
+ // XXX: The correct behavior here would be to latch the various reactor methods to return
318
+ // immediately if the reactor is shutting down.
319
+ ArrayList<EventableChannel> conns = new ArrayList<EventableChannel>();
320
+ Iterator<EventableChannel> i2 = Connections.values().iterator();
321
+ while (i2.hasNext()) {
322
+ EventableChannel ec = i2.next();
323
+ if (ec != null) {
324
+ conns.add (ec);
325
+ }
326
+ }
327
+ Connections.clear();
328
+
329
+ ListIterator<EventableChannel> i3 = conns.listIterator(0);
330
+ while (i3.hasNext()) {
331
+ EventableChannel ec = i3.next();
332
+ eventCallback (ec.getBinding(), EM_CONNECTION_UNBOUND, null);
333
+ ec.close();
334
+
335
+ EventableSocketChannel sc = (EventableSocketChannel) ec;
336
+ if (sc != null && sc.isAttached())
337
+ DetachedConnections.add (sc);
338
+ }
339
+
340
+ ListIterator<EventableSocketChannel> i4 = DetachedConnections.listIterator(0);
341
+ while (i4.hasNext()) {
342
+ EventableSocketChannel ec = i4.next();
343
+ ec.cleanup();
344
+ }
345
+ DetachedConnections.clear();
346
+ }
347
+
348
+ void runLoopbreaks() {
349
+ if (loopBreaker.getAndSet(false)) {
350
+ eventCallback (0, EM_LOOPBREAK_SIGNAL, null);
351
+ }
352
+ }
353
+
354
+ public void stop() {
355
+ bRunReactor = false;
356
+ signalLoopbreak();
357
+ }
358
+
359
+ void runTimers() {
360
+ long now = new Date().getTime();
361
+ while (!Timers.isEmpty()) {
362
+ long k = Timers.firstKey();
363
+ if (k > now)
364
+ break;
365
+
366
+ ArrayList<Long> callbacks = Timers.get(k);
367
+ Timers.remove(k);
368
+
369
+ // Fire all timers at this timestamp
370
+ ListIterator<Long> iter = callbacks.listIterator(0);
371
+ try {
372
+ while (iter.hasNext()) {
373
+ eventCallback (0, EM_TIMER_FIRED, null, iter.next().longValue());
374
+ }
375
+ } catch (UndeclaredThrowableException e) {
376
+ e.printStackTrace();
377
+ }
378
+ }
379
+ }
380
+
381
+ public long installOneshotTimer (int milliseconds) {
382
+ long s = createBinding();
383
+ long deadline = new Date().getTime() + milliseconds;
384
+
385
+ if (Timers.containsKey(deadline)) {
386
+ Timers.get(deadline).add(s);
387
+ } else {
388
+ ArrayList<Long> callbacks = new ArrayList<Long>();
389
+ callbacks.add(s);
390
+ Timers.put(deadline, callbacks);
391
+ }
392
+
393
+ return s;
394
+ }
395
+
396
+ public long startTcpServer (SocketAddress sa) throws EmReactorException {
397
+ try {
398
+ ServerSocketChannel server = ServerSocketChannel.open();
399
+ server.configureBlocking(false);
400
+ server.socket().bind (sa);
401
+ long s = createBinding();
402
+ Acceptors.put(s, server);
403
+ server.register(mySelector, SelectionKey.OP_ACCEPT, s);
404
+ return s;
405
+ } catch (IOException e) {
406
+ throw new EmReactorException ("unable to open socket acceptor: " + e.toString());
407
+ }
408
+ }
409
+
410
+ public long startTcpServer (String address, int port) throws EmReactorException {
411
+ return startTcpServer (new InetSocketAddress (address, port));
412
+ }
413
+
414
+ public void stopTcpServer (long signature) throws IOException {
415
+ ServerSocketChannel server = Acceptors.remove(signature);
416
+ if (server != null)
417
+ server.close();
418
+ else
419
+ throw new RuntimeException ("failed to close unknown acceptor");
420
+ }
421
+
422
+ public long openUdpSocket (InetSocketAddress address) throws IOException {
423
+ // TODO, don't throw an exception out of here.
424
+ DatagramChannel dg = DatagramChannel.open();
425
+ dg.configureBlocking(false);
426
+ dg.socket().bind(address);
427
+ long b = createBinding();
428
+ EventableChannel ec = new EventableDatagramChannel (dg, b, mySelector);
429
+ dg.register(mySelector, SelectionKey.OP_READ, ec);
430
+ Connections.put(b, ec);
431
+ return b;
432
+ }
433
+
434
+ public long openUdpSocket (String address, int port) throws IOException {
435
+ return openUdpSocket (new InetSocketAddress (address, port));
436
+ }
437
+
438
+ public void sendData (long sig, ByteBuffer bb) throws IOException {
439
+ EventableChannel ec = Connections.get(sig);
440
+ if (ec == null) {
441
+ return;
442
+ }
443
+ ec.scheduleOutboundData( bb );
444
+ // HACK: In Ubuntu(java version 1.6.0_33), it is blocked by mSelector.select() in checkIO() and writeOutboundData() is not called.
445
+ if (!ec.isWatchOnly()) {
446
+ ec.writeOutboundData();
447
+ }
448
+ }
449
+
450
+ public void sendData (long sig, byte[] data) throws IOException {
451
+ sendData (sig, ByteBuffer.wrap(data));
452
+ }
453
+
454
+ public void setCommInactivityTimeout (long sig, long mills) {
455
+ Connections.get(sig).setCommInactivityTimeout (mills);
456
+ }
457
+
458
+ public void sendDatagram (long sig, byte[] data, int length, String recipAddress, int recipPort) {
459
+ sendDatagram (sig, ByteBuffer.wrap(data), recipAddress, recipPort);
460
+ }
461
+
462
+ public void sendDatagram (long sig, ByteBuffer bb, String recipAddress, int recipPort) {
463
+ (Connections.get(sig)).scheduleOutboundDatagram( bb, recipAddress, recipPort);
464
+ }
465
+
466
+ public long connectTcpServer (String address, int port) {
467
+ return connectTcpServer(null, 0, address, port);
468
+ }
469
+
470
+ public long connectTcpServer (String bindAddr, int bindPort, String address, int port) {
471
+ long b = createBinding();
472
+
473
+ try {
474
+ SocketChannel sc = SocketChannel.open();
475
+ sc.configureBlocking(false);
476
+ if (bindAddr != null)
477
+ sc.socket().bind(new InetSocketAddress (bindAddr, bindPort));
478
+
479
+ EventableSocketChannel ec = new EventableSocketChannel (sc, b, mySelector);
480
+
481
+ if (sc.connect (new InetSocketAddress (address, port))) {
482
+ // Connection returned immediately. Can happen with localhost connections.
483
+ // WARNING, this code is untested due to lack of available test conditions.
484
+ // Ought to be be able to come here from a localhost connection, but that
485
+ // doesn't happen on Linux. (Maybe on FreeBSD?)
486
+ // The reason for not handling this until we can test it is that we
487
+ // really need to return from this function WITHOUT triggering any EM events.
488
+ // That's because until the user code has seen the signature we generated here,
489
+ // it won't be able to properly dispatch them. The C++ EM deals with this
490
+ // by setting pending mode as a flag in ALL eventable descriptors and making
491
+ // the descriptor select for writable. Then, it can send UNBOUND and
492
+ // CONNECTION_COMPLETED on the next pass through the loop, because writable will
493
+ // fire.
494
+ throw new RuntimeException ("immediate-connect unimplemented");
495
+ }
496
+ else {
497
+ ec.setConnectPending();
498
+ Connections.put (b, ec);
499
+ NewConnections.add (b);
500
+ }
501
+ } catch (IOException e) {
502
+ // Can theoretically come here if a connect failure can be determined immediately.
503
+ // I don't know how to make that happen for testing purposes.
504
+ throw new RuntimeException ("immediate-connect unimplemented: " + e.toString());
505
+ }
506
+ return b;
507
+ }
508
+
509
+ public void closeConnection (long sig, boolean afterWriting) {
510
+ EventableChannel ec = Connections.get(sig);
511
+ if (ec != null)
512
+ if (ec.scheduleClose (afterWriting))
513
+ UnboundConnections.add (sig);
514
+ }
515
+
516
+ long createBinding() {
517
+ return ++BindingIndex;
518
+ }
519
+
520
+ public void signalLoopbreak() {
521
+ loopBreaker.set(true);
522
+ if (mySelector != null)
523
+ mySelector.wakeup();
524
+ }
525
+
526
+ public void startTls (long sig) throws NoSuchAlgorithmException, KeyManagementException {
527
+ Connections.get(sig).startTls();
528
+ }
529
+
530
+ public void setTimerQuantum (int mills) {
531
+ if (mills < 5 || mills > 2500)
532
+ throw new RuntimeException ("attempt to set invalid timer-quantum value: "+mills);
533
+ timerQuantum = mills;
534
+ }
535
+
536
+ public Object[] getPeerName (long sig) {
537
+ return Connections.get(sig).getPeerName();
538
+ }
539
+
540
+ public Object[] getSockName (long sig) {
541
+ return Connections.get(sig).getSockName();
542
+ }
543
+
544
+ public long attachChannel (SocketChannel sc, boolean watch_mode) {
545
+ long b = createBinding();
546
+
547
+ EventableSocketChannel ec = new EventableSocketChannel (sc, b, mySelector);
548
+
549
+ ec.setAttached();
550
+ if (watch_mode)
551
+ ec.setWatchOnly();
552
+
553
+ Connections.put (b, ec);
554
+ NewConnections.add (b);
555
+
556
+ return b;
557
+ }
558
+
559
+ public SocketChannel detachChannel (long sig) {
560
+ EventableSocketChannel ec = (EventableSocketChannel) Connections.get (sig);
561
+ if (ec != null) {
562
+ UnboundConnections.add (sig);
563
+ return ec.getChannel();
564
+ } else {
565
+ return null;
566
+ }
567
+ }
568
+
569
+ public void setNotifyReadable (long sig, boolean mode) {
570
+ ((EventableSocketChannel) Connections.get(sig)).setNotifyReadable(mode);
571
+ }
572
+
573
+ public void setNotifyWritable (long sig, boolean mode) {
574
+ ((EventableSocketChannel) Connections.get(sig)).setNotifyWritable(mode);
575
+ }
576
+
577
+ public boolean isNotifyReadable (long sig) {
578
+ return Connections.get(sig).isNotifyReadable();
579
+ }
580
+
581
+ public boolean isNotifyWritable (long sig) {
582
+ return Connections.get(sig).isNotifyWritable();
583
+ }
584
+
585
+ public int getConnectionCount() {
586
+ return Connections.size() + Acceptors.size();
587
+ }
588
+ }