es.tid.cep.esperanza.Rules.java Source code

Java tutorial

Introduction

Here is the source code for es.tid.cep.esperanza.Rules.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package es.tid.cep.esperanza;

import com.espertech.esper.client.EPAdministrator;
import com.espertech.esper.client.EPException;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author brox
 */
@WebServlet(name = "Rules", loadOnStartup = 1, urlPatterns = { "/rules/*" })
public class Rules extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(Rules.class);
    EPServiceProvider epService;

    @Override
    public void init() {
        ServletContext sc = getServletContext();
        epService = Utils.initEPService(sc);
        logger.debug("init at rules servlet");
        logger.debug("actionURL: " + Configuration.getActionURL());
        logger.debug("ruleCallbackURL: " + Configuration.getRuleCallbackURL());
    }

    @Override
    public void destroy() {
        Utils.destroyEPService(getServletContext());
        logger.debug("destroy at rules servlet");
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("application/json;charset=UTF-8");
        try {
            String ruleName = request.getPathInfo();
            ruleName = ruleName == null ? "" : ruleName.substring(1);
            logger.debug("rule asked for " + ruleName);
            EPAdministrator epa = epService.getEPAdministrator();

            if (ruleName.length() != 0) {
                EPStatement st = epa.getStatement(ruleName);
                if (st == null) {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    out.printf("{\"error\":\"%s not found\"}\n", ruleName);
                } else {
                    out.println(Utils.Statement2JSONObject(st));
                }
            } else {
                String[] sttmntNames = epa.getStatementNames();
                JSONArray ja = new JSONArray();
                for (String name : sttmntNames) {
                    logger.debug("getting rule " + name);
                    EPStatement st = epa.getStatement(name);
                    ja.put(Utils.Statement2JSONObject(st));
                }
                out.println(ja.toString());
            }

        } catch (EPException epe) {
            logger.error("getting statement", epe);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
        } finally {
            out.close();
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("application/json;charset=UTF-8");
        try {
            ServletInputStream sis = request.getInputStream();
            byte[] b = new byte[request.getContentLength()];
            sis.read(b, 0, b.length);
            String expression = new String(b);
            logger.debug("rule text: ", expression);
            EPStatement statement = epService.getEPAdministrator().createEPL(expression);
            logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
            statement.addListener(new GenericListener());
            out.println(Utils.Statement2JSONObject(statement));
        } catch (EPException epe) {
            logger.error("creating statement", epe);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
        } finally {
            out.close();
        }
    }

    /**
     * Handles the HTTP <code>DELETE</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("application/json;charset=UTF-8");
        try {
            String ruleName = request.getPathInfo();
            ruleName = ruleName == null ? "" : ruleName.substring(1);
            logger.debug("rule asked for " + ruleName);
            EPAdministrator epa = epService.getEPAdministrator();

            if (ruleName.length() != 0) {
                EPStatement st = epa.getStatement(ruleName);
                if (st == null) {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    out.printf("{\"error\":\"%s not found\"}\n", ruleName);
                } else {
                    st.destroy();
                    out.println(Utils.Statement2JSONObject(st));
                }
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.println("{\"error\":\"not rule specified for deleting\"}");
            }

        } catch (EPException epe) {
            logger.error("deleting statement", epe);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
        } finally {
            out.close();
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Rules servlet";
    }// </editor-fold>

}