GreatFire
GreatFire

Reputation: 437

Embed jetty in java app and export as jar

I'm making a java application which embeds a Jetty web server, which in turn serves content developed with Google Web Toolkit. It's all working fine when run in Eclipse, but when I export it as a jar file all I get is a Jetty error message saying "File not found".

The Jetty server is launched like this:

    WebAppContext handler = new WebAppContext();
    handler.setResourceBase("./war");
    handler.setDescriptor("./war/WEB-INF/web.xml");
    handler.setContextPath("/");
    handler.setParentLoaderPriority(true);
    server.setHandler(handler);

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I suspect that the problem is the relative paths used in handler.setResourceBase() and handler.setDescriptor(). I've googled and tested lots of solutions to this but so far to no avail. Particularly I've tried using something like getClass().getResource("./war").toExternalForm() but this just throws Null exceptions.

I also tried:

ProtectionDomain protectionDomain = Start.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();

but that only results in a Jetty serving a directory listing of the java classes.

Is there any way to do this?

Upvotes: 4

Views: 1890

Answers (3)

Den R
Den R

Reputation: 547

It looks like ClassLoader.getResource does not understand an empty string or . or / as an argument. In my jar file I had to move all stuf to WEB-INF. So the code looks like

   `contextHandler.setResourceBase(EmbeddedJetty.class.getClassLoader().getResource("WEB-INF").toExternalForm());` 

so the context looks like this then:

ContextHandler:744 - Started o.e.j.w.WebAppContext@48b3806{/,jar:file:/Users/xxx/projects/dropbox/ui/target/ui-1.0-SNAPSHOT.jar!/WEB-INF,AVAILABLE}

Upvotes: 0

ajk
ajk

Reputation: 1

I've posted a detailed description on how to do this here: http://h30499.www3.hp.com/t5/HP-Software-Developers-Blog/Embedding-Jetty-in-a-Java-Main-Application/ba-p/6107503

Upvotes: 0

mxro
mxro

Reputation: 6878

  1. Copy all files of the compiled GWT application into one of your Java packages. For instance:

    my.webapp.resources
      html/MyPage.html
      gwtmodule/gwtmodule.nocache.js
      ...
    

    (html, gwtmodule will become Java packages as well).

  2. Configure the embedded Jetty instance to serve these files.

     final String webDir = this.getClass().
           getClassLoader().getResource("my/webapp/resources").toExternalForm();
    
     final Context root = new Context(server, "/", Context.SESSIONS);
     root.setContextPath("/");
     root.setResourceBase(webDir);
     root.addServlet(MyGwtService.class, "/servlets/v01/gwtservice"); 
    

This approach works for me both when the application is run from eclipse as well as when it is deployed.

Upvotes: 1

Related Questions