Friday, July 8, 2011

URL Classloader

Recently I needed to supply a CXF WS client with a URL of the WSDL, but I needed to load it locally, from my classpath.  I found a nifty solution on Stackoverflow to load classpath resources with a URL:

public static class Handler extends URLStreamHandler {
     /** The classloader to find resources from. */
     private final ClassLoader classLoader;

     public Handler(ClassLoader classLoader) {
         this.classLoader = classLoader;
     }

     @Override
     protected URLConnection openConnection(URL u) throws IOException {
         final URL resourceUrl = classLoader.getResource(u.getPath());
         return resourceUrl.openConnection();
     }
 }

Then create the URL object and hand off to the CXF Proxy

url = new URL(null, "classpath:my.wsdl", new Handler(this.getClass().getClassLoader()));
MyService service = new MyService(url);

Credit goes to Stephen for this awesome trick:
http://stackoverflow.com/questions/861500/url-to-load-resources-from-the-classpath-in-java

No comments:

Post a Comment