001/*
002 * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *
017 * $Id$
018 */
019
020package org.nuxeo.ecm.platform.el;
021
022import javax.el.ELContext;
023import javax.el.ExpressionFactory;
024
025public class ExpressionEvaluator {
026
027    protected ExpressionEvaluator() {
028    }
029
030    public ExpressionEvaluator(ExpressionFactory factory) {
031        expressionFactory = factory;
032    }
033
034    protected ExpressionFactory expressionFactory;
035
036    public void setExpressionFactory(ExpressionFactory expressionFactory) {
037        this.expressionFactory = expressionFactory;
038    }
039
040    public <T> T evaluateExpression(ELContext context, String stringExpression, Class<T> clazz) {
041        return clazz.cast(expressionFactory.createValueExpression(context, stringExpression, clazz).getValue(context));
042    }
043
044    public void bindValue(ELContext context, String name, Object value) {
045        if (value == null) {
046            throw new IllegalArgumentException("No value provided, cannot bind " + name + " in context " + context);
047        }
048        // the jsf/facelets way of binding additional values in the context
049        // is to contribute a variable mapper wrapping the existing one, so
050        // that contexts are not merged and variables are not overridden,
051        // especially when the variable mapper is used in a shared context =>
052        // maybe change this behaviour if needed
053        context.getVariableMapper().setVariable(name, expressionFactory.createValueExpression(value, value.getClass()));
054    }
055
056}