001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.language.simple;
018
019import org.apache.camel.Expression;
020import org.apache.camel.Predicate;
021import org.apache.camel.StaticService;
022import org.apache.camel.builder.ExpressionBuilder;
023import org.apache.camel.support.LanguageSupport;
024import org.apache.camel.util.CamelContextHelper;
025import org.apache.camel.util.LRUCache;
026import org.apache.camel.util.LRUCacheFactory;
027import org.apache.camel.util.ObjectHelper;
028import org.apache.camel.util.PredicateToExpressionAdapter;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031
032/**
033 * A <a href="http://camel.apache.org/simple.html">simple language</a>
034 * which maps simple property style notations to access headers and bodies.
035 * Examples of supported expressions are:
036 * <ul>
037 * <li>exchangeId to access the exchange id</li>
038 * <li>id to access the inbound message id</li>
039 * <li>in.body or body to access the inbound body</li>
040 * <li>in.body.OGNL or body.OGNL to access the inbound body using an OGNL expression</li>
041 * <li>mandatoryBodyAs(&lt;classname&gt;) to convert the in body to the given type, will throw exception if not possible to convert</li>
042 * <li>bodyAs(&lt;classname&gt;) to convert the in body to the given type, will return null if not possible to convert</li>
043 * <li>headerAs(&lt;key&gt;, &lt;classname&gt;) to convert the in header to the given type, will return null if not possible to convert</li>
044 * <li>out.body to access the inbound body</li>
045 * <li>in.header.foo or header.foo to access an inbound header called 'foo'</li>
046 * <li>in.header.foo[bar] or header.foo[bar] to access an inbound header called 'foo' as a Map and lookup the map with 'bar' as key</li>
047 * <li>in.header.foo.OGNL or header.OGNL to access an inbound header called 'foo' using an OGNL expression</li>
048 * <li>out.header.foo to access an outbound header called 'foo'</li>
049 * <li>property.foo to access the exchange property called 'foo'</li>
050 * <li>property.foo.OGNL to access the exchange property called 'foo' using an OGNL expression</li>
051 * <li>sys.foo to access the system property called 'foo'</li>
052 * <li>sysenv.foo to access the system environment called 'foo'</li>
053 * <li>exception.messsage to access the exception message</li>
054 * <li>threadName to access the current thread name</li>
055 * <li>date:&lt;command&gt; evaluates to a Date object
056 *     Supported commands are: <tt>now</tt> for current timestamp,
057 *     <tt>in.header.xxx</tt> or <tt>header.xxx</tt> to use the Date object in the in header.
058 *     <tt>out.header.xxx</tt> to use the Date object in the out header.
059 *     <tt>property.xxx</tt> to use the Date object in the exchange property.
060 *     <tt>file</tt> for the last modified timestamp of the file (available with a File consumer).
061 *     Command accepts offsets such as: <tt>now-24h</tt> or <tt>in.header.xxx+1h</tt> or even <tt>now+1h30m-100</tt>.
062 * </li>
063 * <li>date:&lt;command&gt;:&lt;pattern&gt; for date formatting using {@link java.text.SimpleDateFormat} patterns</li>
064 * <li>date-with-timezone:&lt;command&gt;:&lt;timezone&gt;:&lt;pattern&gt; for date formatting using {@link java.text.SimpleDateFormat} timezones and patterns</li>
065 * <li>bean:&lt;bean expression&gt; to invoke a bean using the
066 * {@link org.apache.camel.language.bean.BeanLanguage BeanLanguage}</li>
067 * <li>properties:&lt;[locations]&gt;:&lt;key&gt; for using property placeholders using the
068 *     {@link org.apache.camel.component.properties.PropertiesComponent}.
069 *     The locations parameter is optional and you can enter multiple locations separated with comma.
070 * </li>
071* </ul>
072 * <p/>
073 * The simple language supports OGNL notation when accessing either body or header.
074 * <p/>
075 * The simple language now also includes file language out of the box which means the following expression is also
076 * supported:
077 * <ul>
078 *   <li><tt>file:name</tt> to access the file name (is relative, see note below))</li>
079 *   <li><tt>file:name.noext</tt> to access the file name with no extension</li>
080 *   <li><tt>file:name.ext</tt> to access the file extension</li>
081 *   <li><tt>file:ext</tt> to access the file extension</li>
082 *   <li><tt>file:onlyname</tt> to access the file name (no paths)</li>
083 *   <li><tt>file:onlyname.noext</tt> to access the file name (no paths) with no extension </li>
084 *   <li><tt>file:parent</tt> to access the parent file name</li>
085 *   <li><tt>file:path</tt> to access the file path name</li>
086 *   <li><tt>file:absolute</tt> is the file regarded as absolute or relative</li>
087 *   <li><tt>file:absolute.path</tt> to access the absolute file path name</li>
088 *   <li><tt>file:length</tt> to access the file length as a Long type</li>
089 *   <li><tt>file:size</tt> to access the file length as a Long type</li>
090 *   <li><tt>file:modified</tt> to access the file last modified as a Date type</li>
091 * </ul>
092 * The <b>relative</b> file is the filename with the starting directory clipped, as opposed to <b>path</b> that will
093 * return the full path including the starting directory.
094 * <br/>
095 * The <b>only</b> file is the filename only with all paths clipped.
096 */
097public class SimpleLanguage extends LanguageSupport implements StaticService {
098
099    private static final Logger LOG = LoggerFactory.getLogger(SimpleLanguage.class);
100
101    // singleton for expressions without a result type
102    private static final SimpleLanguage SIMPLE = new SimpleLanguage();
103
104    boolean allowEscape = true;
105
106    // use caches to avoid re-parsing the same expressions over and over again
107    private LRUCache<String, Expression> cacheExpression;
108    private LRUCache<String, Predicate> cachePredicate;
109
110    /**
111     * Default constructor.
112     */
113    public SimpleLanguage() {
114    }
115
116    @Override
117    @SuppressWarnings("unchecked")
118    public void start() throws Exception {
119        // setup cache which requires CamelContext to be set first
120        if (cacheExpression == null && cachePredicate == null && getCamelContext() != null) {
121            int maxSize = CamelContextHelper.getMaximumSimpleCacheSize(getCamelContext());
122            if (maxSize > 0) {
123                cacheExpression = LRUCacheFactory.newLRUCache(16, maxSize, false);
124                cachePredicate = LRUCacheFactory.newLRUCache(16, maxSize, false);
125                LOG.debug("Simple language predicate/expression cache size: {}", maxSize);
126            } else {
127                LOG.debug("Simple language disabled predicate/expression cache");
128            }
129        }
130    }
131
132    @Override
133    public void stop() throws Exception {
134        if (cachePredicate != null) {
135            if (LOG.isDebugEnabled()) {
136                LOG.debug("Clearing simple language predicate cache[size={}, hits={}, misses={}, evicted={}]",
137                    cachePredicate.size(), cachePredicate.getHits(), cachePredicate.getMisses(), cachePredicate.getEvicted());
138            }
139        }
140        if (cacheExpression != null) {
141            if (LOG.isDebugEnabled()) {
142                LOG.debug("Clearing simple language expression cache[size={}, hits={}, misses={}, evicted={}]",
143                    cacheExpression.size(), cacheExpression.getHits(), cacheExpression.getMisses(), cacheExpression.getEvicted());
144            }
145        }
146    }
147
148    @SuppressWarnings("deprecation")
149    public Predicate createPredicate(String expression) {
150        ObjectHelper.notNull(expression, "expression");
151
152        Predicate answer = cachePredicate != null ? cachePredicate.get(expression) : null;
153        if (answer == null) {
154
155            expression = loadResource(expression);
156
157            // support old simple language syntax
158            answer = SimpleBackwardsCompatibleParser.parsePredicate(expression, allowEscape);
159            if (answer == null) {
160                // use the new parser
161                SimplePredicateParser parser = new SimplePredicateParser(expression, allowEscape, cacheExpression);
162                answer = parser.parsePredicate();
163            }
164            if (cachePredicate != null && answer != null) {
165                cachePredicate.put(expression, answer);
166            }
167        }
168
169        return answer;
170    }
171
172    @SuppressWarnings("deprecation")
173    public Expression createExpression(String expression) {
174        ObjectHelper.notNull(expression, "expression");
175
176        Expression answer = cacheExpression != null ? cacheExpression.get(expression) : null;
177        if (answer == null) {
178
179            expression = loadResource(expression);
180
181            // support old simple language syntax
182            answer = SimpleBackwardsCompatibleParser.parseExpression(expression, allowEscape);
183            if (answer == null) {
184                // use the new parser
185                SimpleExpressionParser parser = new SimpleExpressionParser(expression, allowEscape, cacheExpression);
186                answer = parser.parseExpression();
187            }
188            if (cacheExpression != null && answer != null) {
189                cacheExpression.put(expression, answer);
190            }
191        }
192
193        return answer;
194    }
195
196    /**
197     * Creates a new {@link Expression}.
198     * <p/>
199     * <b>Important:</b> If you need to use a predicate (function to return true|false) then use
200     * {@link #predicate(String)} instead.
201     */
202    public static Expression simple(String expression) {
203        return expression(expression);
204    }
205
206    /**
207     * Creates a new {@link Expression} (or {@link Predicate}
208     * if the resultType is a <tt>Boolean</tt>, or <tt>boolean</tt> type).
209     */
210    public static Expression simple(String expression, Class<?> resultType) {
211        return new SimpleLanguage().createExpression(expression, resultType);
212    }
213
214    public Expression createExpression(String expression, Class<?> resultType) {
215        if (resultType == Boolean.class || resultType == boolean.class) {
216            // if its a boolean as result then its a predicate
217            Predicate predicate = createPredicate(expression);
218            return PredicateToExpressionAdapter.toExpression(predicate);
219        } else {
220            Expression exp = createExpression(expression);
221            if (resultType != null) {
222                exp = ExpressionBuilder.convertToExpression(exp, resultType);
223            }
224            return exp;
225        }
226    }
227
228    /**
229     * Creates a new {@link Expression}.
230     * <p/>
231     * <b>Important:</b> If you need to use a predicate (function to return true|false) then use
232     * {@link #predicate(String)} instead.
233     */
234    public static Expression expression(String expression) {
235        return SIMPLE.createExpression(expression);
236    }
237
238    /**
239     * Creates a new {@link Predicate}.
240     */
241    public static Predicate predicate(String predicate) {
242        return SIMPLE.createPredicate(predicate);
243    }
244
245    /**
246     * Does the expression include a simple function.
247     *
248     * @param expression the expression
249     * @return <tt>true</tt> if one or more simple function is included in the expression
250     */
251    public static boolean hasSimpleFunction(String expression) {
252        return SimpleTokenizer.hasFunctionStartToken(expression);
253    }
254
255    /**
256     * Change the start tokens used for functions.
257     * <p/>
258     * This can be used to alter the function tokens to avoid clashes with other
259     * frameworks etc.
260     * <p/>
261     * The default start tokens is <tt>${</tt> and <tt>$simple{</tt>.
262     *
263     * @param startToken new start token(s) to be used for functions
264     */
265    public static void changeFunctionStartToken(String... startToken) {
266        SimpleTokenizer.changeFunctionStartToken(startToken);
267    }
268    
269    /**
270     * Change the end tokens used for functions.
271     * <p/>
272     * This can be used to alter the function tokens to avoid clashes with other
273     * frameworks etc.
274     * <p/>
275     * The default end token is <tt>}</tt>
276     *
277     * @param endToken new end token(s) to be used for functions
278     */
279    public static void changeFunctionEndToken(String... endToken) {
280        SimpleTokenizer.changeFunctionEndToken(endToken);
281    }
282
283    /**
284     * Change the start token used for functions.
285     * <p/>
286     * This can be used to alter the function tokens to avoid clashes with other
287     * frameworks etc.
288     * <p/>
289     * The default start tokens is <tt>${</tt> and <tt>$simple{</tt>.
290     *
291     * @param startToken new start token to be used for functions
292     */
293    public void setFunctionStartToken(String startToken) {
294        changeFunctionStartToken(startToken);
295    }
296
297    /**
298     * Change the end token used for functions.
299     * <p/>
300     * This can be used to alter the function tokens to avoid clashes with other
301     * frameworks etc.
302     * <p/>
303     * The default end token is <tt>}</tt>
304     *
305     * @param endToken new end token to be used for functions
306     */
307    public void setFunctionEndToken(String endToken) {
308        changeFunctionEndToken(endToken);
309    }
310
311}