1 16 package org.jmanage.core.management; 17 18 import org.jmanage.core.config.*; 19 import org.jmanage.core.util.Loggers; 20 21 import java.lang.reflect.Proxy ; 22 import java.util.logging.Logger ; 23 import java.util.Map ; 24 import java.util.HashMap ; 25 import java.util.Collections ; 26 27 32 public class ServerConnector { 33 34 private static final Logger logger = 35 Loggers.getLogger(ServerConnector.class); 36 37 44 public static ServerConnection 45 getServerConnection(ApplicationConfig appConfig) 46 throws ConnectionFailedException{ 47 48 ApplicationType appType = 49 ApplicationTypes.getApplicationType(appConfig.getType()); 50 assert appType != null: "Invalid type=" + appConfig.getType(); 51 ModuleConfig moduleConfig = appType.getModule(); 52 final ClassLoader classLoader = appType.getClassLoader(); 53 assert classLoader != null; 54 55 final ClassLoader contextClassLoader = 56 Thread.currentThread().getContextClassLoader(); 57 58 Thread.currentThread().setContextClassLoader(classLoader); 59 60 try { 61 logger.fine("Connecting to " + appConfig.getURL()); 62 final ServerConnectionFactory factory = 63 getServerConnectionFactory(moduleConfig, classLoader); 64 ServerConnection connection = 65 factory.getServerConnection(appConfig); 66 logger.fine("Connected to " + appConfig.getURL()); 67 ServerConnectionProxy proxy = new ServerConnectionProxy(connection, 68 classLoader); 69 return (ServerConnection)Proxy.newProxyInstance( 70 ServerConnector.class.getClassLoader(), 71 new Class []{ServerConnection.class}, 72 proxy); 73 } catch(ConnectionFailedException e){ 74 logger.info("Failed to connect. error=" + e.getMessage()); 75 throw e; 76 } finally { 77 79 Thread.currentThread().setContextClassLoader(contextClassLoader); 80 } 81 } 82 83 private static ServerConnectionFactory 84 getServerConnectionFactory(ModuleConfig moduleConfig, 85 ClassLoader classLoader) { 86 87 assert classLoader != null; 88 ServerConnectionFactory factory = (ServerConnectionFactory) 89 factories.get(moduleConfig.getConnectionFactory()); 90 if(factory == null){ 91 try { 92 final Class factoryClass = 93 Class.forName(moduleConfig.getConnectionFactory(), 94 true, classLoader); 95 factory = (ServerConnectionFactory)factoryClass.newInstance(); 96 factories.put(moduleConfig.getConnectionFactory(), factory); 97 } catch (Exception e) { 98 throw new RuntimeException (e); 99 } 100 } 101 return factory; 102 } 103 104 105 private static final Map factories = 106 Collections.synchronizedMap(new HashMap ()); 107 } 108 | Popular Tags |