Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * IronJacamar, a Java EE Connector Architecture implementation
   * Copyright 2013, Red Hat Inc, and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 package org.jboss.jca.core.connectionmanager.ccm;
 
 
 import java.util.Map;
 import java.util.Set;
 
 
CacheConnectionManager.

Author(s):
Jesper Pedersen
 
 {
   
Log instance
 
    private static CoreLogger log = Logger.getMessageLogger(CoreLogger.class
                                                            CachedConnectionManager.class.getName());
   
Trace
 
    private static boolean trace = .isTraceEnabled();

   
The bundle
 
    private static CoreBundle bundle = Messages.getBundle(CoreBundle.class);
   
   
Debugging flag
 
    private boolean debug = false;

   
Enabled error handling for debugging
 
    private boolean error = false;

   
Ignore unknown connections
 
    private boolean ignoreConnections = false;

   
Transaction Manager instance
 
 
User transaction registry
 
ThreadLocal that holds current calling meta-programming aware object, used in case someone is idiotic enough to cache a connection between invocations.and want the spec required behavior of it getting hooked up to an appropriate ManagedConnection on each method invocation.
   private final ThreadLocal<LinkedList<Object>> currentObjects = new ThreadLocal<LinkedList<Object>>();

   
The variable objectToConnectionManagerMap holds the map of meta-aware object to set of connections it holds, used by the idiot spec compliant behavior.
Connection stacktraces
   private final Map<ObjectThrowableconnectionStackTraces = new WeakHashMap<ObjectThrowable>();

   
Creates a new instance.

Parameters:
transactionManager The transaction manager
transactionSynchronizationRegistry the transaction synchronization registry
userTransactionRegistry The user transaction registry
   public CachedConnectionManagerImpl(TransactionManager transactionManager,
                                      TransactionSynchronizationRegistry transactionSynchronizationRegistry,
                                      UserTransactionRegistry userTransactionRegistry)
   {
      this. = transactionManager;
      this. = transactionSynchronizationRegistry;
      this. = userTransactionRegistry;
   }

   
Gets transaction manager.

Returns:
transaction manager
   {
      return ;
   }

   
Gets transaction synchronization registry

Returns:
TransactionSynchronizationRegistry
   {
   }

   
   public boolean isDebug()
   {
      return ;
   }

   
   public void setDebug(boolean v)
   {
       = v;
   }

   
   public boolean isError()
   {
      return ;
   }

   
   public void setError(boolean v)
   {
       = v;
   }

   
   public boolean isIgnoreUnknownConnections()
   {
      return ;
   }

   
   public void setIgnoreUnknownConnections(boolean v)
   {
       = v;
   }

   
   public void start()
   {
      if ( != null)
         .addListener(this);
      .debugf("start: %s"this.toString());
   }

   
   public void stop()
   {
      .debugf("stop: %s"this.toString());
      if ( != null)
   }

   
   public void userTransactionStarted() throws SystemException
   {
      if ()
         .tracef("user tx started, key: %s"key);
      if (key != null)
      {
            key.getCMToConnectionsMap();
         Iterator<Entry<ConnectionCacheListenerCopyOnWriteArrayList<ConnectionRecord>>> cmToConnectionsMapIterator =
            cmToConnectionsMap.entrySet().iterator();
         while (cmToConnectionsMapIterator.hasNext())
         {
               cmToConnectionsMapIterator.next();
            ConnectionCacheListener cm = entry.getKey();
            CopyOnWriteArrayList<ConnectionRecordconns = entry.getValue();
            cm.transactionStarted(conns);
         }
      }
   }

   

Returns:
stack last meta-aware object
   {
      LinkedList<Objectstack = .get();
      if (stack != null && !stack.isEmpty())
      {
         return (KeyConnectionAssociation)stack.getLast();
      }
      return null;
   }


   
   @SuppressWarnings("unchecked")
   public void popMetaAwareObject(Set unsharableResourcesthrows ResourceException
   {
      LinkedList<Objectstack = .get();
      if ()
         .tracef("popped object: %s"oldKey);
      if ()
      {
         if (closeAll(oldKey.getCMToConnectionsMap()) && )
         {
            throw new ResourceException(.someConnectionsWereNotClosed());
         }
      }
   }

   
Register connection.

Parameters:
cm connection manager
cl connection listener
connection connection handle
cri connection request info.
                                  org.jboss.jca.core.api.connectionmanager.listener.ConnectionListener cl,
                                  Object connectionConnectionRequestInfo cri)
   {
      if ()
      {
         synchronized ()
         {
            .put(connectionnew Throwable("STACKTRACE"));
         }
      }
      if ()
         .tracef("registering connection from connection manager: %s, connection : %s, key: %s",
                    cmconnectionkey);
      if (key != null)
      {
         ConnectionRecord cr = new ConnectionRecord(clconnectioncri);
            key.getCMToConnectionsMap();
         CopyOnWriteArrayList<ConnectionRecordconns = cmToConnectionsMap.get(cm);
         if (conns == null)
         {
            conns = new CopyOnWriteArrayList<ConnectionRecord>();
            cmToConnectionsMap.put((ConnectionCacheListener)cmconns);
         }
         conns.add(cr);
      }
   }

   
Unregister connection.

Parameters:
cm connection manager
connection connection handle
                                    Object connection)
   {
      if ()
      {
         if (cas != null)
         {
            cas.remove(connection);
         }
         synchronized ()
         {
            .remove(connection);
         }
      }
      if ()
         .tracef("unregistering connection from connection manager: %s, connection: %s, key: %s",
                    cmconnectionkey);
      if (key == null)
         return;
         key.getCMToConnectionsMap();
      CopyOnWriteArrayList<ConnectionRecordconns = cmToConnectionsMap.get(cm);
      // Can happen if connections are "passed" between contexts
      if (conns == null)
         return
      // Note iterator of CopyOnWriteArrayList does not support remove method
      // We use here remove on CopyOnWriteArrayList directly
      for (ConnectionRecord connectionRecord : conns)
      {
         if (connectionRecord.getConnection() == connection)
         {
            conns.remove(connectionRecord);
            return;
         }
      }
      if (!)
         throw new IllegalStateException(.tryingToReturnUnknownConnection(connection.toString()));
   }

   
   @SuppressWarnings("unchecked")
   public void pushMetaAwareObject(final Object rawKeySet unsharableResourcesthrows ResourceException
   {
      LinkedList<Objectstack = .get();
      if (stack == null)
      {
         if ()
            .tracef("new stack for key: %s"rawKey);
         stack = new LinkedList<Object>();
         .set(stack);
      }
      else
      {
         if ()
            .tracef("old stack for key: %s"rawKey);
      }
      KeyConnectionAssociation key = new KeyConnectionAssociation(rawKey);
      stack.addLast(key);
   }

   
Describe unregisterConnectionCacheListener method here. This is a shutdown method called by a connection manager. It will remove all reference to that connection manager from the cache, so cached connections from that manager will never be recoverable. Possibly this method should not exist.

Parameters:
cm a ConnectionCacheListener value
   {
      if ()
         .tracef("unregisterConnectionCacheListener: %s"cm);
      while (it.hasNext())
      {
         ConcurrentMap<ConnectionCacheListenerCopyOnWriteArrayList<ConnectionRecord>> cmToConnectionsMap = it.next();
         if (cmToConnectionsMap != null)
            cmToConnectionsMap.remove(cm);
      }
   }

   
   public int getNumberOfConnections()
   {
      if (!)
         return 0;
      synchronized ()
      {
         return .size();
      }
   }

   
   public Map<StringStringlistConnections()
   {
      if (!)
         return Collections.unmodifiableMap(.);
      synchronized ()
      {
         HashMap<StringStringresult = new HashMap<StringString>();
         for (Map.Entry<ObjectThrowableentry : .entrySet())
         {
            Object key = entry.getKey();
            Throwable stackTrace = entry.getValue();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baostrue);
            stackTrace.printStackTrace(ps);
            result.put(key.toString(), baos.toString());
         }
         return Collections.unmodifiableMap(result);
      }
   }

   
