1 16 package org.jmanage.core.services; 17 18 import org.jmanage.core.remote.client.HttpServiceProxy; 19 20 import java.util.Map ; 21 import java.util.Hashtable ; 22 import java.lang.reflect.Proxy ; 23 24 40 public class ServiceFactory { 41 42 private static Map serviceClassToObjectMap = new Hashtable (); 43 44 public static final Integer MODE_LOCAL = new Integer (0); 45 public static final Integer MODE_REMOTE = new Integer (1); 46 47 private static Integer mode; 48 49 57 public static void init(Integer mode){ 58 assert ServiceFactory.mode == null : 59 "ServiceFactory already initialized"; 60 assert mode.equals(MODE_LOCAL) || mode.equals(MODE_REMOTE) : 61 "Invalid mode:" + mode; 62 ServiceFactory.mode = mode; 63 } 64 65 71 public static Object getService(Class serviceInterface){ 72 Object service = serviceClassToObjectMap.get(serviceInterface); 73 if(service == null){ 74 if(mode.equals(MODE_LOCAL)){ 75 service = createService(serviceInterface); 76 }else{ 77 service = createServiceProxy(serviceInterface); 78 } 79 serviceClassToObjectMap.put(serviceInterface, service); 80 } 81 return service; 82 } 83 84 public static ConfigurationService getConfigurationService() { 85 return (ConfigurationService)getService(ConfigurationService.class); 86 } 87 88 public static AuthService getAuthService() { 89 return (AuthService)getService(AuthService.class); 90 } 91 92 public static MBeanService getMBeanService() { 93 return (MBeanService)getService(MBeanService.class); 94 } 95 96 public static AlertService getAlertService() { 97 return (AlertService)getService(AlertService.class); 98 } 99 100 private static Object createService(Class serviceClass){ 101 final String implClassName = serviceClass.getName() + "Impl"; 102 try { 103 Class clazz = Class.forName(implClassName); 104 return clazz.newInstance(); 105 } catch (ClassNotFoundException e) { 106 throw new RuntimeException ("Service impl. not found:" + 107 implClassName, e); 108 } catch (InstantiationException e) { 109 throw new RuntimeException ("Service impl.:" + 110 implClassName, e); 111 } catch (IllegalAccessException e) { 112 throw new RuntimeException ("Service impl.:" + 113 implClassName, e); 114 } 115 } 116 117 private static Object createServiceProxy(Class serviceClass){ 118 return Proxy.newProxyInstance 119 (serviceClass.getClassLoader(), 120 new Class []{serviceClass}, 121 new HttpServiceProxy()); 122 } 123 } 124 | Popular Tags |