View Javadoc

    1   /*
    2    *  soapUI, copyright (C) 2004-2007 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( SoapUIScriptEngineRegistry.GROOVY_ID, modelItem ));
    58
    59  			SoapUIScriptEngine result = scriptEngines.pop();
    60  			result.setScript( script );
    61  			borrowed++;
    62
    63  			return result;
    64  		}
    65  	}
    66
    67  	public void release()
    68  	{
    69  		int waitcount = 10;
    70
    71  		while( borrowed > 0 && waitcount--  > 0 )
    72  		{
    73  			try
    74  			{
    75  				System.out.println( "Waiting for " + borrowed + " script engines" );
    76  				Thread.sleep( 1000 );
    77  			}
    78  			catch( InterruptedException e )
    79  			{
    80  				SoapUI.logError( e );
    81  			}
    82  		}
    83
    84  		for( SoapUIScriptEngine scriptEngine : scriptEngines )
    85  		{
    86  			scriptEngine.release();
    87  		}
    88
    89  		scriptEngines.clear();
    90
    91  		if( borrowed > 0 )
    92  			System.out.println( "Failed to release " + borrowed + " script engines" );
    93  	}
    94  }