001/*
002 * (C) Copyright 2007 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: ComponentTagUtils.java 28610 2008-01-09 17:13:52Z sfermigier $
020 */
021
022package org.nuxeo.ecm.platform.ui.web.util;
023
024import javax.el.ELContext;
025import javax.el.ELException;
026import javax.el.ExpressionFactory;
027import javax.el.ValueExpression;
028import javax.faces.application.Application;
029import javax.faces.context.FacesContext;
030import javax.faces.view.facelets.FaceletContext;
031
032import org.apache.commons.logging.Log;
033import org.apache.commons.logging.LogFactory;
034
035/**
036 * Component tag utils.
037 *
038 * @author <a href="mailto:at@nuxeo.com">Anahide Tchertchian</a>
039 */
040public final class ComponentTagUtils {
041
042    private static final Log log = LogFactory.getLog(ComponentTagUtils.class);
043
044    // Utility class.
045    private ComponentTagUtils() {
046    }
047
048    /**
049     * Returns true if the specified value contains a value expression, e.g the start and end of EL markers.
050     *
051     * @param value the value to evaluate, returns false if null
052     */
053    public static boolean isValueReference(String value) {
054        if (value == null) {
055            return false;
056        }
057        return value.contains("#{") && value.indexOf("#{") < value.indexOf('}') || value.contains("${")
058                && value.indexOf("${") < value.indexOf('}');
059    }
060
061    /**
062     * Returns true if the specified value is a value expression, e.g starting and ending with EL markers after being
063     * trimmed.
064     *
065     * @param value the value to evaluate, returns false if null
066     * @since 5.6
067     */
068    public static boolean isStrictValueReference(String value) {
069        if (value == null) {
070            return false;
071        }
072        value = value.trim();
073        return (value.startsWith("#{") && value.indexOf("#{") < value.indexOf('}') && value.endsWith("}"))
074                || (value.startsWith("${") && value.indexOf("${") < value.indexOf('}') && value.endsWith("}"));
075    }
076
077    /**
078     * Returns a value name for given strict value reference. If reference is #{foo} or ${foo}, will return "foo".
079     *
080     * @since 5.6
081     * @throws IllegalArgumentException if reference is null or {@link #isStrictValueReference(String)} returns false.
082     * @param valueReference
083     */
084    public static String getBareValueName(String valueReference) {
085        if (!isStrictValueReference(valueReference)) {
086            throw new IllegalArgumentException("Invalid value reference '" + valueReference + "'");
087        }
088        return valueReference.substring(2, valueReference.length() - 1);
089    }
090
091    /**
092     * Resolves an expression from a given faces context.
093     * <p>
094     * Resolves the expression a second time when first resolution gives a String value using the EL Expression syntax.
095     * <p>
096     * Does not throw any error when resolution fails (only logs an error message).
097     *
098     * @see #resolveElExpression(FaceletContext, String)
099     */
100    public static Object resolveElExpression(FacesContext context, String elExpression) {
101        if (!isValueReference(elExpression)) {
102            // literal
103            return elExpression;
104        } else {
105            if (context == null) {
106                log.error("FacesContext is null => cannot resolve el expression '" + elExpression + "'");
107                return null;
108            }
109            // expression => evaluate
110            Application app = context.getApplication();
111            try {
112                return app.evaluateExpressionGet(context, elExpression, Object.class);
113            } catch (ELException e) {
114                log.error("Faces context: Error processing expression '" + elExpression + "'", e);
115                return null;
116            }
117        }
118    }
119
120    /**
121     * Resolves given value expression as string and sets given value on it.
122     *
123     * @since 6.0
124     */
125    public static void applyValueExpression(FacesContext context, String elExpression, Object value) {
126        if (!isStrictValueReference(elExpression)) {
127            log.warn("Cannot set value '" + value + "' for expression '" + elExpression + "'");
128        } else {
129            if (context == null) {
130                log.error("FacesContext is null => cannot resolve el expression '" + elExpression + "'");
131                return;
132            }
133            Application app = context.getApplication();
134            ExpressionFactory eFactory = app.getExpressionFactory();
135            ELContext elContext = context.getELContext();
136            try {
137                ValueExpression vExpression = eFactory.createValueExpression(elContext, elExpression, Object.class);
138                vExpression.setValue(elContext, value);
139            } catch (ELException e) {
140                log.error("Error setting value '" + value + "' for expression '" + elExpression + "'", e);
141            }
142        }
143    }
144
145    /**
146     * Resolves an expression from a given facelet context, using its {@link ExpressionFactory} that can hold a wider
147     * context than the faces context behind it.
148     * <p>
149     * Resolves the expression a second time when first resolution gives a String value using the EL Expression syntax.
150     * <p>
151     * Does not throw any error when resolution fails (only logs an error message).
152     */
153    public static Object resolveElExpression(FaceletContext faceletContext, String elExpression) {
154        if (!isValueReference(elExpression)) {
155            // literal
156            return elExpression;
157        } else {
158            if (faceletContext == null) {
159                log.error("FaceletContext is null => cannot resolve el expression '" + elExpression + "'");
160                return null;
161            }
162            // expression => evaluate
163            ExpressionFactory eFactory = faceletContext.getExpressionFactory();
164            ELContext elContext = faceletContext.getFacesContext().getELContext();
165            ValueExpression expr = eFactory.createValueExpression(faceletContext, elExpression, Object.class);
166            try {
167                return expr.getValue(elContext);
168            } catch (ELException e) {
169                log.error("Facelet context: Error processing expression '" + elExpression + "'", e);
170                return null;
171            }
172        }
173    }
174
175}