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;
028import org.nuxeo.connect.update.PackageUpdateService;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033public class Guard {
034
035    protected final String value;
036
037    protected Expression expr;
038
039    public Guard(String expr) {
040        value = expr;
041        try {
042            this.expr = ExpressionFactory.createExpression(expr);
043        } catch (ParseException e) {
044            throw new RuntimeException(e);
045        } catch (Exception e) { // stupid JEXL API throws Exception
046            throw ExceptionUtils.runtimeException(e);
047        }
048    }
049
050    public boolean evaluate(final Map<String, Object> map) {
051        map.put("Version", new VersionHelper());
052        map.put("Platform", new PlatformHelper());
053        map.put("Packages", new PackagesHelper((PackageUpdateService) map.get("packageUpdateService")));
054        JexlContext ctx = new JexlContext() {
055            @Override
056            @SuppressWarnings("rawtypes")
057            public void setVars(Map arg0) {
058                // do nothing
059            }
060
061            @Override
062            @SuppressWarnings("rawtypes")
063            public Map getVars() {
064                return map;
065            }
066        };
067        try {
068            return (Boolean) expr.evaluate(ctx);
069        } catch (Exception e) { // stupid JEXL API throws Exception
070            throw ExceptionUtils.runtimeException(e);
071        }
072    }
073
074}