Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:ro.cs.logaudit.web.servlet.ReportServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("doPost START");
    ServletOutputStream sos = null;
    StopWatch sw = new StopWatch();
    sw.start("Retrieve report");
    try {//from ww w . j av a 2s.  c  o m
        //create the bean containing the report parameters which will be passed to the Report Web Service Client
        AuditEventsReportParams reportParams = new AuditEventsReportParams();

        //Retrieve the start date param for the report request
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date startDate = sdf.parse(ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_START_DATE_PARAM), new ParsePosition(0));
        if (startDate != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_START_DATE_PARAM, startDate);
        }

        //Retrieve the end date param for the report request
        Date endDate = sdf.parse(ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_END_DATE_PARAM), new ParsePosition(0));
        if (endDate != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_END_DATE_PARAM, endDate);
        }

        //Retrieve the personId param for the report request
        String personId = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PERSON_ID_PARAM);
        if (personId != null && personId != "") {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PERSON_ID_PARAM,
                    Integer.valueOf(personId));
        }

        //Retrieve the message param for the report request
        String message = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MESSAGE_PARAM);
        if (message != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MESSAGE_PARAM, message);
        }

        //Retrieve the event param for the report request
        String event = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_EVENT_PARAM);
        if (event != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_EVENT_PARAM, event);
        }

        //Retrieve the moduleId param for the report request
        Integer moduleId = ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM);
        if (moduleId != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM, moduleId);
        }

        //Retrieve the reportTitle param for the report request
        String reportTitle = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PARAM_REPORT_TITLE);
        if (reportTitle != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PARAM_REPORT_TITLE,
                    reportTitle);
        }

        //Retrieve the orientation param for the report request
        String orientation = ServletRequestUtils.getRequiredStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORIENTATION_PARAM);
        if (orientation != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORIENTATION_PARAM,
                    orientation);
        }

        //Retrieve the report format param for the report request
        String format = ServletRequestUtils.getRequiredStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_FORMAT_PARAM);
        if (format != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_FORMAT_PARAM,
                    format.toLowerCase());
        }

        //Retrieve the organisationId param for the report request
        Integer organisationId = ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORGANISATION_ID_PARAM);
        if (organisationId != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORGANISATION_ID_PARAM,
                    organisationId);
        }

        reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_LOCALE_PARAM,
                request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME)
                        .toString().toLowerCase().substring(0, 2));

        //if the attachment param exists on the request, it means that the generated report must be a whole html page with head and body tags, 
        //otherwise the report must be embeddable in an existent html page(no head and body tags)
        if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_HTML_IS_EMBEDDABLE, false);
        } else {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_HTML_IS_EMBEDDABLE, true);
        }

        //Servlet's OutputStream
        sos = response.getOutputStream();

        //get the requested report
        DataHandler reportFileReceived = ReportsWebServiceClient.getInstance()
                .getAuditEventsReport(reportParams);

        //set the response content type
        if (format.toLowerCase().equals("html")) {
            response.setContentType("text/html");
            if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"".concat(reportTitle).concat(".html\""));
            } else {
                response.setHeader("Content-Disposition",
                        "inline; filename=\"".concat(reportTitle).concat(".html\""));
            }
        } else if (format.toLowerCase().equals("pdf")) {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition",
                    "inline; filename=\"".concat(reportTitle).concat(".pdf\""));
        } else if (format.toLowerCase().equals("doc")) {
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".doc\""));
        } else if (format.toLowerCase().equals("xls")) {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".xls\""));
        }

        //write the received report bytes stream to response output stream
        byte buffer[] = new byte[4096];
        BufferedInputStream bis = new BufferedInputStream(reportFileReceived.getInputStream());
        int size = 0;
        int i;
        while ((i = bis.read(buffer, 0, 4096)) != -1) {
            sos.write(buffer, 0, i);
            size += i;
        }

        if (size == 0) {
            response.setContentType("text/plain");
            sos.write("No content !".getBytes());
        }

        bis.close();
        response.setContentLength(size);

        logger.debug("**** report transfer completed !");
    } catch (Exception ex) {
        logger.error("", ex);
        response.setContentType("text/html");
        String exceptionCode = null;
        ;
        if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_OM_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITOM_REPORT_CREATE;
        } else if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_DM_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITDM_REPORT_CREATE;
        } else if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_CM_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITCM_REPORT_CREATE;
        } else if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_TS_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITTS_REPORT_CREATE;
        }
        response.getWriter().write("<html xmlns=\"http://www.w3.org/1999/xhtml\">"
                + "<head>   <script type=\"text/javascript\" src=\"js/cs/cs_common.js\"></script>"
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/style.css\"/> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/fonts-min.css\" /> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/container.css\" /> </head> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/button.css\" />"
                + "<body> <div id=\"errorsContainer\" class=\"errorMessagesDiv\"> "
                + "<table class=\"errorMessagesTable\">" + "<tr>" + "<td>" + "</td>" + "<td>"
                + "<div class=\"hd\">" + "<div id=\"closeErrors\" class=\"messagesCloseButon\"></div>"
                + "</div>" + "</td>" + "</tr>" + "<tr>" + "<td>" + "<div class=\"bd\">"
                + "<div style=\"width:470px\"> "
                + messageSource.getMessage(CREATE_ERROR,
                        new Object[] { exceptionCode, ControllerUtils.getInstance().getFormattedCurrentTime() },
                        (Locale) request.getSession()
                                .getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME))
                + "<br/> " + "</div>" + "</div>" + "</td>" + "<td>" + "</td>" + "</tr>" + "</table>"
                + "<div class=\"ft\">&nbsp;</div>" + "</div>" + "<script> "
                + "if(typeof(YAHOO.widget.Module) != \"undefined\") { "
                + "YAHOO.audit.errorsContainer = new YAHOO.widget.Module(\"errorsContainer\", {visible:true} ); "
                + "YAHOO.audit.errorsContainer.render() ;" + "YAHOO.audit.errorsContainer.show();"
                + "YAHOO.util.Event.addListener(\"closeErrors\", \"click\", function () {   "
                + "YAHOO.audit.errorsContainer.hide();" + "YAHOO.audit.errorsContainer.destroy(); "
                + "}, YAHOO.audit.errorsContainer, true);" + "}" + "</script> </body></html>");
        response.getWriter().flush();
    } finally {
        if (sos != null) {
            //Flushing and Closing OutputStream
            sos.flush();
            sos.close();
            logger.debug("**** servlet output stream closed.");
        }
    }
    logger.debug("doPost END");
    //list all the tasks performed
    logger.debug(sw.prettyPrint());
    sw.stop();
}

