001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: SpringParseUtil.java 145 2011-10-20 18:10:07Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.jibx;
009    
010    
011    import org.jibx.runtime.JiBXParseException;
012    import org.springframework.expression.Expression;
013    import org.springframework.expression.ParseException;
014    import org.springframework.expression.ParserContext;
015    import org.springframework.expression.spel.standard.SpelExpressionParser;
016    
017    /**
018     * JiBX parsing utility methods for Spring expressions.
019     */
020    public final class SpringParseUtil {
021    
022        private SpringParseUtil() {
023        }
024    
025        /**
026         * Deserialize a Spring {@link Expression}.
027         *
028         * @see #serializeExpression
029         */
030        public static Expression deserializeExpression(String string) throws JiBXParseException {
031            return SpringParseUtil.deserializeExpression(string, null);
032        }
033    
034        /**
035         * Deserialize a Spring {@link Expression} as a template expression. Equivalent to
036         *  <blockquote><code>
037         *  deserializeExpression(string, ParserContext.TEMPLATE_EXPRESSION);
038         *  <code><blockquote>
039         *
040         * @see #serializeExpression
041         * @see #deserializeExpression(String, ParserContext)
042         */
043        public static Expression deserializeTemplateExpression(String string) throws JiBXParseException {
044            return SpringParseUtil.deserializeExpression(string, ParserContext.TEMPLATE_EXPRESSION);
045        }
046    
047        /**
048         * Deserialize a Spring {@link Expression} using the supplied {@link ParserContext}.
049         *
050         * @see #serializeExpression
051         */
052        public static Expression deserializeExpression(String string, ParserContext context) throws JiBXParseException {
053            SpelExpressionParser parser = new SpelExpressionParser();
054            try {
055                return parser.parseExpression(string, context);
056            } catch (ParseException e) {
057                throw new JiBXParseException("invalid Spring EL expression", string, e);
058            }
059        }
060    
061        /**
062         * Serialize a Spring {@link Expression}.
063         *
064         * @see #deserializeExpression
065         */
066        public static String serializeExpression(Expression expr) {
067            return expr.getExpressionString();
068        }
069    }
070