Close all connections.

Parameters:
cmToConnectionsMap connection manager to connections
Returns:
true if close
                            CopyOnWriteArrayList<ConnectionRecord>> cmToConnectionsMap)
   {
      boolean unclosed = false;
      Collection<CopyOnWriteArrayList<ConnectionRecord>> connections = cmToConnectionsMap.values();
      if (connections.size() != 0)
      {
         for (Iterator<CopyOnWriteArrayList<ConnectionRecord>> i = connections.iterator(); i.hasNext();)
         {
            CopyOnWriteArrayList<ConnectionRecordconns = i.next();
            for (Iterator<ConnectionRecordj = conns.iterator(); j.hasNext();)
            {
               Object c = (j.next()).getConnection();
               CloseConnectionSynchronization cas = getCloseConnectionSynchronization(true);
               if (cas == null)
               {
                  unclosed = true;
                  closeConnection(c);
               }
               else
               {
                  cas.add(c);
               }
            }
         }
      }
      return unclosed;
   }

   
Gets close sync. instance.

Parameters:
createIfNotFound create if not found
Returns:
sync. instance
   private CloseConnectionSynchronization getCloseConnectionSynchronization(boolean createIfNotFound)
   {
      try
      {
         Transaction tx = null;
         if ( != null)
         {
            tx = .getTransaction();
         }
         if (tx != null)
         {
            TransactionSynchronizer.lock(tx);
            try
            {
               CloseConnectionSynchronization cas = 
                  (CloseConnectionSynchronization)TransactionSynchronizer.getCCMSynchronization(tx);
               if (cas == null && createIfNotFound && TxUtils.isActive(tx))
               {
                  cas = new CloseConnectionSynchronization();
                  TransactionSynchronizer.registerCCMSynchronization(txcas);
               }
               return cas;
            }
            finally
            {
               TransactionSynchronizer.unlock(tx);
            }
         }
      }
      catch (Throwable t)
      {
         .debug("Unable to synchronize with transaction"t);
      }
      return null;
   }


   
