001/*
002 * (C) Copyright 2006-2015 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 *     bstefanescu
018 */
019package org.nuxeo.connect.update.task.guards;
020
021import java.util.Map;
022
023import org.apache.commons.jexl.Expression;
024import org.apache.commons.jexl.ExpressionFactory;
025import org.apache.commons.jexl.JexlContext;
026import org.apache.commons.jexl.parser.ParseException;
027import org.nuxeo.common.utils.ExceptionUtils;
028
029/**
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032public class Guard {
033
034    protected final String value;
035
036    protected Expression expr;
037
038    public Guard(String expr) {
039        value = expr;
040        try {
041            this.expr = ExpressionFactory.createExpression(expr);
042        } catch (ParseException e) {
043            throw new RuntimeException(e);
044        } catch (Exception e) { // stupid JEXL API throws Exception
045            throw ExceptionUtils.runtimeException(e);
046        }
047    }
048
049    public boolean evaluate(final Map<String, Object> map) {
050        map.put("Version", new VersionHelper());
051        map.put("Platform", new PlatformHelper());
052        JexlContext ctx = new JexlContext() {
053            @Override
054            @SuppressWarnings("rawtypes")
055            public void setVars(Map arg0) {
056                // do nothing
057            }
058
059            @Override
060            @SuppressWarnings("rawtypes")
061            public Map getVars() {
062                return map;
063            }
064        };
065        try {
066            return (Boolean) expr.evaluate(ctx);
067        } catch (Exception e) { // stupid JEXL API throws Exception
068            throw ExceptionUtils.runtimeException(e);
069        }
070    }
071
072}