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;
14  
15  import java.io.File;
16  import java.io.IOException;
17  import java.lang.reflect.Method;
18  import java.net.URL;
19  import java.net.URLClassLoader;
20  
21  import com.eviware.soapui.SoapUI;
22  
23  public class ClasspathHacker
24  {
25  
26  	private static final Class<?>[] parameters = new Class[] { URL.class };
27  
28  	public static void addFile( String s ) throws IOException
29  	{
30  		File f = new File( s );
31  		addFile( f );
32  	}// end method
33  
34  	public static void addFile( File f ) throws IOException
35  	{
36  		addURL( f.toURI().toURL() );
37  	}// end method
38  
39  	public static void addURL( URL u ) throws IOException
40  	{
41  
42  		try
43  		{
44  			ClassLoader classLoader = SoapUI.class.getClassLoader();
45  			if( !( classLoader instanceof URLClassLoader ) )
46  			{
47  				SoapUI.log.error( "SoapUI classloader is not an URLClassLoader, failed to add external library" );
48  				return;
49  			}
50  
51  			URLClassLoader sysloader = ( URLClassLoader )classLoader;
52  			Class<URLClassLoader> sysclass = URLClassLoader.class;
53  			Method method = sysclass.getDeclaredMethod( "addURL", parameters );
54  			method.setAccessible( true );
55  			method.invoke( sysloader, new Object[] { u } );
56  
57  			SoapUI.log.info( "Added [" + u.toString() + "] to classpath" );
58  
59  		}
60  		catch( Throwable t )
61  		{
62  			SoapUI.logError( t );
63  			throw new IOException( "Error, could not add URL to system classloader" );
64  		}// end try catch
65  
66  	}// end method
67  
68  }// end class