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