View Javadoc

1   /*
2    *  soapUI, copyright (C) 2004-2010 eviware.com 
3    *
4    *  soapUI is free software; you can redistribute it and/or modify it under the 
5    *  terms of version 2.1 of the GNU Lesser General Public License as published by 
6    *  the Free Software Foundation.
7    *
8    *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
9    *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
10   *  See the GNU Lesser General Public License for more details at gnu.org.
11   */
12  
13  package com.eviware.soapui.support.scripting.js;
14  
15  import org.mozilla.javascript.Context;
16  import org.mozilla.javascript.ContextFactory;
17  import org.mozilla.javascript.Script;
18  import org.mozilla.javascript.ScriptableObject;
19  
20  import com.eviware.soapui.support.StringUtils;
21  import com.eviware.soapui.support.scripting.SoapUIScriptEngine;
22  import com.eviware.soapui.support.types.StringToObjectMap;
23  
24  /***
25   * A Groovy ScriptEngine
26   * 
27   * @author ole.matzura
28   */
29  
30  public class JsScriptEngine implements SoapUIScriptEngine
31  {
32  	private String scriptText;
33  	private StringToObjectMap properties = new StringToObjectMap();
34  	private final ClassLoader parentClassLoader;
35  
36  	public JsScriptEngine( ClassLoader parentClassLoader )
37  	{
38  		this.parentClassLoader = parentClassLoader;
39  	}
40  
41  	public Object run() throws Exception
42  	{
43  		if( StringUtils.isNullOrEmpty( scriptText ) )
44  			return null;
45  
46  		Context context = ContextFactory.getGlobal().enterContext();
47  		context.setApplicationClassLoader( parentClassLoader );
48  
49  		ScriptableObject scope = context.initStandardObjects();
50  
51  		try
52  		{
53  			for( String name : properties.keySet() )
54  				ScriptableObject.putProperty( scope, name, Context.javaToJS( properties.get( name ), scope ) );
55  
56  			Script script = context.compileString( scriptText, "Script", 0, null );
57  
58  			return script.exec( context, scope );
59  		}
60  		finally
61  		{
62  			for( String name : properties.keySet() )
63  				scope.delete( name );
64  
65  			Context.exit();
66  		}
67  	}
68  
69  	public synchronized void setScript( String scriptText )
70  	{
71  		if( scriptText != null && scriptText.equals( this.scriptText ) )
72  			return;
73  
74  		this.scriptText = scriptText;
75  	}
76  
77  	public void compile() throws Exception
78  	{
79  	}
80  
81  	public void setVariable( String name, Object value )
82  	{
83  		properties.put( name, value );
84  	}
85  
86  	public void clearVariables()
87  	{
88  		properties.clear();
89  	}
90  
91  	public void release()
92  	{
93  		clearVariables();
94  	}
95  }