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.cache.keygenerator;
8   
9   import org.mule.api.MuleEvent;
10  
11  import java.io.NotSerializableException;
12  import java.io.Serializable;
13  
14  import org.apache.commons.logging.Log;
15  import org.apache.commons.logging.LogFactory;
16  
17  /**
18   * Implements {@link KeyGenerator} using the Mule expression language to
19   * generate the cache keys.
20   */
21  public class ExpressionKeyGenerator implements KeyGenerator
22  {
23  
24      protected Log logger = LogFactory.getLog(getClass());
25  
26      private String expression;
27  
28      public Serializable generateKey(MuleEvent event) throws NotSerializableException
29      {
30          Object key = event.getMuleContext().getExpressionManager().evaluate(expression, event.getMessage());
31  
32          if (logger.isDebugEnabled())
33          {
34              logger.debug("Generated key for event: " + event + " key: " + key);
35          }
36  
37          if (key instanceof Serializable)
38          {
39              return (Serializable) key;
40          }
41          else
42          {
43              throw new NotSerializableException("Generated key must a serializable object but was "
44                                                 + (key != null ? key.getClass().getName() : "null"));
45          }
46      }
47  
48      public String getExpression()
49      {
50          return expression;
51      }
52  
53      public void setExpression(String expression)
54      {
55          this.expression = expression;
56      }
57  }