1
2
3
4
5
6
7
8
9
10
11
12
13 package com.eviware.soapui.support.scripting.groovy;
14
15 import groovy.lang.Binding;
16 import groovy.lang.GroovyClassLoader;
17 import groovy.lang.GroovyShell;
18 import groovy.lang.Script;
19
20 import org.codehaus.groovy.control.CompilerConfiguration;
21
22 import com.eviware.soapui.support.StringUtils;
23 import com.eviware.soapui.support.scripting.SoapUIScriptEngine;
24
25 /***
26 * A Groovy ScriptEngine
27 *
28 * @author ole.matzura
29 */
30
31 public class SoapUIGroovyScriptEngine implements SoapUIScriptEngine
32 {
33 private GroovyClassLoader classLoader;
34 private GroovyShell shell;
35 private Binding binding;
36 private Script script;
37 private String scriptText;
38
39 public SoapUIGroovyScriptEngine( ClassLoader parentClassLoader )
40 {
41 classLoader = new GroovyClassLoader( parentClassLoader );
42 binding = new Binding();
43 CompilerConfiguration config = new CompilerConfiguration();
44 config.setDebug( true );
45 config.setVerbose( true );
46 shell = new GroovyShell( classLoader, binding, config );
47 }
48
49 public synchronized Object run() throws Exception
50 {
51 if( StringUtils.isNullOrEmpty( scriptText ))
52 return null;
53
54 if( script == null )
55 {
56 compile();
57 }
58
59 return script.run();
60 }
61
62 public synchronized void setScript( String scriptText )
63 {
64 if( scriptText != null && scriptText.equals( this.scriptText ))
65 return;
66
67 if( script != null )
68 {
69 script.setBinding( null );
70 script = null;
71
72 if( shell != null )
73 shell.resetLoadedClasses();
74
75 classLoader.clearCache();
76 }
77
78 this.scriptText = scriptText;
79 }
80
81 public void compile() throws Exception
82 {
83 if( script == null )
84 {
85 script = shell.parse( scriptText );
86 script.setBinding( binding );
87 }
88 }
89
90 public void setVariable( String name, Object value )
91 {
92 binding.setVariable( name, value );
93 }
94
95 public void clearVariables()
96 {
97 binding.getVariables().clear();
98 }
99
100 public void release()
101 {
102 script = null;
103
104 if( binding != null )
105 {
106 binding.getVariables().clear();
107 binding = null;
108 }
109
110 if( shell != null )
111 {
112 shell.resetLoadedClasses();
113 shell = null;
114 }
115 }
116
117 protected Binding getBinding()
118 {
119 return binding;
120 }
121
122 protected GroovyClassLoader getClassLoader()
123 {
124 return classLoader;
125 }
126
127 protected synchronized void reset()
128 {
129 script = null;
130 }
131
132 protected Script getScript()
133 {
134 return script;
135 }
136
137 protected String getScriptText()
138 {
139 return scriptText;
140 }
141
142 protected GroovyShell getShell()
143 {
144 return shell;
145 }
146 }