KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > quickserver > net > server > impl > BlockingClientHandler


1 /*
2  * This file is part of the QuickServer library
3  * Copyright (C) QuickServer.org
4  *
5  * Use, modification, copying and distribution of this software is subject to
6  * the terms and conditions of the GNU Lesser General Public License.
7  * You should have received a copy of the GNU LGP License along with this
8  * library; if not, you can download a copy from <http://www.quickserver.org/>.
9  *
10  * For questions, suggestions, bug-reports, enhancement-requests etc.
11  * visit http://www.quickserver.org
12  *
13  */

14
15 package org.quickserver.net.server.impl;
16
17 import org.quickserver.net.server.*;
18 import org.quickserver.net.*;
19 import org.quickserver.util.*;
20
21 import java.io.*;
22 import java.net.*;
23 import java.util.*;
24 import java.util.logging.*;
25
26 import java.nio.channels.*;
27
28 public class BlockingClientHandler extends BasicClientHandler {
29     private static final Logger logger = Logger.getLogger(BlockingClientHandler.class.getName());
30
31     public BlockingClientHandler(int instanceCount) {
32         super(instanceCount);
33     }
34
35     public BlockingClientHandler() {
36         super();
37     }
38
39     public void clean() {
40         logger.finest("Starting clean - "+getName());
41         super.clean();
42         logger.finest("Finished clean - "+getName());
43     }
44
45     protected void finalize() throws Throwable JavaDoc {
46         clean();
47         super.finalize();
48     }
49
50     public void handleClient(TheClient theClient) {
51         super.handleClient(theClient);
52     }
53
54     protected void setInputStream(InputStream in) throws IOException {
55         this.in = in;
56         if(getDataMode(DataType.IN) == DataMode.STRING) {
57             b_in = null;
58             o_in = null;
59             bufferedReader = new BufferedReader(new InputStreamReader(this.in));
60         } else if(getDataMode(DataType.IN) == DataMode.OBJECT) {
61             b_in = null;
62             bufferedReader = null;
63             o_in = new ObjectInputStream(in);
64         } else if(getDataMode(DataType.IN) == DataMode.BYTE ||
65                 getDataMode(DataType.IN) == DataMode.BINARY) {
66             o_in = null;
67             bufferedReader = null;
68             b_in = new BufferedInputStream(in);
69         }
70     }
71
72     public BufferedReader getBufferedReader() {
73         return bufferedReader;
74     }
75
76     public synchronized void closeConnection() {
77         if(connection==false) return;
78         connection = false;
79         try {
80             if(hasEvent(ClientEvent.MAX_CON_BLOCKING)==false) {
81                 notifyCloseOrLost();
82             }
83             
84             if(out!=null) {
85                 logger.finest("Closing output streams");
86                 try {
87                     out.flush();
88                 } catch(IOException ioe) {
89                     logger.finest("Flushing output streams failed: "+ioe);
90                 }
91                 
92                 if(socket!=null && isSecure()==false) {
93                     socket.shutdownOutput();
94                 }
95                 if(dataModeOUT == DataMode.OBJECT) {
96                     o_out.close();
97                 } else {
98                     b_out.close();
99                 }
100                 if(out!=null) out.close();
101             }
102
103             if(in!=null) {
104                 logger.finest("Closing input streams");
105                 //if(socket!=null) socket.shutdownInput();
106

107                 if(dataModeIN == DataMode.STRING) {
108                     if(bufferedReader!=null) bufferedReader.close();
109                 } else if(dataModeIN == DataMode.OBJECT) {
110                     o_in.close();
111                 } else {
112                     b_in.close();
113                 }
114                 if(in!=null) in.close();
115             }
116         } catch(IOException e) {
117             logger.warning("Error in closeConnection : "+e);
118             if(logger.isLoggable(Level.FINE)) {
119                 logger.fine("StackTrace:\n"+MyString.getStackTrace(e));
120             }
121         } catch(NullPointerException JavaDoc npe) {
122             logger.fine("NullPointerException: "+npe);
123             if(logger.isLoggable(Level.FINE)) {
124                 logger.fine("StackTrace:\n"+MyString.getStackTrace(npe));
125             }
126         }
127     }
128
129     public void run() {
130         if(unprocessedClientEvents.size()==0) {
131             logger.finest("No unprocessed ClientEvents!");
132             return;
133         }
134
135         ClientEvent currentEvent = (ClientEvent) unprocessedClientEvents.remove(0);
136
137         if(logger.isLoggable(Level.FINEST)) {
138             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
139             sb.append("Running ").append(getName());
140             sb.append(" using ");
141             sb.append(Thread.currentThread().getName());
142             sb.append(" for ");
143
144             synchronized(clientEvents) {
145                 if(clientEvents.size()>1) {
146                     sb.append(currentEvent+", Current Events - "+clientEvents);
147                 } else {
148                     sb.append(currentEvent);
149                 }
150             }
151             logger.finest(sb.toString());
152         }
153
154         if(currentEvent==null) {
155             threadEvent.set(null);
156             return;
157         } else {
158             threadEvent.set(currentEvent);
159         }
160
161         try {
162             if(socket==null)
163                 throw new SocketException("Socket was null!");
164
165             prepareForRun();
166
167             if(getThreadEvent()==ClientEvent.MAX_CON_BLOCKING) {
168                 processMaxConnection(currentEvent);
169             }
170
171             try {
172                 if(getThreadEvent()==ClientEvent.RUN_BLOCKING) {
173                     clientEventHandler.gotConnected(this);
174                 
175                     if(authorised == false) {
176                         if(clientAuthenticationHandler==null && authenticator == null) {
177                             authorised = true;
178                         } else {
179                             if(clientAuthenticationHandler!=null) {
180                                 AuthStatus authStatus = null;
181                                 do {
182                                     authStatus = processAuthorisation();
183                                 } while(authStatus==AuthStatus.FAILURE);
184
185                                 if(authStatus==AuthStatus.SUCCESS)
186                                     authorised = true;
187                             } else {
188                                 processAuthorisation();
189                             }
190                         }
191                     }//end of authorised
192

193                     processRead();
194                 }
195             } catch(SocketException e) {
196                 appLogger.finest("SocketException - Client [" +
197                     getHostAddress() +"]: " + e.getMessage());
198                 //e.printStackTrace();
199
lost = true;
200             } catch(AppException e) {
201                 //errors from Application
202
appLogger.finest("AppException "+Thread.currentThread().getName()+": "
203                     + e.getMessage());
204             } catch(javax.net.ssl.SSLException e) {
205                 lost = true;
206                 if(Assertion.isEnabled()) {
207                     appLogger.info("SSLException - Client ["+getHostAddress()
208                         +"] "+Thread.currentThread().getName()+": " + e);
209                 } else {
210                     appLogger.warning("SSLException - Client ["+
211                         getHostAddress()+"]: "+e);
212                 }
213             } catch(ConnectionLostException e) {
214                 lost = true;
215                 if(e.getMessage()!=null)
216                     appLogger.finest("Connection lost " +
217                         Thread.currentThread().getName()+": " + e.getMessage());
218                 else
219                     appLogger.finest("Connection lost "+Thread.currentThread().getName());
220             } catch(IOException e) {
221                 lost = true;
222                 appLogger.fine("IOError "+Thread.currentThread().getName()+": " + e);
223             } catch(AssertionError JavaDoc er) {
224                 logger.warning("[AssertionError] "+getName()+" "+er);
225                 if(logger.isLoggable(Level.FINEST)) {
226                     logger.finest("StackTrace "+Thread.currentThread().getName()+": "+MyString.getStackTrace(er));
227                 }
228                 assertionSystemExit();
229             } catch(Error JavaDoc er) {
230                 logger.warning("[Error] "+er);
231                 if(logger.isLoggable(Level.FINEST)) {
232                     logger.finest("StackTrace "+Thread.currentThread().getName()+": "+MyString.getStackTrace(er));
233                 }
234                 if(Assertion.isEnabled()) {
235                     assertionSystemExit();
236                 }
237                 lost = true;
238             } catch(RuntimeException JavaDoc re) {
239                 logger.warning("[RuntimeException] "+MyString.getStackTrace(re));
240                 if(Assertion.isEnabled()) {
241                     assertionSystemExit();
242                 }
243                 lost = true;
244             }
245             
246             if(getThreadEvent()!=ClientEvent.MAX_CON_BLOCKING) {
247                 notifyCloseOrLost();
248             }
249             
250             if(connection) {
251                 logger.finest(Thread.currentThread().getName()+" calling closeConnection()");
252                 closeConnection();
253             }
254         } catch(javax.net.ssl.SSLException se) {
255             logger.warning("SSLException "+Thread.currentThread().getName()+" - " + se);
256         } catch(IOException ie) {
257             logger.warning("IOError "+Thread.currentThread().getName()+" - Closing Client : " + ie);
258         } catch(RuntimeException JavaDoc re) {
259             logger.warning("[RuntimeException] "+getName()+" "+Thread.currentThread().getName()+" - "+MyString.getStackTrace(re));
260             if(Assertion.isEnabled()) {
261                 assertionSystemExit();
262             }
263         } catch(Exception JavaDoc e) {
264             logger.warning("Error "+Thread.currentThread().getName()+" - Event:"+getThreadEvent()+" - Socket:"+socket+" : "+e);
265             logger.fine("StackTrace: "+getName()+"\n"+MyString.getStackTrace(e));
266             if(Assertion.isEnabled()) {
267                 assertionSystemExit();
268             }
269         } catch(Error JavaDoc e) {
270             logger.warning("Error "+Thread.currentThread().getName()+" - Event:"+getThreadEvent()+" - Socket:"+socket+" : "+e);
271             logger.fine("StackTrace: "+getName()+"\n"+MyString.getStackTrace(e));
272             if(Assertion.isEnabled()) {
273                 assertionSystemExit();
274             }
275         }
276
277         synchronized(this) {
278             try {
279                 if(socket!=null && socket.isClosed()==false) {
280                     logger.finest("Closing Socket");
281                     socket.close();
282                 }
283             } catch(Exception JavaDoc re) {
284                 logger.warning("Error closing Socket/Channel: " +re);
285             }
286         }//end synchronized
287

288         willClean = true;
289         returnClientData();
290
291         boolean returnClientHandler = false;
292         synchronized(lockObj) {
293             returnClientHandler = checkReturnClientHandler();
294         }
295
296         if(returnClientHandler) {
297             returnClientHandler(); //return to pool
298
}
299     }
300
301     protected boolean checkReturnClientHandler() {
302         return true;
303     }
304
305     private void processRead() throws IOException, ClassNotFoundException JavaDoc, AppException {
306         AuthStatus authStatus = null;
307
308         String JavaDoc rec = null;
309         Object JavaDoc recObject = null; //v1.2
310
byte[] recByte = null; //1.4
311

312         while(connection) {
313             try {
314                 if(dataModeIN == DataMode.STRING) {
315                     rec = bufferedReader.readLine();
316                     if(rec==null) {
317                         lost = true;
318                         break;
319                     }
320                     if(getCommunicationLogging() && authorised == true) {
321                         appLogger.fine("Got STRING ["+getHostAddress()+"] : "+rec);
322                     }
323                     if(authorised == false)
324                         authStatus = clientAuthenticationHandler.handleAuthentication(this, rec);
325                     else
326                         clientCommandHandler.handleCommand(this, rec);
327                 } else if(dataModeIN == DataMode.OBJECT) {
328                     recObject = o_in.readObject();
329                     if(recObject==null) {
330                         lost = true;
331                         break;
332                     }
333                     if(getCommunicationLogging() && authorised == true) {
334                         appLogger.fine("Got OBJECT ["+getHostAddress()+"] : "+
335                             recObject.toString());
336                     }
337                     if(authorised == false)
338                         authStatus = clientAuthenticationHandler.handleAuthentication(this, recObject);
339                     else
340                         clientObjectHandler.handleObject(this, recObject);
341                 } else if(dataModeIN == DataMode.BYTE) {
342                     rec = readBytes();
343                     if(rec==null) {
344                         lost = true;
345                         break;
346                     }
347                     if(getCommunicationLogging() && authorised == true) {
348                         appLogger.fine("Got BYTE ["+getHostAddress()+"] : "+rec);
349                     }
350                     if(authorised == false)
351                         authStatus = clientAuthenticationHandler.handleAuthentication(this, rec);
352                     else
353                         clientCommandHandler.handleCommand(this, rec);
354                 } else if(dataModeIN == DataMode.BINARY) {
355                     recByte = readBinary();
356                     if(recByte==null) {
357                         lost = true;
358                         break;
359                     }
360                     if(getCommunicationLogging() && authorised == true) {
361                         appLogger.fine("Got BINARY ["+getHostAddress()+"] : "+MyString.getMemInfo(recByte.length));
362                     }
363                     if(authorised == false)
364                         authStatus = clientAuthenticationHandler.handleAuthentication(this, recByte);
365                     else
366                         clientBinaryHandler.handleBinary(this, recByte);
367                 } else {
368                     throw new IllegalStateException JavaDoc("Incoming DataMode is not supported: "+dataModeIN);
369                 }
370                 updateLastCommunicationTime();
371
372                 while(authStatus==AuthStatus.FAILURE)
373                     authStatus = processAuthorisation();
374
375                 if(authStatus==AuthStatus.SUCCESS)
376                     authorised = true;
377             } catch(SocketTimeoutException e) {
378                 handleTimeout(e);
379             }
380         }//end of while
381
}
382
383     protected void returnClientHandler() {
384         logger.finest(getName());
385         super.returnClientHandler();
386     }
387     
388     public void setDataMode(DataMode dataMode, DataType dataType)
389             throws IOException {
390         if(getDataMode(dataType)==dataMode) return;
391
392         appLogger.fine("Setting Type:"+dataType+", Mode:"+dataMode);
393         super.checkDataModeSet(dataMode, dataType);
394
395         setDataModeBlocking(dataMode, dataType);
396     }
397
398     private void setDataModeBlocking(DataMode dataMode, DataType dataType)
399             throws IOException {
400         logger.finest("ENTER");
401         if(dataMode == DataMode.STRING) {
402             if(dataType == DataType.OUT) {
403                 if(dataModeOUT == DataMode.BYTE || dataModeOUT == DataMode.BINARY) {
404                     dataModeOUT = dataMode;
405                 } else if(dataModeOUT == DataMode.OBJECT) {
406                     dataModeOUT = dataMode;
407                     o_out.flush(); o_out = null;
408                     b_out = new BufferedOutputStream(out);
409                 } else {
410                     Assertion.affirm(false, "Unknown DataType.OUT DataMode - "+dataModeOUT);
411                 }
412                 Assertion.affirm(b_out!=null, "BufferedOutputStream is still null!");
413             } else if(dataType == DataType.IN) {
414                 dataModeIN = dataMode;
415
416                 if(o_in!=null) {
417                     if(o_in.available()!=0)
418                         logger.warning("Data looks to be present in ObjectInputStream");
419                     o_in = null;
420                 }
421                 if(b_in!=null) {
422                     if(b_in.available()!=0)
423                         logger.warning("Data looks to be present in BufferedInputStream");
424                     b_in = null;
425                 }
426                 bufferedReader = new BufferedReader(new InputStreamReader(in));
427                 Assertion.affirm(bufferedReader!=null, "BufferedReader is still null!");
428             }
429         } else if(dataMode == DataMode.OBJECT) {
430             if(dataType == DataType.OUT) {
431                 dataModeOUT = dataMode;
432                 if(b_out!=null) {
433                     b_out.flush();
434                     b_out = null;
435                 }
436                 o_out = new ObjectOutputStream(out);
437                 Assertion.affirm(o_out!=null, "ObjectOutputStream is still null!");
438             } else if(dataType == DataType.IN) {
439                 dataModeIN = dataMode;
440                 if(b_in!=null) {
441                     if(b_in.available()!=0)
442                         logger.warning("Data looks to be present in BufferedInputStream");
443                     b_in = null;
444                 }
445                 bufferedReader = null;
446                 o_in = new ObjectInputStream(in); //will block
447
Assertion.affirm(o_in!=null, "ObjectInputStream is still null!");
448             }
449         } else if(dataMode == DataMode.BYTE || dataMode == DataMode.BINARY) {
450             if(dataType == DataType.OUT) {
451                 if(dataModeOUT == DataMode.STRING || dataModeOUT == DataMode.BYTE ||
452                         dataModeOUT == DataMode.BINARY) {
453                     dataModeOUT = dataMode;
454                 } else if(dataModeOUT == DataMode.OBJECT) {
455                     dataModeOUT = dataMode;
456                     if(o_out!=null) {
457                         o_out.flush();
458                         o_out = null;
459                     }
460                     b_out = new BufferedOutputStream(out);
461                 } else {
462                     Assertion.affirm(false, "Unknown DataType.OUT - DataMode: "+dataModeOUT);
463                 }
464                 Assertion.affirm(b_out!=null, "BufferedOutputStream is still null!");
465             } else if(dataType == DataType.IN) {
466                 dataModeIN = dataMode;
467                 if(o_in!=null) {
468                     if(o_in.available()!=0)
469                         logger.warning("Data looks to be present in ObjectInputStream");
470                     o_in = null;
471                 }
472                 bufferedReader = null;
473                 b_in = new BufferedInputStream(in);
474                 Assertion.affirm(b_in!=null, "BufferedInputStream is still null!");
475             } else {
476                 throw new IllegalArgumentException JavaDoc("Unknown DataType : "+dataType);
477             }
478         } else {
479             throw new IllegalArgumentException JavaDoc("Unknown DataMode : "+dataMode);
480         }
481     }
482
483     protected byte[] readInputStream() throws IOException {
484         return readInputStream(b_in);
485     }
486
487     public void updateInputOutputStreams() throws IOException {
488         setInputStream(getSocket().getInputStream());
489         setOutputStream(getSocket().getOutputStream());
490     }
491
492     public void setSocketChannel(SocketChannel socketChannel) {
493         if(true) throw new IllegalStateException JavaDoc("Can't set in blocking mode!");
494     }
495     public SocketChannel getSocketChannel() {
496         if(true) throw new IllegalStateException JavaDoc("Can't get in blocking mode!");
497         return null;
498     }
499
500     public void setSelectionKey(SelectionKey selectionKey) {
501         if(true) throw new IllegalStateException JavaDoc("Can't set in blocking mode!");
502     }
503     public SelectionKey getSelectionKey() {
504         if(true) throw new IllegalStateException JavaDoc("Can't get in blocking mode!");
505         return null;
506     }
507
508     public void registerForRead() throws IOException, ClosedChannelException {
509         if(true) throw new IllegalStateException JavaDoc("Can't register in blocking mode!");
510     }
511
512     public void registerForWrite() throws IOException, ClosedChannelException {
513         if(true) throw new IllegalStateException JavaDoc("Can't register in blocking mode!");
514     }
515
516     protected void setClientWriteHandler(ClientWriteHandler handler) {
517         if(true) throw new IllegalStateException JavaDoc("Can't register in blocking mode!");
518     }
519 }
520
Popular Tags