Embedding Flux as a Servlet

The most common way users run Flux in an application server environment is to embed the engine in a servlet. Running Flux as a servlet allows you to easily integrate the engine into your application server environment and works well across all supported application servers.

Servlet Code

To run the engine in a servlet, you simply need:

  • an init() method to initialize the engine and its configuration
  • a destroy() method that shuts down Flux when the servlet shuts down

Typical code for running Flux in a servlet might look something like this:

import flux.Engine;
import flux.Factory;
import flux.Configuration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class Servlet extends HttpServlet {

    //   The Flux engine.
    private Engine flux;

    //   Starts Flux when your servlet is initialized.  
    public void init() throws ServletException {

        try {
            //      Start a Flux engine instance.//      First, create a factory.
            Factory fluxFactory = Factory.makeInstance();

            //      Create Configuration.
            Configuration config = new Configuration();

            //      Next, create a Flux instance.
            flux = fluxFactory.makeEngine(config);

            //      Finally, start the Flux engine.
            flux.start();
        } // try
        catch (Exception e) {
            throw new ServletException(e.getMessage());
        } // catch

        System.out.println("*** Flux has been started. ***");

    } // init()

    //  Shuts down Flux when your servlet is destroyed.
    public void destroy() {
        try {
            //      Stop Flux and release its resources.
            flux.dispose();
        } // try
        catch (Exception e) {
            e.printStackTrace();
        } // catch
    } // destroy()

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    } // doGet

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        PrintWriter out = response.getWriter();
        try {
            response.setContentType("text/plain");
            out.println("Flux has been started in this servlet\!");
        } // try
        catch (Exception e) {
            out.println("An error occured.");
            e.printStackTrace(out);
        } // catch
    } // doPost()
} // class Servlet

JBoss

You must disable RESTEasy in JBoss AS 7 as explained in https://issues.jboss.org/browse/JBAS-8830.

You may need to copy the flux.jar file to your JBoss deployment lib directory (for example: ‘/jboss-as-7.1.1.Final/jboss-as-7.1.1.Final/standalone/deployments/Flux.war/WEB-INF/lib’).