001/* 002 * (C) Copyright 2006-2010 Nuxeo SAS (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.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 this.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 @SuppressWarnings("rawtypes") 052 public void setVars(Map arg0) { 053 // do nothing 054 } 055 056 @SuppressWarnings("rawtypes") 057 public Map getVars() { 058 return map; 059 } 060 }; 061 try { 062 return (Boolean) expr.evaluate(ctx); 063 } catch (Exception e) { // stupid JEXL API throws Exception 064 throw ExceptionUtils.runtimeException(e); 065 } 066 } 067 068}