From source file:org.openmrs.module.vcttrac.util.FileExporter.java

/**
 * Auto generated method comment//  ww w  .jav  a  2s.c  o m
 * 
 * @param request
 * @param response
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVTracNetIndicators(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ServletOutputStream outputStream = null;
    //      DateFormat df = Context.getDateFormat();
    try {
        outputStream = response.getOutputStream();

        String title = VCTTracUtil.getMessage("vcttrac.tracnetIndicators", null);
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + title.trim().toLowerCase().replace(" ", "_") + ".csv" + "\"");
        outputStream.println(title);

        String location = request.getParameter("location");
        Date dateFrom = Context.getDateFormat().parse(request.getParameter("dateFrom"));
        Date dateTo = Context.getDateFormat().parse(request.getParameter("dateTo"));

        outputStream.println(VCTTracUtil.getMessage("Encounter.location", null) + " , "
                + ((location == null || location.compareTo("") == 0) ? ""
                        : Context.getLocationService().getLocation(Integer.valueOf(location)).getName()));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.from", null) + " , "
                + (new SimpleDateFormat("dd-MMM-yyyy").format(dateFrom)));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.to", null) + " , "
                + (new SimpleDateFormat("dd-MMM-yyyy").format(dateTo)));
        outputStream.println();
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.generatedby", null) + " , "
                + Context.getAuthenticatedUser().getPersonName());
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.generatedon", null) + " , "
                + new SimpleDateFormat("dd-MMM-yyyy").format(new Date()));
        outputStream.println();
        outputStream.println();

        Integer loc = Integer.parseInt(location);
        String from = request.getParameter("dateFrom");
        String to = request.getParameter("dateTo");

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.vct.indicators", null));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+");

        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsCounseledAndTestedForHiv", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 25, 0, "m"));
        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsTestedAndReceivedResults", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 25, 0, "m"));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria.numberOfHivPositiveClients", null)
                + ", " + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 0, 15, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 0, 15, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 15, 25, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 15, 25, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 25, 0, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 25, 0, "m"));

        outputStream.println();
        outputStream.println();

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.pit.indicators", null));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+");

        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsCounseledAndTestedForHiv", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 25, 0, "m"));
        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsTestedAndReceivedResults", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 25, 0, "m"));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria.numberOfHivPositiveClients", null)
                + ", " + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 0, 15, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 0, 15, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 15, 25, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 15, 25, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 25, 0, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 25, 0, "m"));

        outputStream.println();
        outputStream.println();

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.couple.indicators", null));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.counseled", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.tested", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.all", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.tested", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.oneoftwo", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.tested", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.none", null));
        //            +VCTTracUtil.getMessage("vcttrac.person.male", null)+" : "+VCTTracUtil.getMessage("vcttrac.age", null)+" 15-24, "
        //            +VCTTracUtil.getMessage("vcttrac.person.female", null)+" : "+VCTTracUtil.getMessage("vcttrac.age", null)+" 25+, "
        //            +VCTTracUtil.getMessage("vcttrac.person.male", null)+" : "+VCTTracUtil.getMessage("vcttrac.age", null)+" 25+");

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria.numberOfCouples", null) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseled(from, to, loc) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseledAndTested(from, to, loc, 2) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseledAndTested(from, to, loc, 1) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseledAndTested(from, to, loc, 0));

        outputStream.println();

        outputStream.flush();
    } catch (Exception e) {
        log.error(">>VCT>>Export>>in>>CSV>>Format>>Tracnet>>Indicators>> " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }

}

From source file:com.founder.fix.fixflow.FlowManager.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CurrentThread.init();//w w w  .  jav a2 s  .  c  o  m
    String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID));
    if (StringUtil.isEmpty(userId)) {
        String context = request.getContextPath();
        response.sendRedirect(context + "/");
        return;
    }
    ServletOutputStream out = null;
    String action = StringUtil.getString(request.getParameter("action"));
    if (StringUtil.isEmpty(action)) {
        action = StringUtil.getString(request.getAttribute("action"));
    }
    RequestDispatcher rd = null;
    try {
        Map<String, Object> filter = new HashMap<String, Object>();

        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload Uploader = new ServletFileUpload(new DiskFileItemFactory());
            // Uploader.setSizeMax("); // 
            Uploader.setHeaderEncoding("utf-8");
            List<FileItem> fileItems = Uploader.parseRequest(request);
            for (FileItem item : fileItems) {
                filter.put(item.getFieldName(), item);
                if (item.getFieldName().equals("action"))
                    action = item.getString();
                if (item.getFieldName().equals("deploymentId")) {
                    filter.put("deploymentId", item.getString());
                }
            }
        } else {
            Enumeration enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                Object tmp = enu.nextElement();
                Object obj = request.getParameter(StringUtil.getString(tmp));

                //               if (request.getAttribute("ISGET") != null)
                obj = new String(obj.toString().getBytes("ISO8859-1"), "utf-8");

                filter.put(StringUtil.getString(tmp), obj);
            }
        }

        Enumeration attenums = request.getAttributeNames();
        while (attenums.hasMoreElements()) {
            String paramName = (String) attenums.nextElement();
            Object paramValue = request.getAttribute(paramName);
            // ?map
            filter.put(paramName, paramValue);

        }
        filter.put("userId", userId);
        request.setAttribute("nowAction", action);
        if ("processDefinitionList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/processDefinitionList.jsp");
            Map<String, Object> result = getProcessDefinitionService().getProcessDefitionList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("processManageList")) {
            rd = request.getRequestDispatcher("/fixflow/manager/processInstanceList.jsp");
            Map<String, Object> result = getFlowManager().getProcessInstances(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("suspendProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().suspendProcessInstance(filter);
        } else if (action.equals("continueProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().continueProcessInstance(filter);

        } else if (action.equals("terminatProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().terminatProcessInstance(filter);
        } else if (action.equals("deleteProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().deleteProcessInstance(filter);
        } else if (action.equals("toProcessVariable")) {
            rd = request.getRequestDispatcher("/fixflow/manager/processVariableList.jsp");
            Map<String, Object> result = getFlowManager().getProcessVariables(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if (action.equals("saveProcessVariables")) {
            String tmp = (String) filter.get("insertAndUpdate");
            if (StringUtil.isNotEmpty(tmp)) {
                Map<String, Object> tMap = JSONUtil.parseJSON2Map(tmp);
                filter.put("insertAndUpdate", tMap);
            }
            getFlowManager().saveProcessVariables(filter);
            rd = request.getRequestDispatcher("/FlowManager?action=toProcessVariable");
        } else if (action.equals("processTokenList")) {
            Map<String, Object> result = getFlowManager().getProcessTokens(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            rd = request.getRequestDispatcher("/fixflow/manager/processTokenList.jsp");
        } else if (action.equals("taskInstanceList")) {
            rd = request.getRequestDispatcher("/fixflow/manager/taskInstanceList.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getTaskManager().getTaskList(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("doTaskSuspend")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().suspendTask(filter);
        } else if (action.equals("doTaskResume")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().resumeTask(filter);
        } else if (action.equals("doTaskTransfer")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().transferTask(filter);
        } else if (action.equals("doTaskRollBackNode")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().rollBackNode(filter);
        } else if (action.equals("doTaskRollBackTask")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().rollBackStep(filter);
        } else if (action.equals("flowLibrary")) {
            rd = request.getRequestDispatcher("/fixflow-explorer/flowLibrary.jsp");
        }
        //???deploymentId
        if ("deploy".equals(action)) {
            rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList");
            response.setContentType("text/html;charset=utf-8");
            getProcessDefinitionService().deployByZip(filter);
        } else if ("deleteDeploy".equals(action)) {
            rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList");
            getProcessDefinitionService().deleteDeploy(filter);
        } else if ("download".equals(action)) {
            String processDefinitionId = StringUtil.getString(filter.get("processDefinitionId"));
            response.reset();
            request.setCharacterEncoding("gbk");
            response.setContentType("applcation/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + processDefinitionId + ".zip");
            response.setHeader("Cache-Control",
                    "must-revalidate, post-check=0, pre-check=0,private, max-age=0");
            response.setHeader("Content-Type", "application/octet-stream");
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");

            ZipOutputStream outZip = new ZipOutputStream(response.getOutputStream());
            List<Map<String, Object>> fileList = getProcessDefinitionService().getResources(filter);
            for (Map<String, Object> file : fileList) {
                ZipEntry entry = new ZipEntry(file.get("FILENAME").toString());
                entry.setSize(((byte[]) file.get("BYTES")).length);
                outZip.putNextEntry(entry);
                outZip.write((byte[]) file.get("BYTES"));
                outZip.closeEntry();
            }
            outZip.close();
            outZip.flush();
            outZip.close();
        } else if ("getUserList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/userList.jsp");
            request.setAttribute("nowAction", "UserGroup");
            Map<String, Object> result = getUserGroupService().getAllUsers(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);

            List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter);
            request.setAttribute("groupList", groupList);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if ("getGroupList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/groupList.jsp");
            request.setAttribute("nowAction", "UserGroup");
            Map<String, Object> result = getUserGroupService().getAllGroup(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter);
            request.setAttribute("groupList", groupList);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if ("getUserInfo".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/userInfo.jsp");
            Map<String, Object> pageResult = getUserGroupService().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if ("getGroupInfo".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/groupInfo.jsp");
            Map<String, Object> pageResult = getUserGroupService().getGroupInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if ("getJobList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp");
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("viewJobInfo".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp");
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobTrigger(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("suspendJob".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp");
            request.setAttribute("nowAction", "jobManager");
            getJobService().suspendJob(filter);
            Map<String, Object> result = getJobService().getJobList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("continueJob".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp");
            getJobService().continueJob(filter);
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("suspendTrigger".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp");
            getJobService().suspendTrigger(filter);
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobTrigger(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("continueTrigger".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp");
            getJobService().continueTrigger(filter);
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobTrigger(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("setHis".equals(action)) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().setHistory(filter);
        } else if ("updateCache".equals(action)) {
            ProcessEngineManagement.getDefaultProcessEngine().cleanCache(true, true);
            response.getWriter().write("update success!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        request.setAttribute("errorMsg", e.getMessage());
        try {
            CurrentThread.rollBack();
        } catch (SQLException e1) {
            e1.printStackTrace();
            request.setAttribute("errorMsg", e.getMessage());
        }
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        try {
            CurrentThread.clear();
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", e.getMessage());
        }
    }
    if (rd != null)
        rd.forward(request, response);
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetPatientServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * //w w  w.  ja va 2 s.  co m
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@Override
public void exportDataToCsvFile(HttpServletRequest request, HttpServletResponse response,
        Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;
    for (String indicator : indicatorsList.keySet()) {
        count++;
        outputStream.println(
                count + " , " + indicator.toString() + " , " + indicatorsList.get(indicator).toString());
    }

    outputStream.flush();
    outputStream.close();
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * /*w w w . j a va  2s  .com*/
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@SuppressWarnings("unchecked")
@Override
public void exportDataToCsvFile(HttpServletRequest request, HttpServletResponse response,
        Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;

    List<String> indicator_msg = null;

    indicator_msg = (ArrayList<String>) request.getSession().getAttribute(request.getParameter("id") + "_msg");

    for (String indicator : indicatorsList.keySet()) {
        count++;
        outputStream.println(indicator.toString().substring(4) + " , " + indicator_msg.get(count - 1) + " , "
                + indicatorsList.get(indicator).toString());
    }

    outputStream.flush();
    outputStream.close();
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * //w w w .  j  a  va  2  s. c o m
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@Override
public void exportPatientsListToCsvFile(HttpServletRequest request, HttpServletResponse response,
        List<Person> patientsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    Session session = getSessionFactory().getCurrentSession();
    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;

    for (Person person : patientsList) {

        Date maxEncounterDateTime = (Date) session
                .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where patient_id = "
                        + person.getPersonId())
                .uniqueResult();

        Date maxReturnVisitDay = (Date) session
                .createSQLQuery("select cast(max(value_datetime) as DATE ) " + "from obs where concept_id = "
                        + ConstantValues.NEXT_SCHEDULED_VISIT + " and person_id = " + person.getPersonId())
                .uniqueResult();

        count++;
        outputStream.println(count + " , " + person.getPersonId() + " , " + person.getFamilyName() + " "
                + person.getGivenName() + " , " + person.getGender() + " , " + maxEncounterDateTime.toString()
                + " , " + maxReturnVisitDay.toString());
    }

    outputStream.flush();
    outputStream.close();
}