Deploying a Serverless WAR

The code below describes a wrapper class that can be used as a starting point to deploy a serverless WAR.



public class WarWrapper {

    /**
     * Process method.
     *
     * @param inputStream the (standard in) input stream.
     * @param outputStream the (standard out) output stream.
     */
    public void process(InputStream inputStream, PrintStream outputStream) {

        DefaultWebApplication webApp = new DefaultWebApplication();
        webApp.setClassLoader(new DefaultWebApplicationClassLoader(new File("./webapp")));
        webApp.addServlet("HelloWorld", "serverless.HelloWorldServlet");
        webApp.addServletMapping("HelloWorld", "/*");
        webApp.initialize();
        webApp.start();

        ByteBufferHttpServletRequest request = new ByteBufferHttpServletRequest();
        request.setWebApplication(webApp);
        request.setContextPath("");
        request.setServletPath("/helloWorld");

        ByteBufferHttpServletResponse response = new ByteBufferHttpServletResponse();
        ByteBufferServletOutputStream bufferedOutputStream = new ByteBufferServletOutputStream();
        response.setOutputStream(bufferedOutputStream);
        bufferedOutputStream.setResponse(response);

        try {
            webApp.service(request, response);
            response.flushBuffer();
            outputStream.write(bufferedOutputStream.getBytes());
            outputStream.flush();
        } catch (ServletException | IOException e) {
            e.printStackTrace(outputStream);
        }

        webApp.stop();
    }

    /**
     * Main method.
     *
     * @param arguments the arguments.
     */
    public static void main(String[] arguments) {
        WarWrapper wrapper = new WarWrapper();
        wrapper.process(System.in, System.out);
    }
}
        

The servlet below is part of the webapp Maven module.


public class HelloWorldServlet extends HttpServlet {
    
    /**
     * Process the request.
     *
     * @param request the request.
     * @param response the response.
     * @throws IOException when an I/O error occurs.
     * @throws ServletException when a Servlet error occurs.
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/plain");
        PrintWriter writer = response.getWriter();
        writer.println("Hello World");
    }
}
        

This makes it possible to run a WAR as a serverless function.

How do I run this example?

Build the project first, then go to the target directory of the bootstrapper JAR module and use the following commandline:


    java -jar serverlessJar-jar-with-dependencies.jar
        

Project resources

Download the entire project from here.

Posted December 16th, 2018

Up