KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xsocket > stream > MultithreadedServer


1 // $Id: MultithreadedServer.java 1574 2007-07-29 14:59:42Z grro $
2
/*
3  * Copyright (c) xsocket.org, 2006 - 2007. All rights reserved.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  *
19  * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
20  * The latest copy of this software may be found on http://www.xsocket.org/
21  */

22 package org.xsocket.stream;
23
24 import java.io.IOException JavaDoc;
25 import java.lang.reflect.Field JavaDoc;
26 import java.net.InetAddress JavaDoc;
27 import java.net.InetSocketAddress JavaDoc;
28 import java.net.UnknownHostException JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.concurrent.Executor JavaDoc;
33 import java.util.concurrent.ExecutorService JavaDoc;
34 import java.util.concurrent.Executors JavaDoc;
35 import java.util.logging.Level JavaDoc;
36 import java.util.logging.Logger JavaDoc;
37
38 import javax.net.ssl.SSLContext;
39
40
41 import org.xsocket.IWorkerPool;
42 import org.xsocket.Resource;
43 import org.xsocket.stream.io.impl.IoProvider;
44 import org.xsocket.stream.io.spi.IAcceptor;
45 import org.xsocket.stream.io.spi.IServerIoProvider;
46 import org.xsocket.stream.io.spi.IAcceptorCallback;
47 import org.xsocket.stream.io.spi.IIoHandler;
48
49
50
51
52 /**
53  * Implementation of a multithreaded server. For more information see
54  * {@link IMultithreadedServer}
55  *
56  * @author grro@xsocket.org
57  */

58 public final class MultithreadedServer implements IMultithreadedServer {
59
60     /*
61      * known tcp issues
62      * to many max files -> http://support.bea.com/application_content/product_portlets/support_patterns/wls/TooManyOpenFilesPattern.html
63      * windows tcp -> http://publib.boulder.ibm.com/infocenter/wasinfo/v4r0/index.jsp?topic=/com.ibm.websphere.v4.doc/wasa_content/0901.html
64      */

65     
66     private static final Logger JavaDoc LOG = Logger.getLogger(MultithreadedServer.class.getName());
67     
68     
69     private static final String JavaDoc DEFAULT_HOST_ADDRESS = "0.0.0.0";
70     
71     
72     
73
74     // is open flag
75
private boolean isOpen= false;
76
77     
78     // acceptor
79
private static IServerIoProvider serverIoProvider = null;
80     private IAcceptor acceptor = null;
81     private InetSocketAddress JavaDoc address = null;
82
83     
84     // config
85
private Map JavaDoc<String JavaDoc, Object JavaDoc> options = null;
86     private boolean sslOn = false;
87     private SSLContext sslContext = null;
88     
89     
90     // worker pool
91
private Executor JavaDoc workerpool = null;
92     private boolean isSelfCreatedWorkerPool = false;
93
94     
95     
96     // app handler
97
private IHandler appHandlerPrototype = null;
98     
99     // io handler
100
private final IoHandlerContext ioHandlerContext = new IoHandlerContext(null, null);
101
102     
103     // server listeners
104
private final ArrayList JavaDoc<IMutlithreadedServerListener> listeners = new ArrayList JavaDoc<IMutlithreadedServerListener>();
105
106     
107     //timeouts
108
private int idleTimeoutSec = Integer.MAX_VALUE;
109     private int connectionTimeoutSec = Integer.MAX_VALUE;
110     
111     
112     
113     static {
114         // ServerIoProvider
115
String JavaDoc serverIoProviderClassname = System.getProperty(IServerIoProvider.PROVIDER_CLASSNAME_KEY);
116         if (serverIoProviderClassname != null) {
117             try {
118                 Class JavaDoc serverIoProviderClass = Class.forName(serverIoProviderClassname);
119                 serverIoProvider = (IServerIoProvider) serverIoProviderClass.newInstance();
120             } catch (Exception JavaDoc e) {
121                 LOG.warning("error occured by creating ServerIoProivder " + serverIoProviderClassname + ": " + e.toString());
122                 LOG.info("using default ServerIoProvider");
123                 
124             }
125         }
126          
127         if (serverIoProvider == null) {
128             serverIoProvider = new IoProvider();
129         }
130     }
131     
132
133     
134
135     /**
136      * constructor <br><br>
137      *
138      * The idle- and connection time out will be set with the default values. To perform the worker threads a
139      * FixedThreadPool {@link Executors#newFixedThreadPool(int)} with 250 max threads will be created.
140      *
141      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
142      * @throws IOException If some other I/O error occurs
143      * @throws UnknownHostException if the locale host cannot determined
144      */

145     public MultithreadedServer(IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
146         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), 0, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, false, null);
147     }
148
149     
150     /**
151      * constructor <br><br>
152      *
153      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
154      *
155      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
156      * @param workerpool the workerpool to use. By setting the WorkerPool with null the worker pool will be deactivated. The callback handler will be
157      * executed by the main dispatching thread. If the handler performs blocking operations, the disptaching will also be blocked!
158      * @throws IOException If some other I/O error occurs
159      * @throws UnknownHostException if the locale host cannot determined
160      */

