Java tutorial
/* * 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.EPServiceProvider; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.JSONException; import org.json.JSONObject; /** * * @author brox */ @WebServlet(name = "Events", loadOnStartup = 2, urlPatterns = { "/events" }) public class Events extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(Events.class); EPServiceProvider epService; @Override public void init() { ServletContext sc = getServletContext(); epService = Utils.initEPService(sc); logger.debug("init at events servlet"); } @Override public void destroy() { Utils.destroyEPService(getServletContext()); logger.debug("destroy at events servlet"); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * 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 { logger.debug("events doPost"); PrintWriter out = response.getWriter(); try { response.setContentType("application/json;charset=UTF-8"); ServletInputStream sis = request.getInputStream(); byte[] b = new byte[request.getContentLength()]; sis.read(b, 0, b.length); sis.close(); String eventText = new String(b); logger.debug("event as text:" + eventText); org.json.JSONObject jo = new JSONObject(eventText); logger.debug("event as JSONObject: " + jo); Map<String, Object> otro = Utils.JSONObject2Map(jo); logger.debug("event as map: " + otro); epService.getEPRuntime().sendEvent(otro, "iotEvent"); logger.debug("event was sent: " + otro); } catch (JSONException je) { logger.debug("error: " + je.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.printf("{\"error\":\"%s\"}\n", je.getMessage()); } finally { out.close(); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Events server"; }// </editor-fold> }