001/*
002 * (C) Copyright 2006-2008 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.platform.el;
023
024import javax.el.ELContext;
025import javax.el.ExpressionFactory;
026
027public class ExpressionEvaluator {
028
029    protected ExpressionEvaluator() {
030    }
031
032    public ExpressionEvaluator(ExpressionFactory factory) {
033        expressionFactory = factory;
034    }
035
036    protected ExpressionFactory expressionFactory;
037
038    public void setExpressionFactory(ExpressionFactory expressionFactory) {
039        this.expressionFactory = expressionFactory;
040    }
041
042    public <T> T evaluateExpression(ELContext context, String stringExpression, Class<T> clazz) {
043        return clazz.cast(expressionFactory.createValueExpression(context, stringExpression, clazz).getValue(context));
044    }
045
046    public void bindValue(ELContext context, String name, Object value) {
047        if (value == null) {
048            throw new IllegalArgumentException("No value provided, cannot bind " + name + " in context " + context);
049        }
050        // the jsf/facelets way of binding additional values in the context
051        // is to contribute a variable mapper wrapping the existing one, so
052        // that contexts are not merged and variables are not overridden,
053        // especially when the variable mapper is used in a shared context =>
054        // maybe change this behaviour if needed
055        context.getVariableMapper().setVariable(name, expressionFactory.createValueExpression(value, value.getClass()));
056    }
057
058}