161     public MultithreadedServer(IHandler handler, Executor JavaDoc workerpool) throws UnknownHostException JavaDoc, IOException JavaDoc {
162         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), 0, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, workerpool, false, null);
163     }
164
165
166     
167     /**
168      * @deprecated
169      */

170     public MultithreadedServer(StreamSocketConfiguration socketConfiguration, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
171         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), 0, socketConfiguration, handler, false, null);
172     }
173     
174     
175     
176     /**
177      * constructor <br><br>
178      *
179      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
180      *
181      * @param options the socket options
182      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
183      * @throws IOException If some other I/O error occurs
184      * @throws UnknownHostException if the locale host cannot determined
185      */

186     public MultithreadedServer(Map JavaDoc<String JavaDoc, Object JavaDoc> options, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
187         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), 0, options, handler, false, null);
188     }
189     
190     
191     /**
192      * constructor <br><br>
193      *
194      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
195      *
196      * @param port the local port
197      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
198      * @throws UnknownHostException if the locale host cannot determined
199      * @throws IOException If some other I/O error occurs
200      */

201     public MultithreadedServer(int port, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
202         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, false, null);
203     }
204
205     
206     /**
207      * constructor <br><br>
208      *
209      * For idle-, connection time out see {@link MultithreadedServer#MultithreadedServer(IHandler)}
210      *
211      * @param port the local port
212      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
213      * @param workerpool the workerpool to use. By setting the WorkerPool with null the worker pool will be deactivated. The callback handler will be
214      * executed by the main dispatching thread. If the handler performs blocking operations, the disptaching will also be blocked!
215      * @throws UnknownHostException if the locale host cannot determined
216      * @throws IOException If some other I/O error occurs
217      */

218     public MultithreadedServer(int port, IHandler handler, Executor JavaDoc workerpool) throws UnknownHostException JavaDoc, IOException JavaDoc {
219         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, workerpool, false, null);
220     }
221     
222     
223     /**
224      * @deprecated
225      */

226     public MultithreadedServer(int port, StreamSocketConfiguration socketConfiguration, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
227         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), port, socketConfiguration, handler, false, null);
228     }
229     
230     /**
231      * constructor <br><br>
232      *
233      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
234      *
235      * @param port the local port
236      * @param options the acceptor socket options
237      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
238      * @throws UnknownHostException if the locale host cannot determined
239      * @throws IOException If some other I/O error occurs
240      */

241     public MultithreadedServer(int port, Map JavaDoc<String JavaDoc , Object JavaDoc> options, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
242         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), port, options, handler, false, null);
243     }
244
245     
246     
247     /**
248      * constructor <br><br>
249      *
250      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
251      *
252      * @param address the local address
253      * @param port the local port
254      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
255      * @throws UnknownHostException if the locale host cannot determined
256      * @throws IOException If some other I/O error occurs
257      */

258     public MultithreadedServer(InetAddress JavaDoc address, int port, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
259         this(address, port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, false, null);
260     }
261
262     
263     
264     
265     /**
266      * constructor <br><br>
267      *
268      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
269      *
270      * @param address the local address
271      * @param port the local port
272      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
273      * @param workerPool the workerpool
274      * @throws UnknownHostException if the locale host cannot determined
275      * @throws IOException If some other I/O error occurs
276      */

277     public MultithreadedServer(InetAddress JavaDoc address, int port, IHandler handler, Executor JavaDoc workerPool) throws UnknownHostException JavaDoc, IOException JavaDoc {
278         this(address, port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, workerPool, false, null);
279     }
280
281     
282
283     /**
284      * @deprecated
285      */

