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