Hi all.
package com.application.webapp;
import org.eclipse.jetty.rewrite.handler.CompactPathRule;
import org.eclipse.jetty.rewrite.handler.RewriteHandler;
import org.eclipse.jetty.server.AsyncRequestLogWriter;
import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import javax.naming.NamingException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
public class Main {
private URI uri;
public Main() {
try {
var host = Optional.ofNullable(System.getenv("WEB_HOST")).orElse("localhost");
var port = Optional.ofNullable(System.getenv("WEB_PORT")).orElse("8080");
this.setUri(host, Integer.parseInt(port));
} catch (URISyntaxException | NumberFormatException e) {
e.printStackTrace();
}
}
private void setUri(String host, int port) throws URISyntaxException {
this.uri = new URI("http", null, host, port, null, null, null);
}
public String toUrl() {
return this.uri.toString();
}
public Server setupServer() throws NamingException, NoSuchFieldException {
var server = new Server(new InetSocketAddress(this.uri.getHost(), this.uri.getPort()));
var ctx = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
var cfg = new ResourceConfig();
var container = new ServletContainer(cfg);
var holder = new ServletHolder(container);
var handler = new ResourceHandler();
var handlers = new HandlerList();
var logger = new CustomRequestLog(new AsyncRequestLogWriter(), CustomRequestLog.NCSA_FORMAT);
var rewrite = new RewriteHandler();
ctx.addServlet(holder, "/*");
cfg.packages("com.application.webapp.resources");
rewrite.addRule(new CompactPathRule());
server.setRequestLog(logger);
handlers.setHandlers(new Handler[]{handler, ctx, new DefaultHandler()});
server.setHandler(handlers);
return server;
}
public static void main(String[] args) throws NamingException, NoSuchFieldException {
final Server server;
Main m = new Main();
server = m.setupServer();
System.out.println(String.format("Jetty app started at %s", m.toUrl()));
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
} finally {
server.destroy();
}
}
}