286     public MultithreadedServer(InetAddress JavaDoc address, int port, StreamSocketConfiguration socketConfiguration, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
287         this(address, port, socketConfiguration, handler, false, null);
288     }
289     
290     
291     
292     /**
293      * constructor <br><br>
294      *
295      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
296      *
297      * @param ipAddress the local ip address
298      * @param port the local port
299      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
300      * @throws UnknownHostException if the locale host cannot determined
301      * @throws IOException If some other I/O error occurs
302      */

303     public MultithreadedServer(String JavaDoc ipAddress, int port, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
304         this(InetAddress.getByName(ipAddress), port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, false, null);
305     }
306     
307     
308     /**
309      * @deprecated
310      */

311     public MultithreadedServer(String JavaDoc ipAddress, int port, StreamSocketConfiguration socketConfiguration, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
312         this(InetAddress.getByName(ipAddress), port, socketConfiguration, handler, false, null);
313     }
314     
315     
316     /**
317      * constructor <br><br>
318      *
319      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
320      *
321      * @param ipAddress the local ip address
322      * @param port the local port
323      * @param options the socket options
324      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
325      * @throws UnknownHostException if the locale host cannot determined
326      * @throws IOException If some other I/O error occurs
327      */

328     public MultithreadedServer(String JavaDoc ipAddress, int port, Map JavaDoc<String JavaDoc, Object JavaDoc> options, IHandler handler) throws UnknownHostException JavaDoc, IOException JavaDoc {
329         this(InetAddress.getByName(ipAddress), port, options, handler, false, null);
330     }
331     
332     
333     
334     
335     /**
336      * constructor <br><br>
337      *
338      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
339      *
340      * @param port local port
341      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
342      * @param sslOn true, is SSL should be activated
343      * @param sslContext the ssl context to use
344      * @throws UnknownHostException if the locale host cannot determined
345      * @throws IOException If some other I/O error occurs
346      */

347     public MultithreadedServer(int port, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
348         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, sslOn ,sslContext);
349     }
350     
351     
352     /**
353      * @deprecated
354      */

355     public MultithreadedServer(int port, StreamSocketConfiguration socketConfiguration, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
356         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), port, socketConfiguration, handler, sslOn ,sslContext);
357     }
358     
359     
360     
361     /**
362      * constructor <br><br>
363      *
364      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
365      *
366      * @param port local port
367      * @param options the acceptor socket options
368      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IHandlerLifeCycleListener)
369      * @param sslOn true, is SSL should be activated
370      * @param sslContext the ssl context to use
371      * @throws UnknownHostException if the locale host cannot determined
372      * @throws IOException If some other I/O error occurs
373      */

374     public MultithreadedServer(int port,Map JavaDoc<String JavaDoc, Object JavaDoc> options, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
375         this(InetAddress.getByName(DEFAULT_HOST_ADDRESS), port, options, handler, sslOn ,sslContext);
376     }
377     
378     
379     /**
380      * constructor <br><br>
381      *
382      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
383      *
384      * @param ipAddress local ip address
385      * @param port local port
386      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IConnectionScoped, IHandlerLifeCycleListener)
387      * @param sslOn true, is SSL should be activated
388      * @param sslContext the ssl context to use
389      * @throws UnknownHostException if the locale host cannot determined
390      * @throws IOException If some other I/O error occurs
391      */

392     public MultithreadedServer(String JavaDoc ipAddress, int port, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
393         this(InetAddress.getByName(ipAddress), port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, sslOn, sslContext);
394     }
395
396     
397     /**
398      * @deprecated
399      */

400     public MultithreadedServer(String JavaDoc ipAddress, int port, StreamSocketConfiguration socketConfiguration, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
401         this(InetAddress.getByName(ipAddress), port, socketConfiguration, handler, sslOn, sslContext);
402     }
403
404     /**
405      * constructor <br><br>
406      *
407      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
408      *
409      * @param ipAddress local ip address
410      * @param port local port
411      * @param options the acceptor socket options
412      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IConnectionScoped, IHandlerLifeCycleListener)
413      * @param sslOn true, is SSL should be activated
414      * @param sslContext the ssl context to use
415      * @throws UnknownHostException if the locale host cannot determined
416      * @throws IOException If some other I/O error occurs
417      */