Close connection handle.

Parameters:
connectionHandle connection handle
   private void closeConnection(Object connectionHandle)
   {
      try
      {
         Throwable exception;
         synchronized ()
         {
            exception = .remove(connectionHandle);
         }
         Method m = connectionHandle.getClass().getMethod("close"new Class[]{});
         try
         {
            if (exception != null)
            {
               .closingConnection(connectionHandleexception);
            }
            else
            {
               .closingConnection(connectionHandle);
            }
            m.invoke(connectionHandlenew Object[]{});
         }
         catch (Throwable t)
         {
            .closingConnectionThrowable(t);
         }
      }
      catch (NoSuchMethodException nsme)
      {
         .closingConnectionNoClose(connectionHandle.getClass().getName());
      }
   }


   
Close synch. class.
   private class CloseConnectionSynchronization implements Synchronization
   {
      
Connection handle
      CopyOnWriteArraySet<Objectconnections = new CopyOnWriteArraySet<Object>();

      
Closing fla
      AtomicBoolean closing = new AtomicBoolean(false);

      
Creates a new instance.
      public CloseConnectionSynchronization()
      {
      }

      
Add new connection handle.

Parameters:
c connection handle
      public  void add(Object c)
      {
         if (!.get())
            .add(c);
      }

      
Removes connection handle.

Parameters:
c connection handle
      public  void remove(Object c)
      {
         if (!.get())
            .remove(c);
      }

      
      public void beforeCompletion()
      {
         // No-action
      }

      
      public void afterCompletion(int status)
      {
         .set(true);
         for (Iterator<Objecti = .iterator(); i.hasNext();)
         {
            closeConnection(i.next());
         }
         .clear();
      }
   }

   
Get the currentObjects. This method is package protected beacause it is intended only for test case use. Please don't use it in your production code.

Returns:
the currentObjects.
   {
      return ;
   }

   
String representation

Returns:
The string
   public String toString()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("CachedConnectionManagerImpl@").append(Integer.toHexString(System.identityHashCode(this)));
      sb.append("[debug=").append();
      sb.append(" error=").append();
      sb.append(" ignoreConnections=").append();
      sb.append(" transactionManager=").append();
      sb.append(" transactionSynchronizationRegistry=").append();
      sb.append(" userTransactionRegistry=").append();
      sb.append(" currentObjects=").append(.get());
      sb.append(" objectToConnectionManagerMap=").append();
      sb.append(" connectionStackTraces=").append();
      sb.append("]");
      return sb.toString();
   }
New to GrepCode? Check out our FAQ X