001/* 002 * Copyright 2002-2015 the original author or authors. 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 * https://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 017package org.springframework.scripting.bsh; 018 019import java.io.IOException; 020import java.io.StringReader; 021import java.util.Map; 022 023import bsh.EvalError; 024import bsh.Interpreter; 025 026import org.springframework.beans.factory.BeanClassLoaderAware; 027import org.springframework.scripting.ScriptCompilationException; 028import org.springframework.scripting.ScriptEvaluator; 029import org.springframework.scripting.ScriptSource; 030 031/** 032 * BeanShell-based implementation of Spring's {@link ScriptEvaluator} strategy interface. 033 * 034 * @author Juergen Hoeller 035 * @since 4.0 036 * @see Interpreter#eval(String) 037 */ 038public class BshScriptEvaluator implements ScriptEvaluator, BeanClassLoaderAware { 039 040 private ClassLoader classLoader; 041 042 043 /** 044 * Construct a new BshScriptEvaluator. 045 */ 046 public BshScriptEvaluator() { 047 } 048 049 /** 050 * Construct a new BshScriptEvaluator. 051 * @param classLoader the ClassLoader to use for the {@link Interpreter} 052 */ 053 public BshScriptEvaluator(ClassLoader classLoader) { 054 this.classLoader = classLoader; 055 } 056 057 058 @Override 059 public void setBeanClassLoader(ClassLoader classLoader) { 060 this.classLoader = classLoader; 061 } 062 063 064 @Override 065 public Object evaluate(ScriptSource script) { 066 return evaluate(script, null); 067 } 068 069 @Override 070 public Object evaluate(ScriptSource script, Map<String, Object> arguments) { 071 try { 072 Interpreter interpreter = new Interpreter(); 073 interpreter.setClassLoader(this.classLoader); 074 if (arguments != null) { 075 for (Map.Entry<String, Object> entry : arguments.entrySet()) { 076 interpreter.set(entry.getKey(), entry.getValue()); 077 } 078 } 079 return interpreter.eval(new StringReader(script.getScriptAsString())); 080 } 081 catch (IOException ex) { 082 throw new ScriptCompilationException(script, "Cannot access BeanShell script", ex); 083 } 084 catch (EvalError ex) { 085 throw new ScriptCompilationException(script, ex); 086 } 087 } 088 089}