View Javadoc

1   /*
2    * $Id: CachedJndiNameResolver.java 21648 2011-04-01 11:48:20Z pablo.kraan $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transport.jms.jndi;
12  
13  import org.mule.api.MuleException;
14  
15  import java.util.Map;
16  import java.util.concurrent.ConcurrentHashMap;
17  
18  import javax.naming.Context;
19  import javax.naming.NamingException;
20  
21  /**
22   * Defines a {@link JndiNameResolver} that uses a cache in order to store
23   * the already resolved names.
24   * <p/>
25   * The cache does not have an automated mechanism for cleaning up the data.
26   * In case of getting corrupt data, a way to cleaning up the cache is to stop
27   * and then restart the instance.
28   */
29  public class CachedJndiNameResolver extends AbstractJndiNameResolver
30  {
31  
32      protected Map<String, Object> cache;
33  
34      public Object lookup(String name) throws NamingException
35      {
36          Object result = findInCache(name);
37  
38          if (result == null) {
39              result = findInContext(name);
40          }
41  
42          return result;
43      }
44  
45      private Object findInContext(String name) throws NamingException
46      {
47  
48          Context jndiContext = createInitialContext();
49  
50          try
51          {
52              Object result = jndiContext.lookup(name);
53  
54              if (result != null)
55              {
56                  cache.put(name, result);
57              }
58  
59              return result;
60          }
61          finally
62          {
63              jndiContext.close();
64          }
65      }
66  
67      private Object findInCache(String name)
68      {
69          Object result = null;
70          if (name != null)
71          {
72              result = cache.get(name);
73              if (logger.isDebugEnabled())
74              {
75                  logger.debug(String.format("Object: " + name + " was %sfound in the cache", (result == null)? "not ": ""));
76              }
77          }
78  
79          return result;
80      }
81  
82      @Override
83      public void initialise() {
84          cache = new ConcurrentHashMap<String, Object>();
85      }
86  
87      /**
88       * {@inheritDoc}
89       * <p/>
90       * Cleans up the cache.
91       */
92      @Override
93      public void stop() throws MuleException
94      {
95          cache.clear();
96      }
97  }