418     public MultithreadedServer(String JavaDoc ipAddress, int port, Map JavaDoc<String JavaDoc, Object JavaDoc> options, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
419         this(InetAddress.getByName(ipAddress), port, options, handler, sslOn, sslContext);
420     }
421     
422     
423     /**
424      * constructor <br><br>
425      *
426      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
427      *
428      * @param address local address
429      * @param port local port
430      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IConnectionScoped, IHandlerLifeCycleListener)
431      * @param sslOn true, is SSL should be activated
432      * @param sslContext the ssl context to use
433      * @throws UnknownHostException if the locale host cannot determined
434      * @throws IOException If some other I/O error occurs
435      */

436     public MultithreadedServer(InetAddress JavaDoc address, int port, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
437         this(address, port, new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(), handler, sslOn, sslContext);
438     }
439     
440     
441     /**
442      * @deprecated
443      */

444     public MultithreadedServer(InetAddress JavaDoc address, int port, StreamSocketConfiguration socketConfiguration, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
445         this(address, port, socketConfiguration, handler, newServerWorkerPool(), sslOn, sslContext);
446         isSelfCreatedWorkerPool = true;
447     }
448     
449
450     /**
451      * constructor <br><br>
452      *
453      * For idle-, connection time out and the used workerpool see {@link MultithreadedServer#MultithreadedServer(IHandler)}
454      *
455      * @param address local address
456      * @param port local port
457      * @param options the socket options
458      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IConnectionScoped, IHandlerLifeCycleListener)
459      * @param sslOn true, is SSL should be activated
460      * @param sslContext the ssl context to use
461      * @throws UnknownHostException if the locale host cannot determined
462      * @throws IOException If some other I/O error occurs
463      */

464     public MultithreadedServer(InetAddress JavaDoc address, int port, Map JavaDoc<String JavaDoc, Object JavaDoc> options, IHandler handler, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
465         this(address, port, options, handler, newServerWorkerPool(), sslOn, sslContext);
466         isSelfCreatedWorkerPool = true;
467     }
468         
469     /**
470      * @deprecated
471      */

472     public MultithreadedServer(InetAddress JavaDoc address, int port, StreamSocketConfiguration socketConfiguration, IHandler appHandler, Executor JavaDoc workerpool, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
473         this(new InetSocketAddress JavaDoc(address, port), socketConfiguration.toOptions(), appHandler, workerpool, sslOn, sslContext);
474     }
475
476
477     /**
478      * constructor <br><br>
479      *
480      * For idle-, connection time out see {@link MultithreadedServer#MultithreadedServer(IHandler)}
481      *
482      * @param address local address
483      * @param port local port
484      * @param options the acceptor socket options
485      * @param handler the handler to use (supported: IConnectHandler, IDisconnectHandler, IDataHandler, ITimeoutHandler, IConnectionScoped, IHandlerLifeCycleListener)
486      * @param workerpool the workerpool to use
487      * @param sslOn true, is SSL should be activated
488      * @param sslContext the ssl context to use
489      * @throws UnknownHostException if the locale host cannot determined
490      * @throws IOException If some other I/O error occurs
491      */

492     public MultithreadedServer(InetAddress JavaDoc address, int port, Map JavaDoc<String JavaDoc, Object JavaDoc> options, IHandler appHandler, Executor JavaDoc workerpool, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
493         this(new InetSocketAddress JavaDoc(address, port), options, appHandler, workerpool, sslOn, sslContext);
494     }
495     
496     
497     private MultithreadedServer(InetSocketAddress JavaDoc address, Map JavaDoc<String JavaDoc, Object JavaDoc> options, IHandler appHandler, Executor JavaDoc workerpool, boolean sslOn, SSLContext sslContext) throws UnknownHostException JavaDoc, IOException JavaDoc {
498         this.address = address;
499         this.options = options;
500         this.appHandlerPrototype = appHandler;
501         this.workerpool = workerpool;
502         this.sslOn = sslOn;
503         this.sslContext = sslContext;
504         
505         ioHandlerContext.updateAppHandler(appHandler);
506         ioHandlerContext.updateWorkerpool(workerpool);
507     }
508     
509     
510
511     /**
512      * {@inheritDoc}
513      */

