Using Piranha Nano for Azure Functions

As Piranha Nano has been removed as an offering this content is no longer relevant

As I like to push boundaries I thought it would be nice to see if I can integrate a Servlet with Azure Functions.

Below is a simple HelloWorldServlet that illustrates it is indeed possible and actually very easy to do!

The code below is the 'Hello World' Servlet


public class HelloWorldServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        PrintWriter writer = response.getWriter();
        writer.println("Hello World");
        writer.flush();
    }
}
        

The code below is the Azure Function dispatching to the 'Hello World' Servlet

            
public class HelloWorldFunction {

    @FunctionName("/helloworld")
    public HttpResponseMessage run(
            @HttpTrigger(
                    name = "request",
                    methods = {HttpMethod.GET},
                    authLevel = AuthorizationLevel.FUNCTION
            ) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {

        NanoRequest nanoRequest = new NanoRequestBuilder()
                .method("GET")
                .servletPath("")
                .build();

        ByteArrayOutputStream nanoOutputStream = new ByteArrayOutputStream();
        NanoResponse nanoResponse = new NanoResponseBuilder()
                .outputStream(nanoOutputStream)
                .build();

        String body = null;

        try {
            NanoPiranha nanoPiranha = new NanoPiranhaBuilder()
                    .directoryResource("webapp")
                    .servlet("Function Servlet", new HelloWorldServlet())
                    .build();
            nanoPiranha.service(nanoRequest, nanoResponse);
        } catch (IOException | ServletException e) {
            body = e.getMessage();
        }

        if (body == null) {
            body = nanoOutputStream.toString();
        }

        return request.createResponseBuilder(HttpStatus.OK).
                body(body).
                build();
    }
}
        

As you can see this was all very easy to accomplish thanks to Piranha Nano.

A zip file that contains everything you need is available here

Posted February 16th, 2020

Up