001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * bstefanescu 011 */ 012package org.nuxeo.ecm.automation.core.scripting; 013 014import org.mvel2.compiler.BlankLiteral; 015import org.mvel2.templates.CompiledTemplate; 016import org.mvel2.templates.TemplateCompiler; 017import org.mvel2.templates.TemplateRuntime; 018import org.nuxeo.ecm.automation.OperationContext; 019 020/** 021 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 022 */ 023public class MvelTemplate implements Expression { 024 025 private static final long serialVersionUID = 1L; 026 027 protected transient volatile CompiledTemplate compiled; 028 029 protected final String expr; 030 031 public MvelTemplate(String expr) { 032 this.expr = expr; 033 } 034 035 @Override 036 public Object eval(OperationContext ctx) { 037 if (compiled == null) { 038 compiled = TemplateCompiler.compileTemplate(expr); 039 } 040 Object obj = TemplateRuntime.execute(compiled, Scripting.initBindings(ctx)); 041 return obj == null || obj.getClass().isAssignableFrom(BlankLiteral.class) ? "" : obj.toString(); 042 } 043 044}