514     @SuppressWarnings JavaDoc("unchecked")
515     public final void run() {
516         
517         try {
518             if (appHandlerPrototype == null) {
519                 LOG.warning("no handler has been set. Call setHandler-method to set an assigned handler");
520             }
521             
522             
523             Runtime.getRuntime().addShutdownHook(new Thread JavaDoc() {
524                 @Override JavaDoc
525                 public void run() {
526                     close();
527                 }
528             });
529     
530
531             
532             // start listening
533
if (sslContext != null) {
534                 acceptor = new IoProvider().create(new AcceptorCallback(), ioHandlerContext, address, 0, options, sslContext, sslOn);
535             } else {
536                 acceptor = serverIoProvider.createAcceptor(new AcceptorCallback(), ioHandlerContext, address, 0, options);
537             }
538             acceptor.listen();
539
540             
541         } catch (Exception JavaDoc e) {
542             throw new RuntimeException JavaDoc(e.toString());
543         }
544     }
545
546     
547     /**
548      * {@inheritDoc}
549      */

550     public Object JavaDoc getOption(String JavaDoc name) throws IOException JavaDoc {
551         return acceptor.getOption(name);
552     }
553     
554     
555     
556     /**
557      * {@inheritDoc}
558      */

559     public Map JavaDoc<String JavaDoc, Class JavaDoc> getOptions() {
560         return acceptor.getOptions();
561     }
562     
563
564
565     /**
566      * {@inheritDoc}
567      */

568     @SuppressWarnings JavaDoc("unchecked")
569     public void close() {
570         if (isOpen) {
571             isOpen = false;
572
573             try {
574                 acceptor.close(); // closing of dispatcher will be initiated by acceptor
575
} catch (IOException JavaDoc ignore) { }
576             
577             if (isSelfCreatedWorkerPool) {
578                 if(workerpool instanceof ExecutorService JavaDoc) {
579                     ((ExecutorService JavaDoc) workerpool).shutdown();
580                 }
581             }
582         }
583     }
584
585
586     
587     private static final ExecutorService JavaDoc newServerWorkerPool() {
588         return Executors.newFixedThreadPool(250);
589     }
590
591
592
593     IAcceptor getAcceptor() {
594         return acceptor;
595     }
596     
597
598     /**
599      * {@inheritDoc}
600      */

601     public void addListener(IMutlithreadedServerListener listener) {
602         listeners.add(listener);
603 // dispatcherPool.addListener(listener);
604
}
605
606     
607     /**
608      * {@inheritDoc}
609      */

610     public boolean removeListener(IMutlithreadedServerListener listener) {
611         boolean result = listeners.remove(listener);
612 // dispatcherPool.removeListener(listener);
613

614         return result;
615     }
616
617     
618     /**
619      * {@inheritDoc}
620      *
621      * @deprecated use {@link IMultithreadedServer#getWorkerpool()} instead
622      */

623     public IWorkerPool getWorkerPool() {
624         return (IWorkerPool) workerpool;
625     }
626     
627     
628     /**
629      * {@inheritDoc}
630      */

631     public Executor JavaDoc getWorkerpool() {
632         return workerpool;
633     }
634     
635     
636     /**
637      * {@inheritDoc}
638      * @deprecated
639      */

640     @SuppressWarnings JavaDoc("unchecked")
641     public void setWorkerPool(IWorkerPool newWorkerPool) {
642         setWorkerPool((Executor JavaDoc) newWorkerPool);
643     }
644     
645     
646     @SuppressWarnings JavaDoc("unchecked")
647     private void setWorkerPool(Executor JavaDoc newWorkerPool) {
648         Executor JavaDoc oldWorkerPool = workerpool;
649
650         this.workerpool = newWorkerPool;
651  
652         if (isSelfCreatedWorkerPool) {
653             if(oldWorkerPool instanceof ExecutorService JavaDoc) {
654                 ((ExecutorService JavaDoc) oldWorkerPool).shutdown();
655             }
656         }
657         isSelfCreatedWorkerPool = false;
658         
659         ioHandlerContext.updateWorkerpool(workerpool);
660         
661         if (newWorkerPool instanceof IWorkerPool) {
662             for (IMutlithreadedServerListener listener : (ArrayList JavaDoc<IMutlithreadedServerListener>)listeners.clone()) {
663                 listener.onWorkerPoolUpdated(null, (IWorkerPool) newWorkerPool);
664             }
665         }
666     }
667
668
669     
670     
671     /**
672      * {@inheritDoc}
673      *
674      * @deprecated
675      */

