View Javadoc

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