1 14 15 package org.quickserver.net.server; 16 17 import java.io.*; 18 import java.net.*; 19 20 import org.quickserver.net.*; 21 import org.quickserver.net.qsadmin.*; 23 import java.util.logging.*; 25 import org.quickserver.util.pool.*; 27 import org.quickserver.util.pool.thread.*; 28 import org.apache.commons.pool.*; 29 import org.quickserver.util.xmlreader.*; 30 import org.quickserver.sql.*; 31 import java.util.*; 33 import org.quickserver.util.*; 35 import java.util.regex.*; 36 import org.quickserver.security.*; 38 import javax.net.ssl.*; 40 import javax.net.*; 41 import java.security.*; 42 import java.security.cert.*; 43 import org.quickserver.util.io.*; 44 import java.nio.*; 46 import java.nio.channels.*; 47 import org.quickserver.net.server.impl.*; 48 49 113 public class QuickServer implements Runnable , Service, Cloneable , Serializable { 114 117 private final static String VER = "1.4.7"; private final static String NEW_LINE = "\r\n"; 121 122 static { 123 System.out.print("Loading QuickServer v"+getVersion()+" "); 124 } 125 126 private String serverBanner; 127 128 private String clientAuthenticationHandlerString; private String clientEventHandlerString; private String clientExtendedEventHandlerString; private String clientCommandHandlerString; 132 private String clientObjectHandlerString; private String clientBinaryHandlerString; private String clientWriteHandlerString; private String clientDataString; 136 137 private Authenticator authenticator; 138 private ClientAuthenticationHandler clientAuthenticationHandler; private ClientEventHandler clientEventHandler; private ClientExtendedEventHandler clientExtendedEventHandler; private ClientCommandHandler clientCommandHandler; 142 private ClientObjectHandler clientObjectHandler; private ClientBinaryHandler clientBinaryHandler; private ClientWriteHandler clientWriteHandler; private ClientData clientData; 146 protected Class clientDataClass; 147 148 private int serverPort = 9876; 149 private Thread t; private ServerSocket server; 151 private String serverName = "QuickServer"; 152 private long maxConnection = -1; 153 private int socketTimeout = 60 * 1000; private String maxConnectionMsg = "-ERR Server Busy. Max Connection Reached"; 155 private String timeoutMsg = "-ERR Timeout"; 156 private String maxAuthTryMsg = "-ERR Max Auth Try Reached"; 157 private int maxAuthTry = 5; 159 static { 160 System.out.print("."); 161 } 162 163 private InetAddress ipAddr; 165 private boolean stopServer; 166 private Object [] storeObjects; 167 private QSAdminServer adminServer; 168 169 private static final Logger logger = Logger.getLogger(QuickServer.class.getName()); 172 private Logger appLogger; 174 175 private long suspendMaxConnection; private String suspendMaxConnectionMsg; private int serviceState = Service.UNKNOWN; 179 180 static { 181 System.out.print("."); 182 } 183 184 private QuickServerConfig config = new QuickServerConfig(); 186 private String consoleLoggingformatter; 187 private String consoleLoggingLevel = "INFO"; 188 private ClientPool pool; 189 private ObjectPool clientHandlerPool; 190 private ObjectPool clientDataPool; 191 private DBPoolUtil dBPoolUtil; 192 193 private String loggingLevel = "INFO"; 195 196 private boolean skipValidation = false; 198 private boolean communicationLogging = true; 199 200 private String securityManagerClass; 202 private AccessConstraintConfig accessConstraintConfig; 203 private ClassLoader classLoader; 204 private String applicationJarPath; 205 private ServerHooks serverHooks; 206 private ArrayList listOfServerHooks; 207 208 static { 209 System.out.print("."); 210 } 211 212 private Secure secure; 214 private BasicServerConfig basicConfig = config; 215 private SSLContext sslc; 216 private KeyManager km[] = null; 217 private TrustManager tm[] = null; 218 private boolean runningSecure = false; 219 private SecureStoreManager secureStoreManager = null; 220 221 private Exception exceptionInRun = null; 222 223 private ServerSocketChannel serverSocketChannel; 225 private Selector selector; 226 private boolean blockingMode = true; 227 private ObjectPool byteBufferPool; 228 private java.util.Date lastStartTime; 229 private ClientIdentifier clientIdentifier; 230 private GhostSocketReaper ghostSocketReaper; 231 private PoolManager poolManager; 232 private QSObjectPoolMaker qsObjectPoolMaker; 233 234 private DataMode defaultDataModeIN = DataMode.STRING; 236 private DataMode defaultDataModeOUT = DataMode.STRING; 237 238 private Throwable serviceError; 240 private Map registerChannelRequestMap; 241 242 static { 243 System.out.println(" Done"); 244 } 249 250 251 public static final String getVersion() { 252 return VER; 253 } 254 255 259 public static final float getVersionNo() { 260 return getVersionNo(VER); 261 } 262 263 267 public static final float getVersionNo(String ver) { 268 float version = 0; 270 int i = ver.indexOf(" "); if(i == -1) 272 i = ver.length(); 273 ver = ver.substring(0, i); 274 275 i = ver.indexOf("."); if(i!=-1) { 277 int j = ver.indexOf(".", i); 278 if(j!=-1) { 279 ver = ver.substring(0, i)+"."+ 280 MyString.replaceAll(ver.substring(i+1), ".", ""); 281 } 282 } 283 284 try { 285 version = Float.parseFloat(ver); 286 } catch(NumberFormatException e) { 287 throw new RuntimeException ("Corrupt QuickServer"); 288 } 289 return version; 290 } 291 292 296 public static String getNewLine() { 297 return NEW_LINE; 298 } 299 300 303 public String toString() { 304 return serverName + " : " + getPort(); 305 } 306 307 324 public QuickServer() { 325 } 326 327 338 public QuickServer(String commandHandler) { 339 setClientCommandHandler(commandHandler); 340 } 341 342 354 public QuickServer(String commandHandler,int port) { 355 this(commandHandler); setPort(port); 357 } 358 359 367 public void startServer() throws AppException { 368 logger.fine("Starting "+getName()); 369 370 if(isClosed() == false) { 371 logger.warning("Server "+getName()+" already running."); 372 throw new AppException("Server "+getName()+" already running."); 373 } 374 375 if(serverBanner == null) { 376 serverBanner = "\n-------------------------------" + 377 "\n Name : " + getName() + 378 "\n Port : " + getPort() + 379 "\n-------------------------------\n"; 380 logger.finest("Default Server Banner Generated"); 381 } 382 try { 383 loadApplicationClasses(); 384 385 Class clientIdentifierClass = 387 getClass(getBasicConfig().getAdvancedSettings().getClientIdentifier(), true); 388 clientIdentifier = (ClientIdentifier) 389 clientIdentifierClass.newInstance(); 390 clientIdentifier.setQuickServer(QuickServer.this); 391 392 Class poolManagerClass = 394 getClass(getBasicConfig().getObjectPoolConfig().getPoolManager(), true); 395 poolManager = (PoolManager) poolManagerClass.newInstance(); 396 397 Class qsObjectPoolMakerClass = getClass( 399 getBasicConfig().getAdvancedSettings().getQSObjectPoolMaker(), true); 400 qsObjectPoolMaker = (QSObjectPoolMaker) qsObjectPoolMakerClass.newInstance(); 401 402 loadServerHooksClasses(); 403 processServerHooks(ServerHook.PRE_STARTUP); 404 405 if(getSecure().isLoad()==true) 406 loadSSLContext(); 408 loadBusinessLogic(); 409 } catch(ClassNotFoundException e) { 410 logger.severe("Could not load class/s : " + e.getMessage()); 411 throw new AppException("Could not load class/s : " + e.getMessage()); 412 } catch(InstantiationException e) { 413 logger.severe("Could not instantiate class/s : " + e.getMessage()); 414 throw new AppException("Could not instantiate class/s : "+e.getMessage()); 415 } catch(IllegalAccessException e) { 416 logger.severe("Illegal access to class/s : " + e.getMessage()); 417 throw new AppException("Illegal access to class/s : " + e.getMessage()); 418 } catch(IOException e) { 419 logger.severe("IOException : " + e.getMessage()); 420 logger.fine("StackTrace:\n"+MyString.getStackTrace(e)); 421 throw new AppException("IOException : " + e.getMessage()); 422 } catch(Exception e) { 423 logger.severe("Exception : " + e.getMessage()); 424 logger.fine("StackTrace:\n"+MyString.getStackTrace(e)); 425 throw new AppException("Exception : " + e); 426 } 427 428 if(getSecurityManagerClass()!=null) { 430 System.setSecurityManager(getSecurityManager()); 431 } 432 433 blockingMode = getBasicConfig().getServerMode().getBlocking(); 434 435 setServiceState(Service.INIT); 436 t = new Thread (this, "QuickServer - "+getName()); 437 t.start(); 438 439 do { 440 Thread.yield(); 441 } while(getServiceState()==Service.INIT); 442 443 if(getServiceState()!=Service.RUNNING) { 444 if(exceptionInRun!=null) 445 throw new AppException("Could not start server "+getName() 446 +"! Details: "+exceptionInRun); 447 else 448 throw new AppException("Could not start server "+getName()); 449 } 450 lastStartTime = new java.util.Date (); 451 logger.fine("Started "+getName()+", Date: "+lastStartTime); 452 } 453 454 462 public void stopServer() throws AppException { 463 processServerHooks(ServerHook.PRE_SHUTDOWN); 464 logger.warning("Stopping "+getName()); 465 stopServer = true; 466 Socket death = null; 467 if(isClosed()==true) { 468 logger.warning("Server "+getName()+" is not running!"); 469 throw new AppException("Server "+getName()+" is not running!"); 470 } 471 try { 472 if(getBlockingMode()==true) { 473 if(getSecure().isEnable()==false) { 474 death = new Socket(server.getInetAddress(), 475 server.getLocalPort()); 476 death.getInputStream().read(); 477 death.close(); 478 } else { 479 death = getSSLSocketFactory().createSocket( 480 server.getInetAddress(), server.getLocalPort()); 481 Thread.currentThread().sleep(100); 482 death.close(); 483 } 484 } 485 486 if(serverSocketChannel!=null) { 487 serverSocketChannel.close(); 488 } 489 490 } catch(IOException e){ 491 logger.fine("IOError stopping "+getName()+": "+e); 492 } catch(Exception e){ 493 logger.warning("Error stopping "+getName()+": "+e); 494 throw new AppException("Error in stopServer "+getName()+": "+e); 495 } 496 497 for(int i=0;getServiceState()!=Service.STOPPED;i++) { 498 try { 499 Thread.sleep(60); 500 } catch(Exception e) { 501 logger.warning("Error waiting for "+getName()+" to fully stop. Error: "+e); 502 } 503 if(i>1000) { 504 logger.severe("Server was not stopped even after 10sec.. will terminate now."); 505 System.exit(-1); 506 } 507 } 508 if(adminServer==null || getQSAdminServer().getServer()!=this) { 509 setClassLoader(null); 511 } 512 logger.info("Stopped "+getName()); 513 } 514 515 522 public void restartServer() throws AppException { 523 stopServer(); 524 startServer(); 525 } 526 527 531 public String getName() { 532 return serverName; 533 } 534 539 public void setName(String name) { 540 serverName = name; 541 logger.finest("Set to : "+name); 542 } 543 544 548 public String getServerBanner() { 549 return serverBanner; 550 } 551 560 public void setServerBanner(String banner) { 561 serverBanner = banner; 562 logger.finest("Set to : "+banner); 563 } 564 565 571 public void setPort(int port) { 572 if(port<0) { 573 throw new IllegalArgumentException ("Port number can not be less than 0!"); 574 } 575 serverPort=port; 576 logger.finest("Set to "+port); 577 } 578 582 public int getPort() { 583 if(isClosed()==false) { 584 return server.getLocalPort(); 585 } 586 587 if(getSecure().isEnable()==false) { 588 return serverPort; 589 } else { 590 int _port = getSecure().getPort(); 591 if(_port == -1) 592 return serverPort; 593 else 594 return _port; 595 } 596 } 597 598 605 public void setClientCommandHandler(String handler) { 606 clientCommandHandlerString = handler; 607 logger.finest("Set to "+handler); 608 } 609 615 public String getClientCommandHandler() { 616 return clientCommandHandlerString; 617 } 618 619 627 public void setClientAuthenticationHandler(String authenticator) { 628 clientAuthenticationHandlerString = authenticator; 629 logger.finest("Set to "+authenticator); 630 } 631 637 public String getClientAuthenticationHandler() { 638 return clientAuthenticationHandlerString; 639 } 640 641 650 public void setAuthenticator(String authenticator) { 651 clientAuthenticationHandlerString = authenticator; 652 logger.finest("Set to "+authenticator); 653 } 654 661 public String getAuthenticator() { 662 return clientAuthenticationHandlerString; 663 } 664 665 671 public void setClientData(String data) { 672 this.clientDataString = data; 673 logger.finest("Set to "+data); 674 } 675 681 public String getClientData() { 682 return clientDataString; 683 } 684 685 690 public void setTimeout(int time) { 691 if(time>0) 692 socketTimeout = time; 693 else 694 socketTimeout = 0; 695 logger.finest("Set to "+socketTimeout); 696 } 697 701 public int getTimeout() { 702 return socketTimeout; 703 } 704 705 710 public void setMaxAuthTry(int authTry) { 711 maxAuthTry = authTry; 712 logger.finest("Set to "+authTry); 713 } 714 719 public int getMaxAuthTry() { 720 return maxAuthTry; 721 } 722 723 729 public void setMaxAuthTryMsg(String msg) { 730 maxAuthTryMsg = msg; 731 logger.finest("Set to "+msg); 732 } 733 738 public String getMaxAuthTryMsg() { 739 return maxAuthTryMsg; 740 } 741 742 747 public void setTimeoutMsg(String msg) { 748 timeoutMsg = msg; 749 logger.finest("Set to "+msg); 750 } 751 755 public String getTimeoutMsg() { 756 return timeoutMsg; 757 } 758 759 private TheClient initTheClient() { 760 TheClient theClient = new TheClient(); 761 theClient.setServer(QuickServer.this); 762 theClient.setTimeoutMsg(getTimeoutMsg()); 763 theClient.setMaxAuthTry(getMaxAuthTry()); theClient.setMaxAuthTryMsg(getMaxAuthTryMsg()); 765 766 theClient.setClientEventHandler(clientEventHandler); 767 theClient.setClientExtendedEventHandler(clientExtendedEventHandler); theClient.setClientCommandHandler(clientCommandHandler); 769 theClient.setClientObjectHandler(clientObjectHandler); theClient.setClientBinaryHandler(clientBinaryHandler); theClient.setClientWriteHandler(clientWriteHandler); theClient.setAuthenticator(authenticator); theClient.setClientAuthenticationHandler(clientAuthenticationHandler); theClient.setTimeout(socketTimeout); 775 theClient.setMaxConnectionMsg(maxConnectionMsg); 776 theClient.setCommunicationLogging(getCommunicationLogging()); return theClient; 778 } 779 780 public void run() { 781 exceptionInRun = null; 782 TheClient theClient = initTheClient(); 783 try { 784 stopServer = false; 785 786 closeAllPools(); 787 initAllPools(); 788 789 makeServerSocket(); 790 System.out.println(serverBanner); setServiceState(Service.RUNNING); 793 processServerHooks(ServerHook.POST_STARTUP); if(getBlockingMode()==false) { 795 runNonBlocking(theClient); 796 if(stopServer==true) { 797 logger.finest("Closing selector for "+getName()); 798 selector.close(); 799 } 800 return; 801 } else { 802 runBlocking(theClient); 803 } 804 } catch(BindException e) { 805 exceptionInRun = e; 806 logger.severe(getName()+" BindException for Port "+getPort()+" @ "+ 807 getBindAddr().getHostAddress()+" : "+e.getMessage()); 808 } catch(javax.net.ssl.SSLException e) { 809 exceptionInRun = e; 810 logger.severe("SSLException "+e); 811 logger.fine("StackTrace:\n"+MyString.getStackTrace(e)); 812 } catch(IOException e) { 813 exceptionInRun = e; 814 logger.severe("IOError "+e); 815 logger.fine("StackTrace:\n"+MyString.getStackTrace(e)); 816 } catch(Exception e) { 817 exceptionInRun = e; 818 logger.severe("Error "+e); 819 logger.fine("StackTrace:\n"+MyString.getStackTrace(e)); 820 } finally { 821 if(getBlockingMode()==true) { 822 logger.warning("Closing "+getName()); 823 try { 824 if(isClosed()==false) { 825 server.close(); 826 } 827 } catch(Exception e){ 828 throw new RuntimeException (e); 829 } 830 server = null; 831 serverSocketChannel = null; 832 833 setServiceState(Service.STOPPED); 834 logger.warning("Closed "+getName()); 835 836 processServerHooks(ServerHook.POST_SHUTDOWN); 837 } else if(getBlockingMode()==false && exceptionInRun!=null) { 838 logger.warning("Closing "+getName()+" - Had Error: "+exceptionInRun); 839 try { 840 if(isClosed()==false) { 841 if(serverSocketChannel!=null) 842 serverSocketChannel.close(); 843 if(server!=null) 844 server.close(); 845 } 846 } catch(Exception e){ 847 throw new RuntimeException (e); 848 } 849 850 server = null; 851 serverSocketChannel = null; 852 853 setServiceState(Service.STOPPED); 854 logger.warning("Closed "+getName()); 855 856 processServerHooks(ServerHook.POST_SHUTDOWN); 857 } 858 } 859 } 861 866 public void setMaxConnection(long maxConnection) { 867 if(getServiceState()==Service.SUSPENDED) 868 suspendMaxConnection = maxConnection; 869 else 870 this.maxConnection = maxConnection; 871 logger.finest("Set to "+maxConnection); 872 } 873 878 public long getMaxConnection() { 879 return maxConnection; 880 } 881 882 886 public long getClientCount() { 887 if(clientHandlerPool != null) { 888 try { 889 return getClientHandlerPool().getNumActive(); 890 } catch(Exception e) { 891 return 0; 892 } 893 } 894 return 0; 895 } 896 897 904 public void setMaxConnectionMsg(String maxConnectionMsg) { 905 if(getServiceState() == Service.SUSPENDED) 906 suspendMaxConnectionMsg = maxConnectionMsg; 907 else 908 this.maxConnectionMsg = maxConnectionMsg; 909 logger.finest("Set to "+maxConnectionMsg); 910 } 911 917 public String getMaxConnectionMsg() { 918 return maxConnectionMsg; 919 } 920 921 932 public void setBindAddr(String bindAddr) 933 throws UnknownHostException { 934 ipAddr = InetAddress.getByName(bindAddr); 935 logger.finest("Set to "+bindAddr); 936 } 937 942 public InetAddress getBindAddr() { 943 if(ipAddr==null) { 944 try { 945 ipAddr = InetAddress.getByName("0.0.0.0"); 946 } catch(Exception e){ 947 logger.warning("Unable to create default ip(0.0.0.0) : "+e); 948 throw new RuntimeException ("Error: Unable to find servers own ip : "+e); 949 } 950 } 951 return ipAddr; 952 } 953 954 962 public void setStoreObjects(Object [] storeObjects) { 963 this.storeObjects = storeObjects; 964 } 965 966 972 public Object [] getStoreObjects() { 973 return storeObjects; 974 } 975 976 980 public void setQSAdminServerPort(int port) { 981 getQSAdminServer().getServer().setPort(port); 982 } 983 987 public int getQSAdminServerPort() { 988 return getQSAdminServer().getServer().getPort(); 989 } 990 991 996 public void setQSAdminServerAuthenticator(String authenticator) { 997 getQSAdminServer().getServer().setClientAuthenticationHandler(authenticator); 998 } 999 1004 public String getQSAdminServerAuthenticator() { 1005 return getQSAdminServer().getServer().getAuthenticator(); 1006 } 1007 1008 1020 public void startQSAdminServer(int port, String authenticator) 1021 throws AppException { 1022 getQSAdminServer().setClientAuthenticationHandler(authenticator); 1023 getQSAdminServer().startServer(port); 1024 } 1025 1030 public void startQSAdminServer() throws AppException { 1031 getQSAdminServer().startServer(); 1032 } 1033 1034 1038 public QSAdminServer getQSAdminServer() { 1039 if(adminServer==null) 1040 adminServer = new QSAdminServer(QuickServer.this); 1041 return adminServer; 1042 } 1043 1044 1048 public void setQSAdminServer(QSAdminServer adminServer) { 1049 if(adminServer==null) 1050 this.adminServer = adminServer; 1051 } 1052 1053 1057 public boolean isClosed() { 1058 if(server==null) 1059 return true; 1060 return server.isClosed(); 1061 } 1062 1063 1068 public Logger getAppLogger() { 1069 if(appLogger!=null) 1070 return appLogger; 1071 return logger; 1072 } 1073 1077 public void setAppLogger(Logger appLogger) { 1078 this.appLogger = appLogger; 1079 } 1080 1081 1089 public void setClientObjectHandler(String handler) { 1090 clientObjectHandlerString = handler; 1091 logger.finest("Set to "+handler); 1092 } 1093 1099 public String getClientObjectHandler() { 1100 return clientObjectHandlerString; 1101 } 1102 1103 1109 public void setConsoleLoggingFormatter(String formatter) 1110 throws ClassNotFoundException , InstantiationException , 1111 IllegalAccessException { 1112 if(formatter==null) 1113 return; 1114 consoleLoggingformatter = formatter; 1115 1116 Formatter conformatter = 1117 (Formatter) getClass(formatter, true).newInstance(); 1118 Logger jdkLogger = Logger.getLogger(""); 1119 Handler[] handlers = jdkLogger.getHandlers(); 1120 for(int index = 0; index < handlers.length; index++ ) { 1121 if(ConsoleHandler.class.isInstance(handlers[index])) { 1122 handlers[index].setFormatter(conformatter); 1123 } 1124 } 1125 logger.finest("Set to "+formatter); 1126 } 1127 1128 1132 public String getConsoleLoggingFormatter() { 1133 return consoleLoggingformatter; 1134 } 1135 1136 1141 public void setConsoleLoggingToMini() { 1142 try { 1143 setConsoleLoggingFormatter("org.quickserver.util.logging.MiniFormatter"); 1144 } catch(Exception e) { 1145 logger.warning("Setting to logging.MiniFormatter : "+e); 1146 } 1147 } 1148 1149 1154 public void setConsoleLoggingToMicro() { 1155 try { 1156 setConsoleLoggingFormatter("org.quickserver.util.logging.MicroFormatter"); 1157 } catch(Exception e) { 1158 logger.warning("Setting to MicroFormatter : "+e); 1159 } 1160 } 1161 1162 1166 public void setConsoleLoggingLevel(Level level) { 1167 Logger rlogger = Logger.getLogger(""); 1168 Handler[] handlers = rlogger.getHandlers(); 1169 for(int index = 0; index < handlers.length; index++ ) { 1170 if(ConsoleHandler.class.isInstance(handlers[index])) { 1171 handlers[index].setLevel(level); 1172 } 1173 } 1174 if(level==Level.SEVERE) 1175 consoleLoggingLevel = "SEVERE"; 1176 else if(level==Level.WARNING) 1177 consoleLoggingLevel = "WARNING"; 1178 else if(level==Level.INFO) 1179 consoleLoggingLevel = "INFO"; 1180 else if(level==Level.CONFIG) 1181 consoleLoggingLevel = "CONFIG"; 1182 else if(level==Level.FINE) 1183 consoleLoggingLevel = "FINE"; 1184 else if(level==Level.FINER) 1185 consoleLoggingLevel = "FINER"; 1186 else if(level==Level.FINEST) 1187 consoleLoggingLevel = "FINEST"; 1188 else 1189 consoleLoggingLevel = "UNKNOWN"; 1190 1191 logger.fine("Set to "+level); 1192 } 1193 1194 1198 public String getConsoleLoggingLevel() { 1199 return consoleLoggingLevel; 1200 } 1201 1202 1206 public void setLoggingLevel(Level level) { 1207 Logger rlogger = Logger.getLogger(""); 1208 Handler[] handlers = rlogger.getHandlers(); 1209 for(int index = 0; index < handlers.length; index++ ) { 1210 handlers[index].setLevel(level); 1211 } 1212 1213 if(level==Level.SEVERE) 1214 loggingLevel = "SEVERE"; 1215 else if(level==Level.WARNING) 1216 loggingLevel = "WARNING"; 1217 else if(level==Level.INFO) 1218 loggingLevel = "INFO"; 1219 else if(level==Level.CONFIG) 1220 loggingLevel = "CONFIG"; 1221 else if(level==Level.FINE) 1222 loggingLevel = "FINE"; 1223 else if(level==Level.FINER) 1224 loggingLevel = "FINER"; 1225 else if(level==Level.FINEST) 1226 loggingLevel = "FINEST"; 1227 else 1228 loggingLevel = "UNKNOWN"; 1229 1230 consoleLoggingLevel = loggingLevel; 1231 1232 logger.fine("Set to "+level); 1233 } 1234 1235 1240 public Throwable getServiceError() { 1241 return serviceError; 1242 } 1243 1244 1249 public synchronized boolean initService(Object param[]) { 1250 serviceError = null; 1251 try { 1252 initServer(param); 1253 } catch(Exception e) { 1254 serviceError = e; 1255 return false; 1256 } 1257 return true; 1258 } 1259 1260 1265 public synchronized boolean initService(QuickServerConfig qsConfig) { 1266 serviceError = null; 1267 try { 1268 initServer(qsConfig); 1269 } catch(Exception e) { 1270 serviceError = e; 1271 return false; 1272 } 1273 return true; 1274 } 1275 1276 1281 public boolean startService() { 1282 serviceError = null; 1283 if(getServiceState() == Service.RUNNING) 1284 return false; 1285 try { 1286 startServer(); 1287 } catch(AppException e) { 1288 serviceError = e; 1289 return false; 1290 } 1291 return true; 1292 } 1293 1294 1299 public boolean stopService() { 1300 serviceError = null; 1301 if(getServiceState() == Service.STOPPED) 1302 return false; 1303 try { 1304 stopServer(); 1305 clearAllPools(); 1306 } catch(AppException e) { 1307 serviceError = e; 1308 return false; 1309 } catch(Exception e) { 1310 serviceError = e; 1311 return false; 1312 } 1313 return true; 1314 } 1315 1316 1321 public boolean suspendService() { 1322 serviceError = null; 1323 if(getServiceState() == Service.RUNNING) { 1324 suspendMaxConnection = maxConnection; 1325 suspendMaxConnectionMsg = maxConnectionMsg; 1326 maxConnection = 0; 1327 maxConnectionMsg = "Service is suspended."; 1328 setServiceState(Service.SUSPENDED); 1329 logger.info("Service "+getName()+" is suspended."); 1330 return true; 1331 } 1332 return false; 1333 } 1334 1339 public boolean resumeService() { 1340 serviceError = null; 1341 if(getServiceState() == Service.SUSPENDED) { 1342 maxConnection = suspendMaxConnection; 1343 maxConnectionMsg = suspendMaxConnectionMsg; 1344 setServiceState(Service.RUNNING); 1345 logger.info("Service "+getName()+" resumed."); 1346 return true; 1347 } 1348 return false; 1349 } 1350 1354 public String info() { 1355 serviceError = null; 1356 StringBuffer buf = new StringBuffer (); 1357 buf.append(getName()+"\n"); 1358 buf.append(getBindAddr().getHostAddress()+" "+getPort()+"\n"); 1359 return buf.toString(); 1360 } 1361 1363 1369 public synchronized void initServer(Object param[]) throws AppException { 1370 QuickServerConfig qsConfig = null; 1371 try { 1372 qsConfig = ConfigReader.read( (String )param[0]); 1373 } catch(Exception e) { 1374 logger.severe("Could not init server from xml file "+ 1375 (new File((String )param[0]).getAbsolutePath())+" : " +e); 1376 throw new AppException("Could not init server from xml file",e); 1377 } 1378 initServer(qsConfig); 1379 } 1380 1381 1386 public synchronized void initServer(QuickServerConfig qsConfig) throws AppException { 1387 setConfig(qsConfig); 1388 try { 1389 configQuickServer(); 1390 1391 loadApplicationClasses(); 1392 1393 InitServerHooks ish = getConfig().getInitServerHooks(); 1395 if(ish!=null) { 1396 Iterator iterator = ish.iterator(); 1397 String initServerHookClassName = null; 1398 Class initServerHookClass = null; 1399 InitServerHook initServerHook = null; 1400 while(iterator.hasNext()) { 1401 initServerHookClassName = (String )iterator.next(); 1402 initServerHookClass = getClass(initServerHookClassName, true); 1403 initServerHook = (InitServerHook) initServerHookClass.newInstance(); 1404 1405 logger.info("Loaded init server hook: " + initServerHookClassName); 1406 logger.fine("Init server hook info: " + initServerHook.info()); 1407 initServerHook.handleInit(QuickServer.this); 1408 } 1409 } 1410 } catch(Exception e) { 1411 logger.severe("Could not load init server hook: " +e); 1412 logger.warning("StackTrace:\n"+MyString.getStackTrace(e)); 1413 throw new AppException("Could not load init server hook",e); 1414 } 1415 setServiceState(Service.INIT); 1416 logger.finest("\r\n"+MyString.getSystemInfo(getVersion())); 1417 } 1418 1419 1424 public int getServiceState() { 1425 return serviceState; 1426 } 1427 1432 public void setServiceState(int state) { 1433 serviceState = state; 1434 } 1435 1436 private void configConsoleLoggingLevel(QuickServer qs, String temp) { 1437 if(temp.equals("SEVERE")) 1438 qs.setConsoleLoggingLevel(Level.SEVERE); 1439 else if(temp.equals("WARNING")) 1440 qs.setConsoleLoggingLevel(Level.WARNING); 1441 else if(temp.equals("INFO")) 1442 qs.setConsoleLoggingLevel(Level.INFO); 1443 else if(temp.equals("CONFIG")) 1444 qs.setConsoleLoggingLevel(Level.CONFIG); 1445 else if(temp.equals("FINE")) 1446 qs.setConsoleLoggingLevel(Level.FINE); 1447 else if(temp.equals("FINER")) 1448 qs.setConsoleLoggingLevel(Level.FINER); 1449 else if(temp.equals("FINEST")) 1450 qs.setConsoleLoggingLevel(Level.FINEST); 1451 else 1452 logger.warning("unknown level "+temp); 1453 } 1454 1455 1459 public void configQuickServer(QuickServerConfig config) throws Exception { 1460 QuickServer qs = QuickServer.this; 1461 qs.setConfig(config); qs.setBasicConfig(config); 1463 String temp = config.getConsoleLoggingLevel(); 1464 configConsoleLoggingLevel(qs, temp); 1465 temp = null; 1466 1467 qs.setConsoleLoggingFormatter(config.getConsoleLoggingFormatter()); 1468 1469 qs.setName(config.getName()); 1470 qs.setPort(config.getPort()); 1471 qs.setClientEventHandler(config.getClientEventHandler()); 1472 qs.setClientCommandHandler(config.getClientCommandHandler()); 1473 if(config.getAuthenticator()!=null) 1474 qs.setAuthenticator(config.getAuthenticator()); else if(config.getClientAuthenticationHandler()!=null) 1476 qs.setClientAuthenticationHandler(config.getClientAuthenticationHandler()); qs.setClientObjectHandler(config.getClientObjectHandler()); 1478 qs.setClientBinaryHandler(config.getClientBinaryHandler()); qs.setClientWriteHandler(config.getClientWriteHandler()); qs.setClientData(config.getClientData()); 1481 qs.setClientExtendedEventHandler(config.getClientExtendedEventHandler()); 1482 qs.setDefaultDataMode(config.getDefaultDataMode()); qs.setServerBanner(config.getServerBanner()); 1484 qs.setTimeout(config.getTimeout()); 1485 qs.setMaxAuthTry(config.getMaxAuthTry()); 1486 qs.setMaxAuthTryMsg(config.getMaxAuthTryMsg()); 1487 qs.setTimeoutMsg(config.getTimeoutMsg()); 1488 qs.setMaxConnection(config.getMaxConnection()); 1489 qs.setMaxConnectionMsg(config.getMaxConnectionMsg()); 1490 qs.setBindAddr(config.getBindAddr()); 1491 qs.setCommunicationLogging(config.getCommunicationLogging()); 1493 qs.setSecurityManagerClass(config.getSecurityManagerClass()); 1495 qs.setAccessConstraintConfig(config.getAccessConstraintConfig()); 1496 temp = config.getApplicationJarPath(); 1497 if(temp!=null) { 1498 File ajp = new File(temp); 1499 if(ajp.isAbsolute()==false) { 1500 temp = config.getConfigFile(); 1501 ajp = new File(temp); 1502 temp = ajp.getParent() + File.separatorChar + 1503 config.getApplicationJarPath(); 1504 config.setApplicationJarPath(temp); 1505 temp = null; 1506 } 1507 qs.setApplicationJarPath(config.getApplicationJarPath()); 1508 if(config.getQSAdminServerConfig() != null ) { 1510 getQSAdminServer().getServer().setApplicationJarPath( 1511 config.getApplicationJarPath()); 1512 } 1513 } 1514 qs.setServerHooks(config.getServerHooks()); 1515 qs.setSecure(config.getSecure()); 1516 } 1517 1518 1522 public void configQuickServer(QSAdminServerConfig config) 1523 throws Exception { 1524 QuickServer qs = getQSAdminServer().getServer(); 1525 qs.setBasicConfig(config); 1526 1527 String temp = getConsoleLoggingLevel(); configConsoleLoggingLevel(qs, temp); 1530 1531 qs.setConsoleLoggingFormatter(getConsoleLoggingFormatter()); 1534 1535 qs.setClientEventHandler(config.getClientEventHandler()); qs.setClientCommandHandler(config.getClientCommandHandler()); 1537 qs.setName(config.getName()); 1538 qs.setPort(config.getPort()); 1539 if(config.getAuthenticator()!=null) 1540 qs.setAuthenticator(config.getAuthenticator()); else if(config.getClientAuthenticationHandler()!=null) 1542 qs.setClientAuthenticationHandler(config.getClientAuthenticationHandler()); qs.setClientObjectHandler(config.getClientObjectHandler()); 1544 qs.setClientBinaryHandler(config.getClientBinaryHandler()); qs.setClientWriteHandler(config.getClientWriteHandler()); qs.setClientData(config.getClientData()); 1547 qs.setClientExtendedEventHandler(config.getClientExtendedEventHandler()); qs.setDefaultDataMode(config.getDefaultDataMode()); qs.setServerBanner(config.getServerBanner()); 1550 qs.setTimeout(config.getTimeout()); 1551 qs.setMaxAuthTry(config.getMaxAuthTry()); 1552 qs.setMaxAuthTryMsg(config.getMaxAuthTryMsg()); 1553 qs.setTimeoutMsg(config.getTimeoutMsg()); 1554 qs.setMaxConnection(config.getMaxConnection()); 1555 qs.setMaxConnectionMsg(config.getMaxConnectionMsg()); 1556 qs.setBindAddr(config.getBindAddr()); 1557 qs.setCommunicationLogging(config.getCommunicationLogging()); 1559 getQSAdminServer().setCommandPlugin(config.getCommandPlugin()); 1560 if(config.getCommandShellEnable().equals("true")) 1562 getQSAdminServer().setShellEnable(true); 1563 getQSAdminServer().setPromptName(config.getCommandShellPromptName()); 1564 qs.setAccessConstraintConfig(config.getAccessConstraintConfig()); 1566 qs.setServerHooks(config.getServerHooks()); 1567 qs.setSecure(config.getSecure()); 1568 } 1569 1570 1575 public void configQuickServer() throws Exception { 1576 configQuickServer(getConfig()); 1577 if(getConfig().getQSAdminServerConfig() != null ) { 1578 configQuickServer(getConfig().getQSAdminServerConfig()); 1579 } 1580 } 1581 1582 1590 public static void main(String args[]) { 1591 try { 1592 if(args.length >= 1) { 1593 if(args[0].equals("-about")) { 1594 org.quickserver.net.server.gui.About.main(null); 1595 } else if(args[0].equals("-load") && args.length>=2) { 1596 QuickServer qs = QuickServer.load(args[1]); 1597 if(qs!=null) handleOptions(args, qs); 1598 } else { 1599 System.out.println(printUsage()); 1600 } 1601 } else { 1602 System.out.println(printUsage()); 1603 org.quickserver.net.server.gui.About.showAbout(); 1604 } 1605 } catch(Exception e) { 1606 e.printStackTrace(); 1607 } 1608 } 1609 1610 1614 public static QuickServer load(String xml) throws AppException { 1615 QuickServer qs = new QuickServer(); 1616 Object config[] = new Object [] {xml}; 1617 qs.initServer(config); 1618 qs.startServer(); 1619 if(qs.getConfig().getQSAdminServerConfig()!= null) { 1620 qs.startQSAdminServer(); 1621 } 1622 return qs; 1623 } 1624 1625 1626 private static String printUsage() { 1627 StringBuffer sb = new StringBuffer (); 1628 sb.append("QuickServer - Java library/framework for creating robust multi-client TCP servers.\n"); 1629 sb.append("Copyright (C) QuickServer.org\n\n"); 1630 sb.append("Usage: QuickServer [-options]\n"); 1631 sb.append("Where options include:\n"); 1632 sb.append(" -about\t"+"Opens About Dialog box\n"); 1633 sb.append(" -load <xml_config_file> [load-options]\t"+"Loads the server from xml file.\n"); 1634 sb.append(" Where load-options include:\n"); 1635 sb.append(" -fullXML2File <file_name>\t"+"Dumps the Full XML configuration of the QuickServer loaded.\n"); 1636 return sb.toString(); 1637 } 1638 1639 private static void handleOptions(String args[], QuickServer quickserver) { 1640 if(args.length<3) return; 1641 1642 if(args[2].equals("-fullXML2File") && args.length>=4) { 1643 File file = new File(args[3]); 1644 logger.info("Writing full xml configuration to file: "+file.getAbsolutePath()); 1645 try { 1646 TextFile.write(file, quickserver.getConfig().toXML(null)); 1647 } catch(Exception e) { 1648 logger.warning("Error writing full xml configuration: "+e); 1649 } 1650 } 1651 } 1652 1653 1657 public void clearAllPools() throws Exception { 1658 try { 1659 if(pool!=null) 1660 getClientPool().clear(); 1661 if(clientHandlerPool!=null) 1662 getClientHandlerPool().clear(); 1663 if(getClientDataPool()!=null) 1664 getClientDataPool().clear(); 1665 if(getDBPoolUtil()!=null) 1666 getDBPoolUtil().clean(); 1667 if(byteBufferPool!=null) 1668 getByteBufferPool().clear(); 1669 } catch(Exception e) { 1670 logger.warning("Error: "+e); 1671 throw e; 1672 } 1673 } 1674 1675 1679 public void closeAllPools() throws Exception { 1680 if(pool==null && clientHandlerPool==null && getClientDataPool()==null && 1681 getDBPoolUtil()==null && byteBufferPool==null) { 1682 return; 1683 } 1684 logger.fine("Closing pools for "+getName()); 1685 try { 1686 if(pool!=null && PoolHelper.isPoolOpen(getClientPool().getObjectPool())) { 1687 logger.finer("Closing ClientThread pool."); 1688 getClientPool().close(); 1689 } 1690 if(clientHandlerPool!=null && PoolHelper.isPoolOpen(getClientHandlerPool())) { 1691 logger.finer("Closing ClientHandler pool."); 1692 getClientHandlerPool().close(); 1693 } 1694 if(getClientDataPool()!=null && PoolHelper.isPoolOpen(getClientDataPool())) { 1695 logger.finer("Closing ClientData pool."); 1696 getClientDataPool().close(); 1697 } 1698 if(getDBPoolUtil()!=null) { 1699 logger.finer("Closing DB pool."); 1700 getDBPoolUtil().clean(); 1701 } 1702 if(byteBufferPool!=null && PoolHelper.isPoolOpen(getByteBufferPool())) { 1703 logger.finer("Closing ByteBuffer pool."); 1704 getByteBufferPool().close(); 1705 } 1706 logger.fine("Closed pools for "+getName()); 1707 } catch(Exception e) { 1708 logger.warning("Error closing pools for "+getName()+": "+e); 1709 throw e; 1710 } 1711 } 1712 1713 1717 public void initAllPools() throws Exception { 1718 logger.fine("Creating pools"); 1719 if(getBlockingMode()==false) { 1720 makeByteBufferPool(getBasicConfig().getObjectPoolConfig().getByteBufferObjectPoolConfig()); 1721 } 1722 1723 makeClientPool(getBasicConfig().getObjectPoolConfig().getThreadObjectPoolConfig()); 1724 1725 makeClientHandlerPool( 1726 getBasicConfig().getObjectPoolConfig().getClientHandlerObjectPoolConfig()); 1727 1728 if(clientDataClass!=null) { 1730 try { 1731 clientData = (ClientData)clientDataClass.newInstance(); 1732 if(PoolableObject.class.isInstance(clientData)==true) { 1733 PoolableObject po = (PoolableObject)clientData; 1734 if( po.isPoolable()==true) { 1735 makeClientDataPool(po.getPoolableObjectFactory(), 1736 getBasicConfig().getObjectPoolConfig().getClientDataObjectPoolConfig() ); 1737 } else { 1738 clientDataPool = null; 1739 logger.fine("ClientData is not poolable!"); 1740 } 1741 } 1742 } catch(Exception e) { 1743 logger.warning("Error: "+e); 1744 throw e; 1745 } 1746 } 1747 1748 try { 1749 makeDBObjectPool(); 1750 } catch(Exception e) { 1751 logger.warning("Error in makeDBObjectPool() : "+e); 1752 logger.fine("StackTrace:\n"+MyString.getStackTrace(e)); 1753 throw e; 1754 } 1755 logger.fine("Created pools"); 1756 } 1757 1758 1759 1765 public ClientPool getClientPool() { 1766 if(pool==null) 1767 throw new IllegalStateException ("No ClientPool available yet!"); 1768 return pool; 1769 } 1770 1771 1775 private void makeClientHandlerPool(PoolConfig opConfig) throws Exception { 1776 logger.finer("Creating ClientHandler pool"); 1777 PoolableObjectFactory factory = new ClientHandlerObjectFactory(getBlockingMode()); 1778 clientHandlerPool = poolManager.makeClientHandlerPool(factory, opConfig); 1779 poolManager.initPool(clientHandlerPool, opConfig); 1780 clientHandlerPool = makeQSObjectPool(clientHandlerPool); 1781 clientIdentifier.setClientHandlerPool((QSObjectPool)clientHandlerPool); 1782 } 1783 1784 1790 public ObjectPool getClientHandlerPool() { 1791 if(clientHandlerPool==null) 1792 throw new IllegalStateException ("No ClientHandler Pool available yet!"); 1793 return clientHandlerPool; 1794 } 1795 1796 1797 1801 public void setConfig(QuickServerConfig config) { 1802 this.config = config; 1803 } 1804 1805 1809 public QuickServerConfig getConfig() { 1810 return config; 1811 } 1812 1813 1817 private void makeClientDataPool(PoolableObjectFactory factory, 1818 PoolConfig opConfig) throws Exception { 1819 logger.finer("Creating ClientData pool"); 1820 clientDataPool = poolManager.makeClientDataPool(factory, opConfig); 1821 poolManager.initPool(clientDataPool, opConfig); 1822 clientDataPool = makeQSObjectPool(clientDataPool); 1823 } 1824 1825 1830 public ObjectPool getClientDataPool() { 1831 return clientDataPool; 1832 } 1833 1834 1840 public DBPoolUtil getDBPoolUtil() { 1841 return dBPoolUtil; 1842 } 1843 1847 public void setDBObjectPoolConfig(DBObjectPoolConfig dBObjectPoolConfig) { 1848 getConfig().setDBObjectPoolConfig(dBObjectPoolConfig); 1849 } 1850 1851 1855 private void makeDBObjectPool() throws Exception { 1856 if(getConfig().getDBObjectPoolConfig()!=null) { 1857 logger.fine("Creating DBObject Pool"); 1858 Class dbPoolUtilClass = getClass( 1860 getConfig().getDBObjectPoolConfig().getDbPoolUtil(), true); 1861 dBPoolUtil = (DBPoolUtil) dbPoolUtilClass.newInstance(); 1862 dBPoolUtil.setDatabaseConnections( 1863 getConfig().getDBObjectPoolConfig().getDatabaseConnectionSet().iterator()); 1864 dBPoolUtil.initPool(); 1865 } 1866 } 1867 1868 1889 public ClientHandler findFirstClientById(String id) { 1890 return clientIdentifier.findFirstClientById(id); 1891 } 1892 1893 1928 public Iterator findAllClient() { 1929 return clientIdentifier.findAllClient(); 1930 } 1931 1932 1953 public Iterator findAllClientById(String pattern) { 1954 return clientIdentifier.findAllClientById(pattern); 1955 } 1956 1957 1978 public ClientHandler findClientByKey(String key) { 1979 return clientIdentifier.findClientByKey(key); 1980 } 1981 1982 2003 public Iterator findAllClientByKey(String pattern) { 2004 return clientIdentifier.findAllClientByKey(pattern); 2005 } 2006 2007 2012 public void nextClientIsTrusted() { 2013 setSkipValidation(true); 2014 } 2015 2018 private boolean getSkipValidation() { 2019 return skipValidation; 2020 } 2021 2024 private synchronized void setSkipValidation(boolean validation) { 2025 skipValidation = validation; 2026 } 2027 2028 2033 public void setCommunicationLogging(boolean communicationLogging) { 2034 this.communicationLogging = communicationLogging; 2035 } 2036 2041 public boolean getCommunicationLogging() { 2042 return communicationLogging; 2043 } 2044 2045 2052 public void setSecurityManagerClass(String securityManagerClass) { 2053 if(securityManagerClass!=null) 2054 this.securityManagerClass = securityManagerClass; 2055 } 2056 2061 public String getSecurityManagerClass() { 2062 return securityManagerClass; 2063 } 2064 2065 public SecurityManager getSecurityManager() throws AppException { 2066 if(getSecurityManagerClass()==null) 2067 return null; 2068 SecurityManager sm = null; 2069 try { 2070 sm = (SecurityManager ) 2071 getClass(getSecurityManagerClass(), true).newInstance(); 2072 } catch(ClassNotFoundException e) { 2073 throw new AppException(e.getMessage()); 2074 } catch(InstantiationException e) { 2075 throw new AppException(e.getMessage()); 2076 } catch(IllegalAccessException e) { 2077 throw new AppException(e.getMessage()); 2078 } 2079 return sm; 2080 } 2081 2082 2086 public void setAccessConstraintConfig( 2087 AccessConstraintConfig accessConstraintConfig) { 2088 this.accessConstraintConfig = accessConstraintConfig; 2089 } 2090 2094 public AccessConstraintConfig getAccessConstraintConfig() { 2095 return accessConstraintConfig; 2096 } 2097 2098 2103 public void setClassLoader(ClassLoader classLoader) { 2104 this.classLoader = classLoader; 2105 Thread.currentThread().setContextClassLoader(classLoader); 2106 } 2107 2108 2113 public ClassLoader getClassLoader() { 2114 return classLoader; 2115 } 2116 2117 2121 public Class getClass(String name, boolean reload) 2122 throws ClassNotFoundException { 2123 if(name==null) throw new IllegalArgumentException ("Class name can't be null!"); 2124 logger.finest("Class: "+name+", reload: "+reload); 2125 if(reload==true && classLoader!=null) { 2126 return classLoader.loadClass(name); 2127 } else if(reload==true && classLoader==null && this.getClass().getClassLoader()!=null) { 2128 return this.getClass().getClassLoader().loadClass(name); 2129 } else if(reload==false && classLoader!=null) { 2130 return Class.forName(name, true, classLoader); 2131 } else { 2132 return Class.forName(name, true, this.getClass().getClassLoader()); 2133 } 2134 } 2135 2136 2143 protected void setApplicationJarPath(String applicationJarPath) { 2144 this.applicationJarPath = applicationJarPath; 2145 } 2146 2147 2154 public String getApplicationJarPath() { 2155 return applicationJarPath; 2156 } 2157 2158 2162 public void setServerHooks(ServerHooks serverHooks) { 2163 this.serverHooks = serverHooks; 2164 } 2165 2169 public ServerHooks getServerHooks() { 2170 if(serverHooks==null) 2171 serverHooks = new ServerHooks(); 2172 return serverHooks; 2173 } 2174 2175 2178 private void loadServerHooksClasses() { 2179 if(getServerHooks()==null) return; 2180 listOfServerHooks = new ArrayList(); 2181 ServerHook serverHook = null; 2182 String serverHookClassName = null; 2183 Class serverHookClass = null; 2184 2185 serverHook = new GhostSocketReaper(); 2187 serverHook.initHook(QuickServer.this); 2188 listOfServerHooks.add(serverHook); 2189 ghostSocketReaper = (GhostSocketReaper) serverHook; 2190 2191 Iterator iterator = getServerHooks().iterator(); 2193 while(iterator.hasNext()) { 2194 serverHookClassName = (String )iterator.next(); 2195 try { 2196 serverHookClass = getClass(serverHookClassName, true); 2197 serverHook = (ServerHook)serverHookClass.newInstance(); 2198 serverHook.initHook(QuickServer.this); 2199 listOfServerHooks.add(serverHook); 2200 logger.info("Loaded server hook: " + serverHookClassName); 2201 logger.fine("Server hook info: " + serverHook.info()); 2202 } catch(Exception e) { 2203 logger.warning("Could not load server hook ["+serverHookClassName+"]: " + e); 2204 logger.fine("StackTrace:\n"+MyString.getStackTrace(e)); 2205 } 2206 } } 2208 2209 2212 private void processServerHooks(int event) { 2213 if(listOfServerHooks==null) { 2214 logger.warning("listOfServerHooks was null!"); 2215 return; 2216 } 2217 ServerHook serverHook = null; 2218 boolean result = false; 2219 Iterator iterator = listOfServerHooks.iterator(); 2220 2221 String hooktype = "UNKNOWN"; 2222 switch(event) { 2223 case ServerHook.PRE_STARTUP: hooktype="PRE_STARTUP";break; 2224 case ServerHook.POST_STARTUP: hooktype="POST_STARTUP";break; 2225 case ServerHook.PRE_SHUTDOWN: hooktype="PRE_SHUTDOWN";break; 2226 case ServerHook.POST_SHUTDOWN: hooktype="POST_SHUTDOWN";break; 2227 } 2228 2229 while(iterator.hasNext()) { 2230 serverHook = (ServerHook)iterator.next(); 2231 try { 2232 result = serverHook.handleEvent(event); 2233 } catch(Exception e) { 2234 result = false; 2235 logger.warning("Error invoking "+hooktype+" hook ["+ 2236 serverHook.getClass().getName()+"]: " + e.getMessage()); 2237 } 2238 logger.fine("Invoked "+hooktype+" hook ["+ 2239 serverHook.getClass().getName()+"] was: "+result); 2240 } 2241 } 2242 2243 2247 public Object clone() { 2248 Object object = null; 2249 try { 2250 object = super.clone(); 2251 QuickServer _qs = (QuickServer) object; 2252 _qs.setQSAdminServer( new QSAdminServer(_qs) ); 2253 } catch(CloneNotSupportedException e) { 2254 logger.warning("Error cloning : "+e); } 2256 return object; 2257 } 2258 2259 2263 public void setSecure(Secure secure) { 2264 this.secure = secure; 2265 } 2266 2270 public Secure getSecure() { 2271 if(secure==null) secure = new Secure(); 2272 return secure; 2273 } 2274 2275 2279 public boolean isRunningSecure() { 2280 return runningSecure; 2281 } 2282 2283 2287 public void setRunningSecure(boolean runningSecure) { 2288 this.runningSecure = runningSecure; 2289 } 2290 2291 private File makeAbsoluteToConfig(String fileName) { 2292 Assertion.affirm(fileName!=null, "FileName can't be null"); 2293 return ConfigReader.makeAbsoluteToConfig(fileName, getConfig()); 2294 } 2295 2296 2300 protected void makeServerSocket() 2301 throws BindException, IOException { 2302 server = null; 2303 logger.finest("Binding "+getName()+" to IP: "+getBindAddr()); 2304 InetSocketAddress bindAddress = 2305 new InetSocketAddress(getBindAddr(), getPort()); 2306 2307 try { 2308 NetworkInterface ni = NetworkInterface.getByInetAddress(getBindAddr()); 2309 if(ni!=null) { 2310 logger.fine("NetworkInterface: "+ni); 2311 } 2312 } catch(Exception igrnore) {} 2313 catch(Error igrnore) {} 2314 2315 2316 if(getSecure().isEnable()==false) { 2317 logger.fine("Making a normal ServerSocket for "+getName()); 2318 setRunningSecure(false); 2319 2320 if(getBlockingMode()==false) { 2321 serverSocketChannel = ServerSocketChannel.open(); 2323 server = serverSocketChannel.socket(); 2324 server.bind(bindAddress, 2325 getBasicConfig().getAdvancedSettings().getBacklog()); 2326 } else { 2327 server = new ServerSocket(getPort(), getBasicConfig().getAdvancedSettings().getBacklog(), getBindAddr()); 2329 } 2330 } else { 2331 logger.fine("Making a secure ServerSocket for "+getName()); 2332 try { 2333 ServerSocketFactory ssf = 2334 getSSLContext().getServerSocketFactory(); 2335 SSLServerSocket serversocket = (SSLServerSocket) 2336 ssf.createServerSocket(getPort(), 2337 getBasicConfig().getAdvancedSettings().getBacklog(), 2338 getBindAddr()); 2339 serversocket.setNeedClientAuth(secure.isClientAuthEnable()); 2340 setRunningSecure(true); 2341 2342 secureStoreManager.logSSLServerSocketInfo(serversocket); 2343 2344 server = serversocket; 2345 serverSocketChannel = server.getChannel(); 2346 if(serverSocketChannel==null && getBlockingMode()==false) { 2347 logger.warning("Secure Server does not support Channel! So will run in blocking mode."); 2348 blockingMode = true; 2349 } 2350 } catch(NoSuchAlgorithmException e) { 2351 logger.warning("NoSuchAlgorithmException : "+e); 2352 throw new IOException("Error creating secure socket : "+e.getMessage()); 2353 } catch(KeyManagementException e) { 2354 logger.warning("KeyManagementException : "+e); 2355 throw new IOException("Error creating secure socket : "+e.getMessage()); 2356 } 2357 } 2358 2359 server.setReuseAddress(true); 2360 2361 if(getBlockingMode()==false) { 2362 logger.fine("Server Mode "+getName()+" - Non Blocking"); 2363 if(selector==null || selector.isOpen()==false) { 2364 logger.finest("Opening new selector"); 2365 selector = Selector.open(); 2366 } else { 2367 logger.finest("Reusing selector: "+selector); 2368 } 2369 serverSocketChannel.configureBlocking(false); 2370 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); 2371 selector.wakeup(); 2372 } else { 2373 logger.fine("Server Mode "+getName()+" - Blocking"); 2374 } 2375 } 2376 2377 2381 public void setBasicConfig(BasicServerConfig basicConfig) 2382 throws Exception { 2383 Assertion.affirm(basicConfig!=null, "BasicServerConfig can't be null"); 2384 this.basicConfig = basicConfig; 2385 } 2386 2387 2391 public BasicServerConfig getBasicConfig() { 2392 return basicConfig; 2393 } 2394 2395 2400 public void loadSSLContext() throws IOException { 2401 if(getSecure().isLoad()==false) { 2402 throw new IllegalStateException ("Secure setting is not yet enabled for loading!"); 2403 } 2404 logger.info("Loading Secure Context.."); 2405 km = null; 2406 tm = null; 2407 try { 2408 String ssManager = "org.quickserver.security.SecureStoreManager"; 2409 if(getSecure().getSecureStore()!=null) 2410 ssManager = getSecure().getSecureStore().getSecureStoreManager(); 2411 2412 Class secureStoreManagerClass = getClass(ssManager, true); 2413 2414 secureStoreManager = (SecureStoreManager) secureStoreManagerClass.newInstance(); 2415 2416 km = secureStoreManager.loadKeyManagers(getConfig()); 2417 logger.fine("KeyManager got"); 2418 2419 tm = secureStoreManager.loadTrustManagers(getConfig()); 2420 logger.fine("TrustManager got"); 2421 2422 sslc = secureStoreManager.getSSLContext(getConfig().getSecure().getProtocol()); 2423 sslc.init(km, tm, null); 2424 logger.fine("SSLContext loaded"); 2425 } catch(KeyStoreException e) { 2426 logger.warning("KeyStoreException : "+e); 2427 throw new IOException("Error creating secure socket : "+e.getMessage()); 2428 } catch(NoSuchAlgorithmException e) { 2429 logger.warning("NoSuchAlgorithmException : "+e); 2430 throw new IOException("Error creating secure socket : "+e.getMessage()); 2431 } catch(NoSuchProviderException e) { 2432 logger.warning("NoSuchProviderException : "+e); 2433 throw new IOException("Error creating secure socket : "+e.getMessage()); 2434 } catch(UnrecoverableKeyException e) { 2435 logger.warning("UnrecoverableKeyException : "+e); 2436 throw new IOException("Error creating secure socket : "+e.getMessage()); 2437 } catch(CertificateException e) { 2438 logger.warning("CertificateException : "+e); 2439 throw new IOException("Error creating secure socket : "+e.getMessage()); 2440 } catch(KeyManagementException e) { 2441 logger.warning("KeyManagementException : "+e); 2442 throw new IOException("Error creating secure socket : "+e.getMessage()); 2443 } catch(GeneralSecurityException e) { 2444 logger.warning("GeneralSecurityException : "+e); 2445 throw new IOException("Error creating secure socket : "+e.getMessage()); 2446 } catch(ClassNotFoundException e) { 2447 logger.warning("ClassNotFoundException : "+e); 2448 throw new IOException("Error creating secure socket : "+e.getMessage()); 2449 } catch(InstantiationException e) { 2450 logger.warning("InstantiationException : "+e); 2451 throw new IOException("Error creating secure socket : "+e.getMessage()); 2452 } catch(IllegalAccessException e) { 2453 logger.warning("IllegalAccessException : "+e); 2454 throw new IOException("Error creating secure socket : "+e.getMessage()); 2455 } 2456 } 2457 2458 2463 public SSLContext getSSLContext() 2464 throws IOException, NoSuchAlgorithmException, 2465 KeyManagementException { 2466 return getSSLContext(null); 2467 } 2468 2469 2479 public SSLContext getSSLContext(String protocol) 2480 throws IOException, NoSuchAlgorithmException, 2481 KeyManagementException { 2482 if(sslc==null) loadSSLContext(); 2483 if(protocol!=null && secureStoreManager!=null) { 2484 SSLContext _sslc = secureStoreManager.getSSLContext(protocol); 2485 _sslc.init(km, tm, null); 2486 return _sslc; 2487 } 2488 return sslc; 2489 } 2490 2491 2500 public SSLSocketFactory getSSLSocketFactory() 2501 throws IOException, NoSuchAlgorithmException, 2502 KeyManagementException { 2503 if(sslc==null) loadSSLContext(); 2504 return secureStoreManager.getSocketFactory(getSSLContext()); 2505 } 2506 2507 2518 public SSLSocketFactory getSSLSocketFactory(String protocol) 2519 throws IOException, NoSuchAlgorithmException, KeyManagementException { 2520 if(sslc==null) loadSSLContext(); 2521 return secureStoreManager.getSocketFactory(getSSLContext(protocol)); 2522 } 2523 2524 2532 public void setClientBinaryHandler(String handler) { 2533 clientBinaryHandlerString = handler; 2534 logger.finest("Set to "+handler); 2535 } 2536 2542 public String getClientBinaryHandler() { 2543 return clientBinaryHandlerString; 2544 } 2545 2546 2550 public void setSelector(Selector selector) { 2551 this.selector = selector; 2552 } 2553 2557 public Selector getSelector() { 2558 return selector; 2559 } 2560 2561 2565 private void runBlocking(TheClient theClient) throws Exception { 2566 Socket client = null; 2567 ClientHandler _chPolled = null; 2568 int linger = getBasicConfig().getAdvancedSettings().getSocketLinger(); 2569 2570 while(true) { 2573 client = server.accept(); 2576 2578 if(linger<0) { 2579 client.setSoLinger(false, 0); 2580 } else { 2581 client.setSoLinger(true, linger); 2582 } 2583 2584 if(stopServer) { 2585 try { 2587 client.close(); 2588 } catch(Exception e) {} 2589 break; 2590 } 2591 2592 if(checkAccessConstraint(client)==false) { 2593 continue; 2594 } 2595 2596 if(getSkipValidation()!=true && maxConnection != -1 && 2598 getClientHandlerPool().getNumActive() >= maxConnection) { 2599 theClient.setClientEvent(ClientEvent.MAX_CON_BLOCKING); 2600 } else { 2601 theClient.setClientEvent(ClientEvent.RUN_BLOCKING); 2602 } 2603 2604 theClient.setTrusted(getSkipValidation()); 2605 theClient.setSocket(client); 2606 theClient.setSocketChannel(client.getChannel()); 2608 if(clientDataClass != null) { 2609 if(getClientDataPool()==null) { 2610 clientData = (ClientData)clientDataClass.newInstance(); 2611 } else { 2612 clientData = (ClientData)getClientDataPool().borrowObject(); 2613 } 2614 theClient.setClientData(clientData); 2615 } 2616 2617 try { 2618 _chPolled = (ClientHandler) getClientHandlerPool().borrowObject(); 2619 _chPolled.handleClient(theClient); 2620 } catch(java.util.NoSuchElementException nsee) { 2621 logger.warning("Could not borrow ClientHandler from pool. Error: "+nsee); 2622 logger.warning("Closing Socket ["+client+"] since no ClientHandler available."); 2623 client.close(); 2624 } 2625 2626 if(_chPolled!=null) { 2627 try { 2628 getClientPool().addClient(_chPolled, true); 2629 } catch(java.util.NoSuchElementException nsee) { 2630 logger.warning("Could not borrow Thread from pool. Error: "+nsee); 2631 } 2635 _chPolled = null; 2636 } 2637 client = null; 2638 2639 setSkipValidation(false); 2641 } } 2643 2644 2648 private void runNonBlocking(TheClient theClient) throws Exception { 2649 int selectCount = 0; 2650 Iterator iterator = null; 2651 SelectionKey key = null; 2652 ServerSocketChannel serverChannel = null; 2653 SocketChannel socketChannel = null; 2654 Socket client = null; 2655 ClientHandler _chPolled = null; 2656 boolean stopServerProcessed = false; 2657 int linger = getBasicConfig().getAdvancedSettings().getSocketLinger(); 2658 registerChannelRequestMap = new HashMap(); 2659 2660 while(true) { 2661 selectCount = selector.select(500); 2662 2664 synchronized(registerChannelRequestMap) { 2666 if(registerChannelRequestMap.size()>0) { 2667 RegisterChannelRequest req = null; 2668 Object hashkey = null; 2669 iterator = registerChannelRequestMap.keySet().iterator(); 2670 while(iterator.hasNext()) { 2671 hashkey = iterator.next(); 2672 req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey); 2673 req.register(getSelector()); 2674 } 2675 iterator = null; 2676 registerChannelRequestMap.clear(); 2677 } } 2680 if(stopServer==true && stopServerProcessed==false) { 2681 logger.warning("Closing "+getName()); 2682 serverSocketChannel.close(); 2683 stopServerProcessed = true; 2684 2685 server = null; 2686 serverSocketChannel = null; 2687 2688 setServiceState(Service.STOPPED); 2689 logger.warning("Closed "+getName()); 2690 2691 processServerHooks(ServerHook.POST_SHUTDOWN); 2692 } 2693 2694 if(stopServer==false && stopServerProcessed==true) { 2695 logger.finest("Server must have re-started.. will break"); 2696 break; 2697 } 2698 2699 if(selectCount==0 && stopServerProcessed==true) { 2700 java.util.Set keyset = selector.keys(); 2701 if(keyset.isEmpty()==true && getClientCount()<=0) { 2702 break; 2703 } else { 2704 continue; 2705 } 2706 } else if(selectCount==0) { 2707 continue; 2708 } 2709 2710 iterator = selector.selectedKeys().iterator(); 2711 while(iterator.hasNext()) { 2712 key = (SelectionKey) iterator.next(); 2713 2714 if(key.isValid()==false) { 2715 iterator.remove(); 2716 continue; 2717 } 2718 2719 if(key.isAcceptable() && stopServer==false) { 2720 logger.finest("Key is Acceptable"); 2721 serverChannel = (ServerSocketChannel) key.channel(); 2722 socketChannel = serverChannel.accept(); 2723 2724 if(socketChannel==null) { 2725 iterator.remove(); 2726 continue; 2727 } 2728 2729 client = socketChannel.socket(); 2730 2731 if(linger<0) { 2732 client.setSoLinger(false, 0); 2733 } else { 2734 client.setSoLinger(true, linger); 2735 } 2736 2737 if(checkAccessConstraint(client)==false) { 2738 iterator.remove(); 2739 continue; 2740 } 2741 2742 socketChannel.configureBlocking(false); 2743 theClient.setTrusted(getSkipValidation()); 2744 theClient.setSocket(socketChannel.socket()); 2745 theClient.setSocketChannel(socketChannel); 2746 2747 if(clientDataClass != null) { 2748 if(getClientDataPool()==null) { 2749 clientData = (ClientData)clientDataClass.newInstance(); 2750 } else { 2751 clientData = (ClientData)getClientDataPool().borrowObject(); 2753 } 2754 theClient.setClientData(clientData); 2755 } 2756 2757 if(getSkipValidation()!=true && maxConnection != -1 && 2759 getClientHandlerPool().getNumActive() >= maxConnection) { 2760 theClient.setClientEvent(ClientEvent.MAX_CON); 2761 } else { 2762 theClient.setClientEvent(ClientEvent.ACCEPT); 2763 } 2764 2765 try { 2766 _chPolled = (ClientHandler)getClientHandlerPool().borrowObject(); 2767 logger.finest("Asking "+_chPolled.getName()+" to handle."); 2768 _chPolled.handleClient(theClient); 2769 } catch(java.util.NoSuchElementException nsee) { 2770 logger.warning("Could not borrow ClientHandler Object from pool. Error: "+nsee); 2771 logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no ClientHandler available."); 2772 socketChannel.close(); 2773 } 2774 2775 if(_chPolled!=null) { 2776 try { 2777 getClientPool().addClient(_chPolled, true); 2778 } catch(java.util.NoSuchElementException nsee) { 2779 logger.warning("Could not borrow Thread from pool. Error: "+nsee); 2780 } 2784 _chPolled = null; 2785 } 2786 socketChannel = null; 2787 client = null; 2788 2789 setSkipValidation(false); } else if(key.isValid() && key.isReadable()) { 2791 boolean addedEvent = false; 2792 ClientHandler _ch = null; 2793 try { 2794 _ch = (ClientHandler)key.attachment(); 2795 logger.finest("Key is Readable, removing OP_READ from interestOps for "+_ch.getName()); 2796 key.interestOps(key.interestOps() & (~SelectionKey.OP_READ)); 2797 _ch.addEvent(ClientEvent.READ);addedEvent= true; 2798 getClientPool().addClient(_ch); 2800 } catch(CancelledKeyException cke) { 2801 logger.fine("Ignored Error - Key was Cancelled: "+cke); 2802 } catch(java.util.NoSuchElementException nsee) { 2803 logger.finest("NoSuchElementException: "+nsee); 2804 if(addedEvent) _ch.removeEvent(ClientEvent.READ); 2805 continue; } 2807 _ch = null; 2808 } else if(key.isValid() && key.isWritable()) { 2809 if(getClientPool().shouldNioWriteHappen()==false) { 2810 continue; } 2812 boolean addedEvent = false; 2813 ClientHandler _ch = null; 2814 try { 2815 _ch = (ClientHandler)key.attachment(); 2816 logger.finest("Key is Writable, removing OP_WRITE from interestOps for "+_ch.getName()); 2817 key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); 2819 _ch.addEvent(ClientEvent.WRITE);addedEvent= true; 2820 getClientPool().addClient(_ch); 2822 } catch(CancelledKeyException cke) { 2823 logger.fine("Ignored Error - Key was Cancelled: "+cke); 2824 } catch(java.util.NoSuchElementException nsee) { 2825 logger.finest("NoSuchElementException: "+nsee); 2826 if(addedEvent) _ch.removeEvent(ClientEvent.WRITE); 2827 continue; } 2829 _ch = null; 2830 } else if(stopServer==true && key.isAcceptable()) { 2831 setSkipValidation(false); } else { 2834 logger.warning("Unknown key got in SelectionKey: "+key); 2835 } 2836 iterator.remove(); 2838 Thread.yield(); 2839 } iterator = null; 2841 } } 2843 2844 private boolean checkAccessConstraint(Socket socket) { 2845 try { 2846 if(getAccessConstraintConfig()!=null) { 2847 getAccessConstraintConfig().checkAccept(socket); 2848 } 2849 return true; 2850 } catch(SecurityException se) { 2851 logger.warning("SecurityException occurred accepting connection : " 2852 +se.getMessage()); 2853 return false; 2854 } 2855 } 2856 2857 2863 public boolean registerChannel(SocketChannel channel, int ops, Object att) 2864 throws IOException, ClosedChannelException { 2865 if(getSelector()==null) { 2866 throw new IllegalStateException ("Selector is not open!"); 2867 } 2868 if(channel==null) { 2869 throw new IllegalArgumentException ("Can't register a null channel!"); 2870 } 2871 2872 if(channel.isConnected()==false) { 2873 throw new ClosedChannelException(); 2874 } 2875 2876 RegisterChannelRequest req = new RegisterChannelRequest(channel, ops, att); 2877 RegisterChannelRequest reqOld = null; 2878 synchronized(registerChannelRequestMap) { 2879 reqOld = (RegisterChannelRequest) registerChannelRequestMap.get(channel); 2880 if(reqOld==null) { 2881 registerChannelRequestMap.put(channel, req); 2882 getSelector().wakeup(); 2883 return true; 2884 } else { 2885 if(reqOld.equals(req)==false) { 2886 reqOld.setOps(reqOld.getOps() | req.getOps()); 2887 reqOld.setAtt(req.getAtt()); 2888 return true; 2889 } 2890 return false; 2891 } 2892 } 2893 2900 } 2901 2902 2906 private void makeByteBufferPool(PoolConfig opConfig) { 2907 logger.finer("Creating ByteBufferPool pool"); 2908 2909 int bufferSize = getBasicConfig().getAdvancedSettings().getByteBufferSize(); 2910 boolean useDirectByteBuffer = getBasicConfig().getAdvancedSettings().getUseDirectByteBuffer(); 2911 PoolableObjectFactory factory = new ByteBufferObjectFactory(bufferSize, useDirectByteBuffer); 2912 2913 byteBufferPool = poolManager.makeByteBufferPool(factory, opConfig); 2914 poolManager.initPool(byteBufferPool, opConfig); 2915 } 2916 2917 2921 public ObjectPool getByteBufferPool() { 2922 return byteBufferPool; 2923 } 2924 2925 2929 private void makeClientPool(PoolConfig opConfig) throws Exception { 2930 logger.finer("Creating ClientThread pool"); 2931 ThreadObjectFactory factory = new ThreadObjectFactory(); 2932 ObjectPool objectPool = poolManager.makeClientPool(factory, opConfig); 2933 pool = new ClientPool(makeQSObjectPool(objectPool), opConfig); 2934 factory.setClientPool(pool); 2935 pool.setMaxThreadsForNioWrite( 2936 getBasicConfig().getAdvancedSettings().getMaxThreadsForNioWrite()); 2937 poolManager.initPool(objectPool, opConfig); 2938 } 2939 2940 2948 public void setClientWriteHandler(String handler) { 2949 clientWriteHandlerString = handler; 2950 logger.finest("Set to "+handler); 2951 } 2952 2958 public String getClientWriteHandler() { 2959 return clientWriteHandlerString; 2960 } 2961 2962 2967 public java.util.Date getLastStartTime() { 2968 return lastStartTime; 2969 } 2970 2971 2976 public static void setDebugNonBlockingMode(boolean flag) { 2977 org.quickserver.util.io.ByteBufferOutputStream.setDebug(flag); 2978 org.quickserver.util.io.ByteBufferInputStream.setDebug(flag); 2979 } 2980 2981 2985 public ClientIdentifier getClientIdentifier() { 2986 return clientIdentifier; 2987 } 2988 2989 2993 private QSObjectPool makeQSObjectPool(ObjectPool objectPool) 2994 throws Exception { 2995 return (QSObjectPool) qsObjectPoolMaker.getQSObjectPool(objectPool); 2996 } 2997 2998 2999 3003 public boolean getBlockingMode() { 3004 return blockingMode; 3005 } 3006 3007 3011 protected void loadBusinessLogic() throws Exception { 3012 if(clientCommandHandlerString == null && 3013 clientEventHandlerString == null) { 3014 logger.severe("ClientCommandHandler AND ClientEventHandler was not set."); 3015 throw new AppException("ClientCommandHandler AND ClientEventHandler was not set."); 3016 } 3017 3018 clientCommandHandler = null; 3019 if(clientCommandHandlerString != null) { 3020 logger.finest("Loading ClientCommandHandler class.."); 3021 Class clientCommandHandlerClass = 3022 getClass(clientCommandHandlerString, true); 3023 clientCommandHandler = (ClientCommandHandler) 3024 clientCommandHandlerClass.newInstance(); 3025 } 3026 3027 boolean setClientCommandHandlerLookup = false; 3028 clientEventHandler = null; 3029 if(clientEventHandlerString==null) { 3030 clientEventHandlerString = "org.quickserver.net.server.impl.DefaultClientEventHandler"; 3031 setClientCommandHandlerLookup = true; 3032 } 3033 logger.finest("Loading ClientEventHandler class.."); 3034 if(clientEventHandlerString.equals(clientCommandHandlerString) && 3035 ClientEventHandler.class.isInstance(clientCommandHandler)) { 3036 clientEventHandler = (ClientEventHandler) clientCommandHandler; 3037 } else { 3038 clientEventHandler = (ClientEventHandler) 3039 getClass(clientEventHandlerString, true).newInstance(); 3040 if(setClientCommandHandlerLookup) { 3041 ((DefaultClientEventHandler)clientEventHandler).setClientCommandHandler( 3042 clientCommandHandler); 3043 } 3044 } 3045 3046 clientExtendedEventHandler = null; 3047 if(clientExtendedEventHandlerString != null) { 3048 logger.finest("Loading ClientExtendedEventHandler class.."); 3049 if(clientExtendedEventHandlerString.equals(clientCommandHandlerString) && 3050 ClientExtendedEventHandler.class.isInstance(clientCommandHandler)) { 3051 clientExtendedEventHandler = (ClientExtendedEventHandler) clientCommandHandler; 3052 } else if(clientExtendedEventHandlerString.equals(clientEventHandlerString) && 3053 ClientExtendedEventHandler.class.isInstance(clientEventHandler)) { 3054 clientExtendedEventHandler = (ClientExtendedEventHandler) clientEventHandler; 3055 } else { 3056 Class clientExtendedEventHandlerClass = 3057 getClass(clientExtendedEventHandlerString, true); 3058 clientExtendedEventHandler = (ClientExtendedEventHandler) 3059 clientExtendedEventHandlerClass.newInstance(); 3060 } 3061 } 3062 3063 clientObjectHandler = null; 3064 if(clientObjectHandlerString != null) { 3065 logger.finest("Loading ClientObjectHandler class.."); 3066 if(clientObjectHandlerString.equals(clientCommandHandlerString) && 3067 ClientObjectHandler.class.isInstance(clientCommandHandler)) { 3068 clientObjectHandler = (ClientObjectHandler) clientCommandHandler; 3069 } else if(clientObjectHandlerString.equals(clientEventHandlerString) && 3070 ClientObjectHandler.class.isInstance(clientEventHandler)) { 3071 clientObjectHandler = (ClientObjectHandler) clientEventHandler; 3072 } else if(clientObjectHandlerString.equals(clientExtendedEventHandlerString) && 3073 ClientObjectHandler.class.isInstance(clientExtendedEventHandler)) { 3074 clientObjectHandler = (ClientObjectHandler) clientExtendedEventHandler; 3075 } else { 3076 clientObjectHandler = (ClientObjectHandler) 3077 getClass(clientObjectHandlerString, true).newInstance(); 3078 } 3079 } 3081 clientBinaryHandler = null; 3082 if(clientBinaryHandlerString != null) { 3083 logger.finest("Loading ClientBinaryHandler class.."); 3084 if(clientBinaryHandlerString.equals(clientCommandHandlerString) && 3085 ClientBinaryHandler.class.isInstance(clientCommandHandler)) { 3086 clientBinaryHandler = (ClientBinaryHandler) clientCommandHandler; 3087 } else if(clientBinaryHandlerString.equals(clientEventHandlerString) && 3088 ClientBinaryHandler.class.isInstance(clientEventHandler)) { 3089 clientBinaryHandler = (ClientBinaryHandler) clientEventHandler; 3090 } else if(clientBinaryHandlerString.equals(clientExtendedEventHandlerString) && 3091 ClientBinaryHandler.class.isInstance(clientExtendedEventHandler)) { 3092 clientBinaryHandler = (ClientBinaryHandler) clientExtendedEventHandler; 3093 } else if(clientBinaryHandlerString.equals(clientObjectHandlerString) && 3094 ClientBinaryHandler.class.isInstance(clientObjectHandler)) { 3095 clientBinaryHandler = (ClientBinaryHandler) clientObjectHandler; 3096 } else { 3097 clientBinaryHandler = (ClientBinaryHandler) 3098 getClass(clientBinaryHandlerString, true).newInstance(); 3099 } 3100 } 3102 clientWriteHandler = null; 3103 if(clientWriteHandlerString != null) { 3104 logger.finest("Loading ClientWriteHandler class.."); 3105 if(clientWriteHandlerString.equals(clientCommandHandlerString) && 3106 ClientWriteHandler.class.isInstance(clientCommandHandler)) { 3107 clientWriteHandler = (ClientWriteHandler) clientCommandHandler; 3108 } else if(clientWriteHandlerString.equals(clientEventHandlerString) && 3109 ClientWriteHandler.class.isInstance(clientEventHandler)) { 3110 clientWriteHandler = (ClientWriteHandler) clientEventHandler; 3111 } else if(clientWriteHandlerString.equals(clientExtendedEventHandlerString) && 3112 ClientWriteHandler.class.isInstance(clientExtendedEventHandler)) { 3113 clientWriteHandler = (ClientWriteHandler) clientExtendedEventHandler; 3114 } else if(clientWriteHandlerString.equals(clientObjectHandlerString) && 3115 ClientWriteHandler.class.isInstance(clientObjectHandler)) { 3116 clientWriteHandler = (ClientWriteHandler) clientObjectHandler; 3117 } else if(clientWriteHandlerString.equals(clientBinaryHandlerString) && 3118 ClientWriteHandler.class.isInstance(clientBinaryHandler)) { 3119 clientWriteHandler = (ClientWriteHandler) clientBinaryHandler; 3120 } else { 3121 clientWriteHandler = (ClientWriteHandler) 3122 getClass(clientWriteHandlerString, true).newInstance(); 3123 } 3124 } 3126 Class authenticatorClass = null; 3127 if(clientAuthenticationHandlerString != null) { 3128 logger.finest("Loading ClientAuthenticationHandler class.."); 3129 authenticatorClass = getClass(clientAuthenticationHandlerString, true); 3130 } 3131 3132 if(authenticatorClass!=null) { 3133 Object obj = authenticatorClass.newInstance(); 3134 3135 if(ClientAuthenticationHandler.class.isInstance(obj)) 3136 clientAuthenticationHandler = (ClientAuthenticationHandler) obj; 3137 else 3138 authenticator = (Authenticator) obj; 3139 } 3140 3141 clientDataClass = null; 3142 if(clientDataString != null) { 3143 logger.finest("Loading ClientData class.."); 3144 clientDataClass = getClass(clientDataString, true); 3145 } 3146 3147 Assertion.affirm(clientEventHandler!=null, "ClientEventHandler was not loaded!"); 3148 } 3149 3150 3158 public void setClientEventHandler(String handler) { 3159 clientEventHandlerString = handler; 3160 logger.finest("Set to "+handler); 3161 } 3162 3168 public String getClientEventHandler() { 3169 return clientEventHandlerString; 3170 } 3171 3172 3176 public void setDefaultDataMode(DataMode dataMode, DataType dataType) 3177 throws IOException { 3178 if(dataType==DataType.IN) 3179 this.defaultDataModeIN = dataMode; 3180 if(dataType==DataType.OUT) 3181 this.defaultDataModeOUT = dataMode; 3182 } 3183 3187 public void setDefaultDataMode(DefaultDataMode defaultDataMode) 3188 throws IOException { 3189 defaultDataModeIN = defaultDataMode.getDataMode(DataType.IN); 3190 defaultDataModeOUT = defaultDataMode.getDataMode(DataType.OUT);; 3191 } 3192 3196 public DataMode getDefaultDataMode(DataType dataType) { 3197 if(dataType==DataType.IN) 3198 return defaultDataModeIN; 3199 if(dataType==DataType.OUT) 3200 return defaultDataModeOUT; 3201 else 3202 throw new IllegalArgumentException ("Unknown DataType: "+dataType); 3203 } 3204 3205 3213 public void setClientExtendedEventHandler(String handler) { 3214 clientExtendedEventHandlerString = handler; 3215 logger.finest("Set to "+handler); 3216 } 3217 3223 public String getClientExtendedEventHandler() { 3224 return clientExtendedEventHandlerString; 3225 } 3226 3227 3231 private void loadApplicationClasses() throws Exception { 3232 if(getApplicationJarPath()!=null && getClassLoader()==null) { 3233 setClassLoader( 3234 ClassUtil.getClassLoader(getApplicationJarPath())); 3235 if(adminServer!=null) { 3237 adminServer.getServer().setClassLoader(getClassLoader()); 3238 } 3239 } 3240 } 3241} 3242 | Popular Tags |