676     public final void setDispatcherPoolSize(int size) {
677         LOG.warning("not implemented. Method will be removed");
678     }
679
680     /**
681      * {@inheritDoc}
682      *
683      * @deprecated
684      */

685     public int getDispatcherPoolSize() {
686         LOG.warning("not implemented. Method will be removed");
687         return -1;
688     }
689         
690
691     /**
692      * {@inheritDoc}
693      */

694     public boolean isOpen() {
695         return isOpen;
696     }
697
698
699
700     /**
701      * {@inheritDoc}
702      */

703     public void setHandler(IHandler appHandler) {
704         if (appHandler == null) {
705             throw new NullPointerException JavaDoc("handler is null");
706         }
707
708         if (isOpen) {
709             destroyCurrentHandler();
710             this.appHandlerPrototype = appHandler;
711             
712             ioHandlerContext.updateAppHandler(appHandlerPrototype);
713             initCurrentHandler();
714             
715         } else {
716             this.appHandlerPrototype = appHandler;
717             ioHandlerContext.updateAppHandler(appHandlerPrototype);
718         }
719     }
720
721     
722     
723     private void destroyCurrentHandler() {
724         if (appHandlerPrototype != null) {
725             if (ioHandlerContext.isLifeCycleHandler()) {
726                 ((org.xsocket.ILifeCycle) appHandlerPrototype).onDestroy();
727             }
728             appHandlerPrototype = null;
729         }
730     }
731     
732     private void initCurrentHandler() {
733         injectContext(appHandlerPrototype);
734         
735         if (ioHandlerContext.isLifeCycleHandler()) {
736             ((org.xsocket.ILifeCycle) appHandlerPrototype).onInit();
737         }
738     }
739     
740
741
742     
743     /**
744      * {@inheritDoc}
745      */

746     public final int getLocalPort() {
747         return address.getPort();
748     }
749     
750
751     /**
752      * {@inheritDoc}
753      */

754     public final InetAddress JavaDoc getLocalAddress() {
755         return address.getAddress();
756     }
757
758
759
760
761     /**
762      * {@inheritDoc}
763      *
764      * @deprecated no replacement
765      */

766     public final int getReceiveBufferPreallocationSize() {
767         LOG.warning("not implemented. Method will be removed");
768         return -1;
769     }
770
771     
772
773     /**
774      * {@inheritDoc}
775      *
776      * @deprecated use System.property instead. see {@link org.xsocket.stream.io.impl.IoProvider}
777      */

778     public void setReceiveBufferPreallocationSize(int size) {
779         LOG.warning("not implemented. Method will be removed");
780     }
781     
782
783     
784     
785     /**
786      * {@inheritDoc}
787      */

788     public void setConnectionTimeoutSec(int timeoutSec) {
789         this.connectionTimeoutSec = timeoutSec;
790     }
791
792     
793     /**
794      * {@inheritDoc}
795      */

796     public void setIdleTimeoutSec(int timeoutSec) {
797         this.idleTimeoutSec = timeoutSec;
798     }
799
800
801
802     /**
803      * {@inheritDoc}
804      */

805     public int getConnectionTimeoutSec() {
806         return connectionTimeoutSec;
807     }
808
809
810
811     /**
812      * {@inheritDoc}
813      */

814     public int getIdleTimeoutSec() {
815         return idleTimeoutSec;
816     }
817     
818     
819     
820     int getNumberOfOpenConnections() {
821         return acceptor.getNumberOfOpenConnections();
822     }
823
824     /**
825      * @deprecated
826      */

