Nov 8, 2008

GWT on Embedded Jetty

Goal:
  • A valid maven dependency to be used in other maven projects
In this jar should be
  • a) a webserver
  • b) all static content (e.g. the GWT-ompiled .js )
  • c) all dynamic content (e.g. the GWT servlets)
The building of the jar should be performed by Maven.

Sources considered:

Solution:
  • Jetty 6
  • A custom ClasspathHandler serving content from the classpath
  • A wrapper to do this setup
  • Clever structure of directories and the pom.xml
Too lazy to write down all details. :-)

2 comments:

  1. hi max... would you post a sample project? that would be greatly appreciated!

    ReplyDelete
  2. Hmm, my project layout and the GWT version change since then...

    I guess the central part is the ClasspathResourceHandler.

    Here is my code:

    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;

    import org.mortbay.jetty.handler.ResourceHandler;
    import org.mortbay.resource.Resource;
    import org.mortbay.util.URIUtil;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    public class ClasspathResourceHandler extends ResourceHandler {

    private static Logger log = LoggerFactory
    .getLogger(ClasspathResourceHandler.class);
    private String rootPath;

    /**
    * @param rootPath without leading or trailing slashes
    */
    public ClasspathResourceHandler(String rootPath) {
    this.rootPath = rootPath;
    }

    @Override
    public Resource getResource(String path) throws MalformedURLException {
    log.debug("GET '" + path + "' from classpath ...");

    if ((path == null) || (path.length() == 0) || !path.startsWith("/"))
    throw new MalformedURLException(path);

    String absolutePath = this.rootPath + path;
    log.debug("Absolute: " + absolutePath);

    String canonicalPath = URIUtil.canonicalPath(absolutePath);
    log.debug("Canonical: " + canonicalPath);

    // bite off leading '/'
    if (canonicalPath.startsWith("/")) {
    canonicalPath = canonicalPath.substring(1);
    }
    log.debug("Valid resource name syntax: " + canonicalPath);

    Resource resource = this.getResourceDirect(canonicalPath);
    if (resource == null) {
    log.warn("404 NOT FOUND for '" + canonicalPath + "'");
    } else {
    log.debug("200 OK for '" + canonicalPath + "'");
    }
    return resource;
    }

    private Resource getResourceDirect(String path) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource(path);
    if (url == null) {
    return null;
    }

    Resource resource;
    try {
    resource = Resource.newResource(url);
    } catch (IOException e) {
    throw new RuntimeException(e);
    }
    return resource;
    }

    }

    ReplyDelete