View Javadoc

1   /*
2   
3   This software is OSI Certified Open Source Software.
4   OSI Certified is a certification mark of the Open Source Initiative.
5   
6   The license (Mozilla version 1.0) can be read at the MMBase site.
7   See http://www.MMBase.org/license
8   
9   */
10  package net.sf.mmapps.commons.bridge;
11  
12  import org.mmbase.bridge.Cloud;
13  import org.mmbase.util.logging.Logger;
14  import org.mmbase.util.logging.Logging;
15  
16  
17  public class CloudThreadLocal {
18  
19      /*** MMbase logging system */
20      private static Logger log = Logging.getLoggerInstance(CloudThreadLocal.class.getName());
21      
22      /***
23       * A ThreadLocal maintaining current cloud for the given execution thread.
24       */
25      private static final ThreadLocal context = new ThreadLocal();
26      
27      public static Cloud currentCloud() {
28          return (Cloud) context.get();
29      }
30      
31      /***
32       * Associates the given cloud with the current thread of execution.
33       *
34       * @param cloud The cloud to bind.
35       */
36      public static void bind(Cloud cloud) {
37          cleanupAnyOrphanedCloud();
38          doBind( cloud );
39      }
40      
41      /***
42       * Unassociate a previously bound cloud from the current thread of execution.
43       *
44       * @return The cloud which was unbound.
45       */
46      public static Cloud unbind() {
47          return doUnbind();
48      }
49      
50      private static void cleanupAnyOrphanedCloud() {
51          Cloud orphan = doUnbind();
52          if ( orphan != null ) {
53              log.warn( "Already cloud bound on call to bind(); make sure you clean up your cloud!" );
54          }
55      }
56      
57      private static void doBind(Cloud cloud) {
58          if ( cloud != null ) {
59              context.set( cloud );
60          }
61      }
62  
63      private static Cloud doUnbind() {
64          Cloud cloud = (Cloud) context.get();
65          if ( cloud != null ) {
66              context.set( null );
67          }
68          return cloud;
69      }
70      
71  }