View Javadoc

1   /*
2    *  soapUI, copyright (C) 2004-2009 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;
14  
15  import java.util.Stack;
16  
17  import com.eviware.soapui.SoapUI;
18  import com.eviware.soapui.model.ModelItem;
19  
20  /***
21   * A pool of script engines
22   * 
23   * @author ole.matzura
24   */
25  
26  public class ScriptEnginePool
27  {
28  	private Stack<SoapUIScriptEngine> scriptEngines = new Stack<SoapUIScriptEngine>();
29  	private String script;
30  	private ModelItem modelItem;
31  	private int borrowed;
32  
33  	public ScriptEnginePool( ModelItem modelItem )
34  	{
35  		this.modelItem = modelItem;
36  	}
37  
38  	public void setScript( String script )
39  	{
40  		this.script = script;
41  	}
42  
43  	public void returnScriptEngine( SoapUIScriptEngine scriptEngine )
44  	{
45  		synchronized( this )
46  		{
47  			scriptEngines.push( scriptEngine );
48  			borrowed-- ;
49  		}
50  	}
51  
52  	public SoapUIScriptEngine getScriptEngine()
53  	{
54  		synchronized( this )
55  		{
56  			if( scriptEngines.isEmpty() )
57  				scriptEngines.push( SoapUIScriptEngineRegistry.create( modelItem ) );
58  
59  			SoapUIScriptEngine result = scriptEngines.pop();
60  			if( script != null )
61  				result.setScript( script );
62  
63  			borrowed++ ;
64  
65  			return result;
66  		}
67  	}
68  
69  	public void release()
70  	{
71  		int waitcount = 10;
72  
73  		while( borrowed > 0 && waitcount-- > 0 )
74  		{
75  			try
76  			{
77  				System.out.println( "Waiting for " + borrowed + " script engines" );
78  				Thread.sleep( 1000 );
79  			}
80  			catch( InterruptedException e )
81  			{
82  				SoapUI.logError( e );
83  			}
84  		}
85  
86  		for( SoapUIScriptEngine scriptEngine : scriptEngines )
87  		{
88  			scriptEngine.release();
89  		}
90  
91  		scriptEngines.clear();
92  
93  		if( borrowed > 0 )
94  			System.out.println( "Failed to release " + borrowed + " script engines" );
95  	}
96  }