827     long getNumberOfHandledConnections() {
828         return -1;
829     }
830     
831     
832     
833
834
835     
836
837     private String JavaDoc getVersionInfo(String JavaDoc packName) {
838         Package JavaDoc p = Package.getPackage(packName);
839         if (p != null) {
840             String JavaDoc implVersion = p.getImplementationVersion();
841             if (implVersion == null) {
842                 implVersion = "";
843             }
844             return implVersion;
845         } else {
846             return "";
847         }
848     }
849
850     
851     
852
853     private void injectContext(IHandler hdl) {
854         IServerContext ctx = null;
855         Field JavaDoc[] fields = hdl.getClass().getDeclaredFields();
856         for (Field JavaDoc field : fields) {
857             if ((field.getType() == IServerContext.class) && (field.getAnnotation(Resource.class) != null)) {
858                 field.setAccessible(true);
859                 try {
860                     if (ctx == null) {
861                         ctx = new HandlerContext();
862                     }
863                     field.set(hdl, ctx);
864                 } catch (IllegalAccessException JavaDoc iae) {
865                     LOG.warning("couldn't set HandlerContext for attribute " + field.getName() + ". Reason " + iae.toString());
866                 }
867             }
868         }
869     }
870     
871     
872     private final class AcceptorCallback implements IAcceptorCallback {
873         
874         @SuppressWarnings JavaDoc("unchecked")
875         public void onConnected() {
876
877             address = acceptor.getLocalAddress();
878             isOpen = true;
879             
880             
881             // init app handler
882
initCurrentHandler();
883             
884             // notify listenes
885
for (IMutlithreadedServerListener listener : (ArrayList JavaDoc<IMutlithreadedServerListener>)listeners.clone()) {
886                 listener.onInit();
887             }
888
889             String JavaDoc versionInfo = getVersionInfo("org.xsocket").trim();
890             if (versionInfo.length() > 0) {
891                 versionInfo = "xSocket " + versionInfo;
892             }
893
894             
895             if (!(serverIoProvider instanceof IoProvider)) {
896                 String JavaDoc verInfo = getVersionInfo(serverIoProvider.getClass().getPackage().getName());
897                 if (verInfo.length() > 0) {
898                     versionInfo = versionInfo + "; " + serverIoProvider.getClass().getName() + " " + verInfo;
899                 }
900             }
901             
902             LOG.info("server listening on " + acceptor.getLocalAddress().toString() + " (" + versionInfo + ")");
903         }
904         
905         
906         @SuppressWarnings JavaDoc("unchecked")
907         public void onDisconnected() {
908             
909             destroyCurrentHandler();
910             
911             for (IMutlithreadedServerListener listener : (ArrayList JavaDoc<IMutlithreadedServerListener>)listeners.clone()) {
912                 listener.onDestroy();
913             }
914             
915             LOG.info("server has been shutdown");
916         }
917         
918         
919         public void onConnectionAccepted(IIoHandler ioHandler) throws IOException JavaDoc {
920             
921             IHandler hdl = appHandlerPrototype;
922             if (ioHandlerContext.isAppHandlerConnectionScoped()) {
923                 try {
924                     hdl = (IHandler) ((IConnectionScoped) appHandlerPrototype).clone();
925                 } catch (CloneNotSupportedException JavaDoc cne) {
926                     if (LOG.isLoggable(Level.FINE)) {
927                         LOG.fine("error occured by cloning appHandler " + appHandlerPrototype.getClass().getName() + ". " + cne.toString());
928                     }
929                 }
930             }
931             
932             
933             // create a new connection based on the socketHandler and set timeouts
934
INonBlockingConnection connection = new NonBlockingConnection(ioHandlerContext, ioHandler, hdl, serverIoProvider);
935             connection.setIdleTimeoutSec(idleTimeoutSec);
936             connection.setConnectionTimeoutSec(connectionTimeoutSec);
937         }
938     }
939
940     
941     private final class HandlerContext implements IServerContext {
942         
943         /**
944          * {@inheritDoc}
945          */

946         public int getLocalePort() {
947             return MultithreadedServer.this.getLocalPort();
948         }
949
950         /**
951          * {@inheritDoc}
952          */

953         public InetAddress JavaDoc getLocaleAddress() {
954             return MultithreadedServer.this.getLocalAddress();
955         }
956         
957         /**
958          * {@inheritDoc}
959          */

960         public int getNumberOfOpenConnections() {
961             return MultithreadedServer.this.getNumberOfOpenConnections();
962         }
963         
964         /**
965          * {@inheritDoc}
966          */

967         public IWorkerPool getWorkerPool() {
968             return MultithreadedServer.this.getWorkerPool();
969         }
970         
971         /**
972          * {@inheritDoc}
973          */

974         public Executor JavaDoc getWorkerpool() {
975             return MultithreadedServer.this.getWorkerpool();
976         }
977         
978         /**
979          * {@inheritDoc}
980          */

981         public int getReceiveBufferPreallocationSize() {
982             return MultithreadedServer.this.getReceiveBufferPreallocationSize();
983         }
984     }
985 }
986
Popular Tags