Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * IronJacamar, a Java EE Connector Architecture implementation
   * Copyright 2008-2009, 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;
 
 
 import java.util.Map;
 import java.util.Set;
 
 
 
AbstractConnectionManager.

Author(s):
Gurkan Erdogdu
Jesper Pedersen
 
 public abstract class AbstractConnectionManager implements ConnectionManager
 {
   
Log instance
 
    private final CoreLogger log;

   
Log trace
 
    protected boolean trace;
   
   
The bundle
 
    private static CoreBundle bundle = Messages.getBundle(CoreBundle.class);
   
   
The pool
 
    private Pool pool;

   
Security domain
 
    private String securityDomain;

   
SubjectFactory
 
    private SubjectFactory subjectFactory;

   
The flush strategy
 
    private FlushStrategy flushStrategy;

   
Number of retry to allocate connection
 
    private int allocationRetry;

   
Interval between retries
 
    private long allocationRetryWaitMillis;

   
Startup/ShutDown flag
 
    private final AtomicBoolean shutdown = new AtomicBoolean(false);

   
Cached connection manager
 
Jndi name
 
    private String jndiName;

   
Sharable
 
   private boolean sharable;

   
Enlistment
   protected Boolean enlistment;

   
Creates a new instance of connection manager.
   protected AbstractConnectionManager()
   {
      this. = getLogger();
      this. = .isTraceEnabled();
   }

   
Get the logger.

Returns:
The value
   protected abstract CoreLogger getLogger();

   
Set the pool.

Parameters:
pool the pool
   public void setPool(Pool pool)
   {
      this. = pool;
   }

   
Get the pool.

Returns:
the pool
   public Pool getPool()
   {
      return ;
   }

   
Sets cached connection manager.

Parameters:
cachedConnectionManager cached connection manager
   public void setCachedConnectionManager(CachedConnectionManager cachedConnectionManager)
   {
      this. = cachedConnectionManager;
   }

   
Gets cached connection manager.

Returns:
cached connection manager
   {
      return ;
   }

   
Shutdown
   public void shutdown()
   {
      getLogger().debug( + ": shutdown");
      .set(true);
      if ( != null)
         .shutdown();
   }

   
Gets jndi name.

Returns:
jndi name
   public String getJndiName()
   {
      return ;
   }

   
Sets jndi name.

Parameters:
jndiName jndi name
   public void setJndiName(String jndiName)
   {
      this. = jndiName;
   }

   
Is sharable

Returns:
The value
   public boolean isSharable()
   {
      return ;
   }

   
Set the sharable flag

Parameters:
v The value
   public void setSharable(boolean v)
   {
      this. = v;
      if ()
         .tracef("sharable=%s");
   }

   
Is enlistment

Returns:
The value
   public boolean isEnlistment()
   {
      return  != null ? .booleanValue() : true;
   }

   
Set the enlistment flag

Parameters:
v The value
   public void setEnlistment(boolean v)
   {
      if ( == null)
         this. = Boolean.valueOf(v);
      if ()
         .tracef("enlistment=%s");
   }

   
   public String getSecurityDomain()
   {
      return ;
   }

   
Sets security domain

Parameters:
securityDomain security domain
   public void setSecurityDomain(String securityDomain)
   {
      this. = securityDomain;
   }

   
   {
      return ;
   }

   
Sets subject factory.

Parameters:
subjectFactory subject factory
   public void setSubjectFactory(SubjectFactory subjectFactory)
   {
      this. = subjectFactory;
   }

   
Get the flush strategy

Returns:
The value
   {
      return ;
   }

   
Set the flush strategy

Parameters:
v The value
   public void setFlushStrategy(FlushStrategy v)
   {
      this. = v;
   }

   
Gets managed connection factory.

Returns:
managed connection factory
   {
      if ( == null)
      {
         if ()
         {
            .trace("No pooling strategy found! for connection manager : " + this);
            return null;
         }
      }
      else
      {
         return .getManagedConnectionFactory();
      }
      return null;
   }

   
Set the number of allocation retries

Parameters:
number retry number
   public void setAllocationRetry(int number)
   {
      if (number >= 0)
          = number;
   }

   
Get the number of allocation retries

Returns:
The number of retries
   public int getAllocationRetry()
   {
      return ;
   }

   
Set the wait time between each allocation retry

Parameters:
millis wait in ms
   public void setAllocationRetryWaitMillis(long millis)
   {
      if (millis > 0)
          = millis;
   }

   
Get the wait time between each allocation retry

Returns:
The millis
   public long getAllocationRetryWaitMillis()
   {
      return ;
   }

   
Public for use in testing pooling functionality by itself. called by both allocateConnection and reconnect.

Parameters:
subject a Subject value
cri a ConnectionRequestInfo value
Returns:
a ManagedConnection value
Throws:
javax.resource.ResourceException if an error occurs
   {
      return getManagedConnection(nullsubjectcri);
   }

   
Get the managed connection from the pool.

Parameters:
transaction the transaction for track by transaction
subject the subject
cri the ConnectionRequestInfo
Returns:
a managed connection
Throws:
javax.resource.ResourceException if an error occurs
   protected ConnectionListener getManagedConnection(Transaction transactionSubject subject,
         ConnectionRequestInfo crithrows ResourceException
   {
      Exception failure = null;
      if (.get())
      {
      }
      // First attempt
      boolean isInterrupted = Thread.interrupted();
      boolean innerIsInterrupted = false;
      try
      {
         return .getConnection(transactionsubjectcri);
      }
      catch (ResourceException e)
      {
         failure = e;
         // Retry?
         if ( != 0)
         {
            for (int i = 0; i < i++)
            {
               if (.get())
               {
                  throw new ResourceException(.connectionManagerIsShutdown());
               }
               if ()
               {
                  .trace("Attempting allocation retry for cri=" + cri);
               }
               if (Thread.currentThread().isInterrupted())
               {
                  Thread.interrupted();
                  innerIsInterrupted = true;
               }
               try
               {
                  if ( != 0)
                  {
                     Thread.sleep();
                  }
                  return .getConnection(transactionsubjectcri);
               }
               catch (ResourceException re)
               {
                  failure = re;
               }
               catch (InterruptedException ie)
               {
                  failure = ie;
                  innerIsInterrupted = true;
               }
            }
         }
      }
      finally
      {
         if (isInterrupted || innerIsInterrupted)
         {
            Thread.currentThread().interrupt();
      
            if (innerIsInterrupted)
               throw new ResourceException(.getManagedConnectionRetryWaitInterrupted(), failure);
         }
      }
      // If we get here all retries failed, throw the lastest failure
      throw new ResourceException(.unableGetManagedConnection(), failure);
   }

   
Kill given connection listener wrapped connection instance.

Parameters:
bcl connection listener that wraps connection
kill kill connection or not
                                       boolean kill)
   {
      // Hack - We know that we can type cast it
      ConnectionListener cl = (ConnectionListener)bcl;
      Pool localStrategy = cl.getPool();
      if (localStrategy != )
      {
         kill = true;
      }
      try
      {
         if (!kill && cl.getState().equals(.))
         {
            cl.tidyup();
         }
      }
      catch (Throwable t)
      {
         .errorDuringTidyUpConnection(clt);
         kill = true;
      }
      try
      {
         localStrategy.returnConnection(clkill);
      }
      catch (ResourceException re)
      {
         // We can receive notification of an error on the connection
         // before it has been assigned to the pool. Reduce the noise for
         // these errors
         if (kill)
         {
            .debug("resourceException killing connection (error retrieving from pool?)"re);
         }
         else
         {
         }
      }
   }

   
   {
      //Check for pooling!
      if ( == null)
      {
      }
      //it is an explicit spec requirement that equals be used for matching rather than ==.
      if (!.getManagedConnectionFactory().equals(mcf))
      {
         throw new ResourceException(
      }
      // Pick a managed connection from the pool
      Subject subject = getSubject();
      ConnectionListener cl = getManagedConnection(subjectcri);
      // Tell each connection manager the managed connection is active
      // Ask the managed connection for a connection
      Object connection = null;
      try
      {
         connection = cl.getManagedConnection().getConnection(subjectcri);
      }
      catch (Throwable t)
      {
         try
         {
            managedConnectionDisconnected(cl);
         }
         catch (ResourceException re)
         {
            if ()
               .trace("Get exception from managedConnectionDisconnected, maybe delist() have problem" + re);
            returnManagedConnection(cltrue);
         }
      }
      // Associate managed connection with the connection
      registerAssociation(clconnection);
      if ( != null)
      {
         .registerConnection(thisclconnectioncri);
      }
      return connection;
   }

   
   public void associateConnection(Object connectionManagedConnectionFactory mcfConnectionRequestInfo cri)
      throws ResourceException
   {
      associateManagedConnection(connectionmcfcri);
   }

   
                                                       ConnectionRequestInfo cri)
      throws ResourceException
   {
      // Check for pooling!
      if ( == null)
      {
      }
      // It is an explicit spec requirement that equals be used for matching rather than ==.
      if (!.getManagedConnectionFactory().equals(mcf))
      {
         throw new ResourceException(
      }
      if (connection == null)
         throw new ResourceException(.connectionIsNull());
      // Pick a managed connection from the pool
      Subject subject = getSubject();
      ConnectionListener cl = getManagedConnection(subjectcri);
      // Tell each connection manager the managed connection is active
      // Associate managed connection with the connection
      cl.getManagedConnection().associateConnection(connection);
      registerAssociation(clconnection);
      if ( != null)
      {
         .registerConnection(thisclconnectioncri);
      }
      return cl.getManagedConnection();
   }
 
   
   public boolean dissociateManagedConnection(Object connectionManagedConnection mcManagedConnectionFactory mcf)
      throws ResourceException
   {
      if (connection == null || mc == null || mcf == null)
      ConnectionListener cl = getPool().findConnectionListener(mcconnection);
      if (cl != null)
      {
         if ()
            .tracef("DissociateManagedConnection: cl=%s, connection=%s"clconnection);
         if (getCachedConnectionManager() != null)
         {
            try
            {
               getCachedConnectionManager().unregisterConnection(thisconnection);
            }
            catch (Throwable t)
            {
               .debug("Throwable from unregisterConnection"t);
            }
         }
         unregisterAssociation(clconnection);
         if (cl.getNumberOfConnections() == 0)
         {
            if ()
               .tracef("DissociateManagedConnection: Returning cl=%s"cl);
            cl.dissociate();
            if ()
               .tracef("DissociateManagedConnection: isManagedConnectionFree=%s"cl.isManagedConnectionFree());
            returnManagedConnection(clfalse);
            return true;
         }
      }
      else
      {
      }
      return false;
   }

   
   public void inactiveConnectionClosed(Object connectionManagedConnectionFactory mcf)
   {
      // We don't track inactive connections
   }

   
   public void disconnect(Collection<ConnectionRecordconRecordsSet<StringunsharableResources)
      throws ResourceException
   {
      // if we have an unshareable connection do not remove the association
      // nothing to do
      if (unsharableResources.contains())
      {
         if ()
            .trace("disconnect for unshareable connection: nothing to do");
         return;
      }
      Set<ConnectionListenercls = new HashSet<ConnectionListener>(conRecords.size());
      for (Iterator<ConnectionRecordi = conRecords.iterator(); i.hasNext();)
      {
         ConnectionRecord cr = i.next();
         ConnectionListener cl = cr.getConnectionListener();
         cr.setConnectionListener(null);
         unregisterAssociation(clcr.getConnection());
         if (!cls.contains(cl))
         {
            cls.add(cl);
         }
      }
      for (Iterator<ConnectionListeneri = cls.iterator(); i.hasNext();)
      {
         disconnectManagedConnection(i.next());
      }
   }

   
   public void reconnect(Collection<ConnectionRecordconnsSet<StringunsharableResourcesthrows ResourceException
   {
      // if we have an unshareable connection the association was not removed
      // nothing to do
      if (unsharableResources.contains())
      {
         if ()
            .trace("reconnect for unshareable connection: nothing to do");
         return;
      }
      Map<ConnectionRequestInfoConnectionListenercriToCLMap =
         new HashMap<ConnectionRequestInfoConnectionListener>(conns.size());
      for (Iterator<ConnectionRecordi = conns.iterator(); i.hasNext();)
      {
         ConnectionRecord cr = i.next();
         if (cr.getConnectionListener() != null)
         {
            //This might well be an error.
               cr.getConnectionListener().getManagedConnection(),
               cr.getConnection());
         }
         ConnectionListener cl = criToCLMap.get(cr.getCri());
         if (cl == null)
         {
            cl = getManagedConnection(getSubject(), cr.getCri());
            criToCLMap.put(cr.getCri(), cl);
            //only call once per managed connection, when we get it.
            reconnectManagedConnection(cl);
         }
         registerAssociation(clcr.getConnection());
         cr.setConnectionListener(cl);
      }
   }

   
Unregister association.

Parameters:
cl connection listener
c connection
   //does NOT put the mc back in the pool if no more handles. Doing so would introduce a race condition
   //whereby the mc got back in the pool while still enlisted in the tx.
   //The mc could be checked out again and used before the delist occured.
   public void unregisterAssociation(ConnectionListener clObject c)
   {
      cl.unregisterConnection(c);
   }

   
   public void lazyEnlist(ManagedConnection mcthrows ResourceException
   {
      // Nothing by default
   }

   
Invoked to reassociate a managed connection.

Parameters:
cl the managed connection
Throws:
javax.resource.ResourceException for exception
   {
      try
      {
         managedConnectionReconnected(cl);
      }
      catch (Throwable t)
      {
         disconnectManagedConnection(cl);
      }
   }

   
Invoked when a managed connection is no longer associated

Parameters:
cl the managed connection
   {
      try
      {
         managedConnectionDisconnected(cl);
      }
      catch (Throwable t)
      {
      }
   }

   
For polymorphism.

Do not invoke directly, use reconnectManagedConnection which does the relevent exception handling

Parameters:
cl connection listener
Throws:
javax.resource.ResourceException for exception
   {
      //Nothing as default
   }

   
For polymorphism.

Do not invoke directly, use disconnectManagedConnection which does the relevent exception handling

Parameters:
cl connection listener
Throws:
javax.resource.ResourceException for exception
   {
      //Nothing as default
   }

   
Register connection with connection listener.

Parameters:
cl connection listener
c connection
Throws:
javax.resource.ResourceException exception
   private void registerAssociation(ConnectionListener clObject cthrows ResourceException
   {
      cl.registerConnection(c);
   }

   
   public abstract void transactionStarted(Collection<ConnectionRecordconnsthrows SystemException;

   
   public abstract boolean isTransactional();

   
   public abstract TransactionIntegration getTransactionIntegration();

   
Gets subject.

Returns:
subject
   private Subject getSubject()
   {
      Subject subject = null;
      if ( != null &&  != null)
      {
         subject = .createSubject();
         Set<PasswordCredentialcredentials = subject.getPrivateCredentials(PasswordCredential.class);
         if (credentials.size() > 0)
         {
            ManagedConnectionFactory pcMcf = getManagedConnectionFactory();
            for (PasswordCredential pc : credentials)
            {
               pc.setManagedConnectionFactory(pcMcf);
            }
         }
      }
      if ()
         .tracef("Subject: %s"subject);
      return subject;
   }
New to GrepCode? Check out our FAQ X