View Javadoc

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