1 45 package org.exolab.jms.net.connector; 46 47 import java.util.ArrayList ; 48 import java.util.List ; 49 50 import org.apache.commons.logging.Log; 51 import org.apache.commons.logging.LogFactory; 52 53 import org.exolab.jms.net.uri.URI; 54 import org.exolab.jms.net.uri.URIHelper; 55 56 57 66 public final class ConnectionContext { 67 68 71 private static ThreadLocal _contexts = new ThreadLocal (); 72 73 76 private static final Log _log = LogFactory.getLog(ConnectionContext.class); 77 78 79 82 private ConnectionContext() { 83 } 84 85 91 public static void push(ConnectionFactory factory, Connection connection) { 92 List stack = (List ) _contexts.get(); 93 if (stack == null) { 94 stack = new ArrayList (2); 95 _contexts.set(stack); 96 } 97 stack.add(new Context(factory, connection)); 98 } 99 100 103 public static void pop() { 104 List stack = (List ) _contexts.get(); 105 stack.remove(stack.size() - 1); 106 } 107 108 116 public static Connection getConnection(URI uri) { 117 Connection result = null; 118 Context context = top(); 119 if (context != null) { 120 Connection connection = context.getConnection(); 121 if (connection != null) { 122 try { 123 URI remoteURI = connection.getRemoteURI(); 124 if (remoteURI.equals(uri)) { 125 result = connection; 126 } else { 127 URI normalised = URIHelper.convertHostToAddress(uri); 128 if (normalised.equals(remoteURI)) { 129 result = connection; 130 } 131 } 132 } catch (ResourceException exception) { 133 _log.debug(exception, exception); 134 } 135 } 136 } 137 return result; 138 } 139 140 146 public static ConnectionFactory getConnectionFactory() { 147 ConnectionFactory result = null; 148 Context context = top(); 149 if (context != null) { 150 result = context.getConnectionFactory(); 151 } 152 return result; 153 } 154 155 161 private static Context top() { 162 Context context = null; 163 List stack = (List ) _contexts.get(); 164 if (stack != null && !stack.isEmpty()) { 165 context = (Context) stack.get(stack.size() - 1); 166 } 167 return context; 168 } 169 170 171 private static class Context { 172 173 176 private final ConnectionFactory _factory; 177 178 181 private final Connection _connection; 182 183 184 190 public Context(ConnectionFactory factory, Connection connection) { 191 _factory = factory; 192 _connection = connection; 193 } 194 195 200 public ConnectionFactory getConnectionFactory() { 201 return _factory; 202 } 203 204 209 public Connection getConnection() { 210 return _connection; 211 } 212 213 } 214 } 215 | Popular Tags |