1 21 22 package com.rift.coad.util.connection; 24 25 import java.lang.reflect.Proxy ; 27 import java.util.Map ; 28 import java.util.concurrent.ConcurrentHashMap ; 29 import javax.naming.Context ; 30 import javax.rmi.PortableRemoteObject ; 31 32 import org.apache.log4j.Logger; 34 35 40 public class RMIConnection implements Connection { 41 42 protected static Logger log = 44 Logger.getLogger(RMIConnection.class.getName()); 45 46 private Context context = null; 48 private String jndiURL = null; 49 private Object ref = null; 50 private Map connectionMap = new ConcurrentHashMap (); 51 52 53 59 public RMIConnection(Context context, String jndiURL) { 60 this.context = context; 61 this.jndiURL = jndiURL; 62 } 63 64 65 72 public Object getConnection(Class type) throws ConnectionException, 73 java.lang.ClassCastException { 74 try { 75 synchronized (type) { 76 Object proxy = connectionMap.get(type); 77 if (proxy != null) { 78 return proxy; 79 } 80 81 Object ref = null; 83 synchronized (this) { 84 if (this.ref == null) { 85 this.ref = context.lookup(jndiURL); 86 } 87 ref = this.ref; 88 } 89 Object reference = PortableRemoteObject.narrow(ref,type); 90 proxy = createProxy(type, reference); 91 connectionMap.put(type,proxy); 92 return proxy; 93 } 94 } catch (javax.naming.NameNotFoundException ex) { 95 log.error("The name [" + jndiURL + "] is not found : " + 96 ex.getMessage(),ex); 97 throw new com.rift.coad.util.connection.NameNotFound("The name [" + 98 jndiURL + "] is not found : " + ex.getMessage(),ex); 99 } catch (java.lang.ClassCastException ex) { 100 log.error("Failed to cast object refered to by [" + jndiURL 101 + "] to a [" + type.getName() + "] because : " + 102 ex.getMessage(),ex); 103 throw ex; 104 } catch (Exception ex) { 105 log.error("Failed to make the connection : " + 106 ex.getMessage(),ex); 107 throw new ConnectionException("Failed to make the connection : " + 108 ex.getMessage(),ex); 109 } 110 } 111 112 113 120 public static boolean isRMIConnection(String jndiURL) { 121 if (jndiURL.trim().indexOf("java:comp") == -1) { 122 return true; 123 } 124 return false; 125 } 126 127 128 131 public synchronized void invalidateConnection() { 132 log.debug("Calling clear"); 133 ref = null; 134 connectionMap.clear(); 135 } 136 137 138 145 private Object createProxy(Class type, Object rmiRef) { 146 ConnectionHandler handler = new ConnectionHandler(this,rmiRef); 147 return (Object )Proxy.newProxyInstance( 148 type.getClassLoader(), 149 new Class [] {type},handler); 150 } 151 } 152 | Popular Tags |