Hamid Hamid - 4 months ago 26
Java Question

Jetty resource base different in Maven Nested Multi-module project of IntelliJ IDEA vs Eclipse

We have a nested multi-module project. Our developers are a mix of IntelliJ IDEA and Eclipse users.

When running a jetty server inside an inner module, it seems we need to set the resource base to different values depending on which IDE we are using.

For IntelliJ:

root.setResourceBase("myModule/src/main/webapp");


For Eclipse:

root.setResourceBase("src/main/webapp");


We don't want to have to tweak our IDEs to make it work, e.g. I don't want to have to change some setting in IntelliJ to make it work with the Eclipse version of the code.

Any ideas?

Answer

The short answer:

Your execution differences between Eclipse vs Intellij can be explained by having different PWD, or ${user.dir}, or working directory setups.

The better answer:

Don't use filesystem paths then.

Look up a known resource in that location via a Classloader.getResource() and then pass the parent directory into the root.setResourceBase()

Example:

    Server server = new Server(8080);

    // Figure out what path to serve content from
    ClassLoader cl = WebAppContextFromClasspath.class.getClassLoader();
    // We look for a file, as ClassLoader.getResource() is not
    // designed to look for directories (we resolve the directory later)
    URL f = cl.getResource("hello.html");
    if (f == null)
    {
        throw new RuntimeException("Unable to find resource directory");
    }

    // Resolve file to directory
    URI webRootUri = f.toURI().resolve("./").normalize();
    System.err.println("WebRoot is " + webRootUri);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(webRootUri.toASCIIString());
    webapp.setParentLoaderPriority(true);

    server.setHandler(webapp);

    server.start();
    server.join();

You can see this in the embedded-jetty-cookbook examples:

The other better answer:

Another approach is to find the src/main/webapp a few different ways depending on how it is being run

See the operational modes in the ServerMain.java in the embedded-jetty-live-war example.

Comments