1 14 15 package org.quickserver.net.server.impl; 16 17 import org.quickserver.net.server.*; 18 import java.lang.reflect.*; 19 import java.net.*; 20 import java.io.*; 21 import java.util.logging.*; 22 23 34 public class DefaultClientEventHandler implements ClientEventHandler { 35 private static Logger logger = Logger.getLogger(DefaultClientEventHandler.class.getName()); 36 37 private ClientCommandHandler clientCommandHandler = null; 38 private Method gotConnectedMethod = null; 39 private Method lostConnectionMethod = null; 40 private Method closingConnectionMethod = null; 41 42 46 public void setClientCommandHandler(ClientCommandHandler handler) { 47 this.clientCommandHandler = handler; 48 if(clientCommandHandler!=null) 49 loadMethods(); 50 } 51 52 public void gotConnected(ClientHandler handler) 53 throws SocketTimeoutException, IOException { 54 if(gotConnectedMethod==null) 55 handler.sendSystemMsg("Connection opened: "+handler.getHostAddress()); 56 else 57 invoke(gotConnectedMethod, handler); 58 } 59 60 public void lostConnection(ClientHandler handler) 61 throws IOException { 62 if(lostConnectionMethod==null) 63 handler.sendSystemMsg("Connection lost: "+handler.getHostAddress()); 64 else 65 invoke(lostConnectionMethod, handler); 66 } 67 68 public void closingConnection(ClientHandler handler) 69 throws IOException { 70 if(closingConnectionMethod==null) 71 handler.sendSystemMsg("Connection closing: "+handler.getHostAddress()); 72 else 73 invoke(closingConnectionMethod, handler); 74 } 75 76 private void loadMethods() { 77 Class cls = clientCommandHandler.getClass(); 78 try { 79 gotConnectedMethod = cls.getMethod("gotConnected", 80 new Class [] {ClientHandler.class}); 81 } catch(NoSuchMethodException ex) { 82 logger.fine("Error finding gotConnected : "+ex); 83 } 84 try { 85 lostConnectionMethod = cls.getMethod("lostConnection", 86 new Class [] {ClientHandler.class}); 87 } catch(NoSuchMethodException ex) { 88 logger.fine("Error finding lostConnection : "+ex); 89 } 90 try { 91 closingConnectionMethod = cls.getMethod("closingConnection", 92 new Class [] {ClientHandler.class}); 93 } catch(NoSuchMethodException ex) { 94 logger.fine("Error finding lostConnection : "+ex); 95 } 96 } 97 98 private void invoke(Method method, ClientHandler handler) throws SocketTimeoutException, IOException { 99 try { 100 method.invoke(clientCommandHandler, new Object [] {handler}); 101 } catch(IllegalAccessException e) { 102 logger.warning("Error invoking "+method+" : "+e); 103 } catch(InvocationTargetException e) { 104 Exception cause = (Exception ) e.getCause(); 105 if(cause!=null) { 106 if(SocketTimeoutException.class.isInstance(cause)) 107 throw (SocketTimeoutException) cause; 108 else if(IOException.class.isInstance(cause)) 109 throw (IOException) cause; 110 } 111 logger.warning("Error invoking "+method+" : "+e+"\n Cause: "+cause); 112 IOException ioe = new IOException(); 113 ioe.initCause(cause); 114 throw ioe; 115 } 116 } 117 } 118 | Popular Tags |