Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * IronJacamar, a Java EE Connector Architecture implementation
   * Copyright 2010, 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.workmanager;
 
 
 import java.util.List;
 import java.util.Map;
 
 
 
Wraps the resource adapter's work.

Author(s):
Jesper Pedersen
Version:
$Revision: 71538 $
 
 public class WorkWrapper implements Runnable
 {
   
The log
 
    private static CoreLogger log = Logger.getMessageLogger(CoreLogger.class
       WorkWrapper.class.getName());

   
Whether we are tracing
 
    private static boolean trace = .isTraceEnabled();
   
   
The bundle
 
    private static CoreBundle bundle = Messages.getBundle(CoreBundle.class);
   
   
The work
 
    private Work work;

   
The execution context
 
    private ExecutionContext executionContext;
   
   
If work is an instance of WorkContextProvider, it may contain WorkContext instances
 
    private Map<Class<? extends WorkContext>, WorkContextworkContexts;

   
the work listener
 
    private WorkListener workListener;   

   
The work manager
 
    private WorkManagerImpl workManager;

   
The start time
 
    private long startTime;

   
Any exception
 
    private WorkException exception;

   
Started latch
 
   private CountDownLatch startedLatch;

   
Completed latch
   private CountDownLatch completedLatch;

   
Create a new WorkWrapper

Parameters:
workManager the work manager
work the work
executionContext the execution context
workListener the WorkListener
startedLatch The latch for when work has started
completedLatch The latch for when work has completed
startTime The start time
Throws:
java.lang.IllegalArgumentException for null work, execution context or a negative start timeout
   public WorkWrapper(WorkManagerImpl workManager
                      Work work
                      ExecutionContext executionContext
                      WorkListener workListener,
                      CountDownLatch startedLatch,
                      CountDownLatch completedLatch,
                      long startTime)
   {
      super();
      if (work == null)
         throw new IllegalArgumentException("Null work");
      if (executionContext == null)
         throw new IllegalArgumentException("Null execution context");
      this. = workManager;
      this. = work;
      this. = executionContext;
      this. = workListener;
      this. = startedLatch;
      this. = completedLatch;
      this. = startTime;
      this. = null;
   }
   
   
Get the work manager

Returns:
the work manager
   {
      return ;
   }

   
Retrieve the work

Returns:
the work
   public Work getWork()
   {
      return ;
   }

   
Retrieve the exection context

Returns:
the execution context
   {
      return ;
   }

   
Retrieve the work listener

Returns:
the WorkListener
   {
      return ;
   }
   
   
Get any exception

Returns:
the exception or null if there is none
   {
      return ;
   }

   
Set work exception

Parameters:
e The exception
   {
       = e;
   }

   
Run
   public void run()
   {
      ClassLoader oldCL = SecurityActions.getThreadContextClassLoader();
      org.jboss.security.SecurityContext oldSC = SecurityContextAssociation.getSecurityContext();
      try
      {
         start();
         .addWorkWrapper(this);
         if ( != null)
            .countDown();
         .run();
         end();
      }
      catch (Throwable t)
      {
          = new WorkCompletedException(t.getMessage(), t);
         cancel();
      } 
      finally
      {
         .removeWorkWrapper(this);
         .release();
         if ( != null)
         {
            WorkEvent event = new WorkEvent(.);
            .workCompleted(event);
         }
         SecurityContextAssociation.setSecurityContext(oldSC);
         SecurityActions.setThreadContextClassLoader(oldCL);
         if ( != null)
         {
            while (.getCount() != 0)
               .countDown();
         }
         if ( != null)
            .countDown();
         if ()
            .tracef("Executed work: %s"this);
      }
   }

   
Start

   protected void start() throws WorkException
   {
      if ()
         .tracef("Starting work: %s"this);  
      if ( != null)
      {
         long duration = System.currentTimeMillis() - ;
         if (duration < 0)
            duration = .....;
         WorkEvent event = new WorkEvent(.nullduration);
         .workStarted(event);
      }
      // Transaction setup
      if (ctx == null)
      {
         ctx = getExecutionContext();
      }
      
      if (ctx != null)
      {
         Xid xid = ctx.getXid();
         if (xid != null)
         {
            //JBAS-4002 base value is in seconds as per the API, here we convert to millis
            long timeout = (ctx.getTransactionTimeout() * 1000);
            .getXATerminator().registerWork(xidtimeout);
         }
      }
      // Fire complete for transaction context
      
      // Security setup
      javax.resource.spi.work.SecurityContext securityContext = 
      if (securityContext != null && .getCallbackSecurity() != null)
      {
         if ()
            .tracef("Setting security context: %s"securityContext);
         try
         {
            // Security context
            org.jboss.security.SecurityContext sc = null;
            // Setup callback handler
            CallbackHandler cbh = null;
            if (.getCallbackSecurity() != null && .getCallbackSecurity().isMappingRequired())
            {
               cbh = new CallbackHandlerImpl(.getCallbackSecurity());
            }
            if (cbh == null)
               cbh = new CallbackHandlerImpl();
            // Subjects for execution environment
            Subject executionSubject = null;
            Subject serviceSubject = null;
         
            if ()
               .tracef("Callback security: %s".getCallbackSecurity());
            if (SecurityContextAssociation.getSecurityContext() == null ||
                .getCallbackSecurity().getDomain() != null)
            {
               String scDomain = .getCallbackSecurity().getDomain();
               if ()
                  .tracef("Creating security context: %s"scDomain);
               if (scDomain == null || scDomain.trim().equals(""))
               {
                  fireWorkContextSetupFailed(securityContext);
               }
               sc = SecurityContextFactory.createSecurityContext(scDomain);
               SecurityContextAssociation.setSecurityContext(sc);
            }
            else
            {
               sc = SecurityContextAssociation.getSecurityContext();
               if ()
                  .tracef("Using security context: %s"sc);
            }
            executionSubject = sc.getSubjectInfo().getAuthenticatedSubject();
            if (executionSubject == null)
            {
               if ()
                  .tracef("Creating empty subject");
               executionSubject = new Subject();
            }
            // Resource adapter callback
            securityContext.setupSecurityContext(cbhexecutionSubjectserviceSubject);
            if (.getCallbackSecurity() != null)
            {
               List<Callbackcallbacks = new ArrayList<Callback>();
               if (.getCallbackSecurity().getDefaultPrincipal() != null)
               {
                  Principal defaultPrincipal = .getCallbackSecurity().getDefaultPrincipal();
                  if ()
                     .tracef("Adding default principal: %s"defaultPrincipal);
                  CallerPrincipalCallback cpc =
                     new CallerPrincipalCallback(executionSubjectdefaultPrincipal);
                  callbacks.add(cpc);
               }
               if (.getCallbackSecurity().getDefaultGroups() != null)
               {
                  String[] defaultGroups = .getCallbackSecurity().getDefaultGroups();
                  if ()
                     .tracef("Adding default groups: %s", Arrays.toString(defaultGroups));
                  
                  GroupPrincipalCallback gpc = 
                     new GroupPrincipalCallback(executionSubjectdefaultGroups);
                  callbacks.add(gpc);
               }
               if (callbacks.size() > 0)
               {
                  Callback[] cb = new Callback[callbacks.size()];
                  cbh.handle(callbacks.toArray(cb));
               }
            }
            if ()
               .tracef("Setting authenticated subject (%s) on security context (%s)"executionSubjectsc);
            // Set the authenticated subject
            sc.getSubjectInfo().setAuthenticatedSubject(executionSubject);
            // Fire complete for security context
            fireWorkContextSetupComplete(securityContext);
         }
         catch (Throwable t)
         {
            .securityContextSetupFailed(t.getMessage(), t);
            fireWorkContextSetupFailed(securityContext);
            throw new WorkException(.securityContextSetupFailed(t.getMessage()), t);
         }
      }
      else if (securityContext != null && .getCallbackSecurity() == null)
      {
         fireWorkContextSetupFailed(securityContext);
      }
   
      if (ctx != null)
      {
         Xid xid = ctx.getXid();
         if (xid != null)
         {
            .getXATerminator().startWork(xid);
         }
      }
      if ()
         .tracef("Started work: %s"this);  
   }

   
End
   protected void end()
   {
      if ()
         .tracef("Ending work: %s"this);  
      if (ctx == null)
      {
         ctx = getExecutionContext();
      }
      if (ctx != null)
      {
         Xid xid = ctx.getXid();
         if (xid != null)
         {
            .getXATerminator().endWork(xid);
         }
      }
      if ()
         .tracef("Ended work: %s"this);  
   }

   
Cancel
   protected void cancel()
   {
      if ()
         .tracef("Cancel work: %s"this);  
      if (ctx == null)
      {
         ctx = getExecutionContext();
      }
      if (ctx != null)
      {
         Xid xid = ctx.getXid();
         if (xid != null)
         {
            .getXATerminator().cancelWork(xid);
         }
      }
      if ()
         .tracef("Canceled work: %s"this);  
   }

   
Returns work context instance.

Parameters:
<T> class type info
workContextClass work context type
Returns:
work context instance
   public <T> T getWorkContext(Class<T> workContextClass)
   {
      T instance = null;
      if ( != null && .containsKey(workContextClass))
      {
         instance = workContextClass.cast(.get(workContextClass));
      }
      return instance;
   }

   
Adds new work context.

Parameters:
workContext new work context
workContextClass work context class
   public void addWorkContext(Class<? extends WorkContextworkContextClassWorkContext workContext)
   {
      if (workContextClass == null)
      {
         throw new IllegalArgumentException("Work context class is null");
      }
      if (workContext == null)
      {
         throw new IllegalArgumentException("Work context is null");
      }
      if ( == null)
      {
          = new HashMap<Class<? extends WorkContext>, WorkContext>(1);
      }
      if ()
         .tracef("Adding work context %s for %s"workContextClassthis);  
      .put(workContextClassworkContext);
   }
   
   
Calls listener after work context is setted up.

Parameters:
listener work context listener
   private void fireWorkContextSetupComplete(Object workContext)
   {
      if (workContext != null && workContext instanceof WorkContextLifecycleListener)
      {
         if ()
            .tracef("WorkContextSetupComplete(%s) for %s"workContextthis);  
         WorkContextLifecycleListener listener = (WorkContextLifecycleListener)workContext;
         listener.contextSetupComplete();   
      }
   }
   
   
Calls listener if setup failed

Parameters:
listener work context listener
   private void fireWorkContextSetupFailed(Object workContext)
   {
      if (workContext != null && workContext instanceof WorkContextLifecycleListener)
      {
         if ()
            .tracef("WorkContextSetupFailed(%s) for %s"workContextthis);  
         WorkContextLifecycleListener listener = (WorkContextLifecycleListener)workContext;
      }
   }
   
   
String representation

Returns:
The string
   public String toString()
   {
      StringBuilder buffer = new StringBuilder(100);
      buffer.append("WorkWrapper@").append(Integer.toHexString(System.identityHashCode(this)));
      buffer.append("[workManger=").append();
      buffer.append(" work=").append();
      if ( != null && .getXid() != null)
      {
         buffer.append(" xid=").append(.getXid());
         buffer.append(" txTimeout=").append(.getTransactionTimeout());
      }
      buffer.append(" workListener=").append();
      buffer.append(" workContexts=").append();
      buffer.append(" exception=").append();
      buffer.append("]");
      return buffer.toString();
   }
New to GrepCode? Check out our FAQ X