1 /*
2 * $Id: OGNLFilter.java 7976 2007-08-21 14:26:13Z dirk.olmes $
3 * --------------------------------------------------------------------------------------
4 * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.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
11 package org.mule.routing.filters;
12
13 import org.mule.config.ConfigurationException;
14 import org.mule.umo.UMOFilter;
15 import org.mule.umo.UMOMessage;
16
17 import ognl.Ognl;
18 import ognl.OgnlException;
19 import org.apache.commons.logging.Log;
20 import org.apache.commons.logging.LogFactory;
21
22 public class OGNLFilter implements UMOFilter
23 {
24 protected final Log logger = LogFactory.getLog(this.getClass());
25
26 private volatile String expression;
27 private volatile Object compiledExpression;
28
29 public String getExpression()
30 {
31 return expression;
32 }
33
34 /**
35 * Sets the expression for this filter. The argument must be a valid expression
36 * as described ini the OGNL documentation.
37 *
38 * @param expression the expression to use for message evaluation
39 * @throws ConfigurationException if the expression cannot be parsed
40 * @see {@link Ognl#parseExpression(String)}
41 */
42 public void setExpression(String expression) throws ConfigurationException
43 {
44 try
45 {
46 this.compiledExpression = Ognl.parseExpression(expression);
47 this.expression = expression;
48 }
49 catch (OgnlException ex)
50 {
51 throw new ConfigurationException(ex);
52 }
53 }
54
55 public boolean accept(UMOMessage message)
56 {
57 // no message: nothing to filter
58 if (message == null)
59 {
60 return false;
61 }
62
63 Object candidate = message.getPayload();
64 // no payload: still nothing to filter
65 if (candidate == null)
66 {
67 return false;
68 }
69
70 // no expression configured: we reject by default
71 if (compiledExpression == null)
72 {
73 logger.warn("No expression configured - rejecting message.");
74 return false;
75 }
76
77 try
78 {
79 Object result = Ognl.getValue(compiledExpression, candidate);
80 // we only need to take boolean expressoin results into account
81 if (result instanceof Boolean)
82 {
83 return ((Boolean) result).booleanValue();
84 }
85 }
86 catch (OgnlException ex)
87 {
88 logger.error(ex);
89 }
90
91 // default action: reject
92 return false;
93 }
94
95 }