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.module.ognl.expression;
8   
9   import org.mule.api.MuleMessage;
10  import org.mule.api.expression.ExpressionEvaluator;
11  import org.mule.api.expression.ExpressionRuntimeException;
12  import org.mule.api.lifecycle.Disposable;
13  import org.mule.config.i18n.CoreMessages;
14  
15  import java.util.Map;
16  import java.util.concurrent.ConcurrentHashMap;
17  
18  import ognl.Ognl;
19  import ognl.OgnlException;
20  import org.apache.commons.logging.Log;
21  import org.apache.commons.logging.LogFactory;
22  
23  /**
24   * An expression evaluator that uses OGNL as the expression language
25   */
26  public class OgnlExpressionEvaluator implements ExpressionEvaluator, Disposable
27  {
28      Map<String, Object> expressions = new ConcurrentHashMap<String, Object>(4);
29  
30      public static final String NAME = "ognl";
31  
32      /**
33       * logger used by this class
34       */
35      protected transient final Log logger = LogFactory.getLog(OgnlExpressionEvaluator.class);
36  
37      public Object evaluate(String expression, MuleMessage message)
38      {
39          Object o = expressions.get(expression);
40          if(o==null)
41          {
42              try
43              {
44                  o = Ognl.parseExpression(expression);
45                  expressions.put(expression,  o);
46              }
47              catch (OgnlException e)
48              {
49                  throw new ExpressionRuntimeException(CoreMessages.expressionMalformed(expression,  NAME), e);
50              }
51          }
52  
53          try
54          {
55              return Ognl.getValue(o, message.getPayload());
56          }
57          catch (OgnlException e)
58          {
59              //Only log the exceptions so that the behaviour is consistent with the Expression API
60              logger.warn(e.getMessage(), e);
61              return null;
62          }
63  
64      }
65  
66      public void setName(String name)
67      {
68          throw new UnsupportedOperationException("setName");
69      }
70  
71      public String getName()
72      {
73          return NAME;
74      }
75  
76      public void dispose()
77      {
78          expressions.clear();
79      }
80  }