001: /*
002: * soapUI, copyright (C) 2004-2007 eviware.com
003: *
004: * soapUI is free software; you can redistribute it and/or modify it under the
005: * terms of version 2.1 of the GNU Lesser General Public License as published by
006: * the Free Software Foundation.
007: *
008: * soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
009: * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
010: * See the GNU Lesser General Public License for more details at gnu.org.
011: */
012:
013: package com.eviware.soapui.support.scripting.groovy;
014:
015: import groovy.lang.Binding;
016: import groovy.lang.GroovyClassLoader;
017: import groovy.lang.GroovyShell;
018: import groovy.lang.Script;
019:
020: import com.eviware.soapui.support.scripting.SoapUIScriptEngine;
021:
022: /**
023: * A Groovy ScriptEngine
024: *
025: * @author ole.matzura
026: */
027:
028: public class SoapUIGroovyScriptEngine implements SoapUIScriptEngine {
029: private GroovyClassLoader classLoader;
030: private GroovyShell shell;
031: private Binding binding;
032: private Script script;
033: private String scriptText;
034:
035: public SoapUIGroovyScriptEngine(ClassLoader parentClassLoader) {
036: classLoader = new GroovyClassLoader(parentClassLoader);
037: binding = new Binding();
038: shell = new GroovyShell(classLoader, binding);
039: }
040:
041: public synchronized Object run() throws Exception {
042: if (script == null) {
043: compile();
044: }
045:
046: return script.run();
047: }
048:
049: public synchronized void setScript(String scriptText) {
050: if (scriptText != null && scriptText.equals(this .scriptText))
051: return;
052:
053: if (script != null) {
054: script.setBinding(null);
055: script = null;
056:
057: if (shell != null)
058: shell.resetLoadedClasses();
059:
060: classLoader.clearCache();
061: }
062:
063: this .scriptText = scriptText;
064: }
065:
066: public void compile() throws Exception {
067: if (script == null) {
068: script = shell.parse(scriptText);
069: script.setBinding(binding);
070: }
071: }
072:
073: public void setVariable(String name, Object value) {
074: binding.setVariable(name, value);
075: }
076:
077: public void clearVariables() {
078: binding.getVariables().clear();
079: }
080:
081: public void release() {
082: script = null;
083:
084: if (binding != null) {
085: binding.getVariables().clear();
086: binding = null;
087: }
088:
089: if (shell != null) {
090: shell.resetLoadedClasses();
091: shell = null;
092: }
093: }
094:
095: protected Binding getBinding() {
096: return binding;
097: }
098:
099: protected GroovyClassLoader getClassLoader() {
100: return classLoader;
101: }
102:
103: protected synchronized void reset() {
104: script = null;
105: }
106:
107: protected Script getScript() {
108: return script;
109: }
110:
111: protected String getScriptText() {
112: return scriptText;
113: }
114:
115: protected GroovyShell getShell() {
116: return shell;
117: }
118: }
|