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