Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

@Override
public void creditCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest)
        throws BankingException {
    Session printBeanSession = itsSessionFactory.openSession();
    SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession
            .getSessionFactory();//from  w  w w  .  j ava 2 s  .c om
    ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
    Map<String, Object> params = new HashMap<String, Object>();
    Connection connection = null;
    Rxaddress address = null;
    try {
        itsLogger.info("Testing:--->" + theRequest.getParameter("moTransactionID"));

        ServletOutputStream out = theResponse.getOutputStream();
        String fileName = theRequest.getParameter("fileName");
        theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        theResponse.setContentType("application/pdf");
        connection = connectionProvider.getConnection();
        String path_JRXML = theRequest.getSession().getServletContext()
                .getRealPath("/resources/jasper_reports/CreditPayment.jrxml");
        JasperReport report = JasperCompileManager.compileReport(path_JRXML);
        JasperPrint print = JasperFillManager.fillReport(report, params, connection);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(print, baos);
        out.write(baos.toByteArray());
        out.flush();
        out.close();
    } catch (Exception e) {
        itsLogger.error(e.getMessage(), e);
        BankingException aBankingException = new BankingException(e.getMessage(), e);
        //   throw aBankingException;
    } finally {
        try {
            if (connectionProvider != null) {
                connectionProvider.closeConnection(connection);
                connectionProvider = null;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        printBeanSession.flush();
        printBeanSession.close();
    }
}

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

/**
 * writes the zip file to browser//from  ww w  . j  a  v a2s . c o m
 * 
 * @param file
 *            - zip file to download
 * @throws Exception
 */
private void download(File file) throws Exception {
    FileInputStream fis = null;
    ServletOutputStream out = null;
    try {
        String disposition = "attachment; filename=\"" + file.getName() + "\"";
        fis = new FileInputStream(file);

        response.setContentType("application/zip"); // application/zip
        response.addHeader("Content-Disposition", disposition);

        out = response.getOutputStream();

        int len;
        byte buf[] = new byte[102400];
        while ((len = fis.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        out.flush();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e1) {
        }

        try {
            if (fis != null)
                fis.close();
        } catch (IOException e2) {
        }
    }
}

From source file:org.apache.ranger.biz.ServiceDBStore.java

public void getPoliciesInCSV(List<RangerPolicy> policies, HttpServletResponse response) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceDBStore.getPoliciesInCSV()");
    }/*ww w. jav a2  s  . c o  m*/
    InputStream in = null;
    ServletOutputStream out = null;
    String CSVFileName = null;
    try {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        CSVFileName = "Ranger_Policies_" + timeStamp + ".csv";
        out = response.getOutputStream();
        StringBuffer sb = writeCSV(policies, CSVFileName, response);
        in = new ByteArrayInputStream(sb.toString().getBytes());
        byte[] outputByte = new byte[sb.length()];
        while (in.read(outputByte, 0, sb.length()) != -1) {
            out.write(outputByte, 0, sb.length());
        }
    } catch (Exception e) {
        LOG.error("Error while generating report file " + CSVFileName, e);
        e.printStackTrace();

    } finally {
        try {
            if (in != null) {
                in.close();
                in = null;
            }
        } catch (Exception ex) {
        }
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (Exception ex) {
        }
    }
}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

@Override
public void printCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest)
        throws BankingException {
    Session printBeanSession = itsSessionFactory.openSession();
    SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession
            .getSessionFactory();/*  ww  w  .  j a  v a  2 s  . c om*/
    ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
    Map<String, Object> params = new HashMap<String, Object>();
    //Rxaddress address = null;
    Connection connection = null;
    InputStream imageStream = null;
    try {
        Integer addressID = rxAddressID[0];
        //address = (Rxaddress)printBeanSession.get(Rxaddress.class,addressID);
        params.put("Name", "");
        params.put("Address2", "");
        params.put("Address3", "");
        itsLogger.info(billId.length);
        String count = billId.length + "";
        params.put("BillCount", count);
        params.put("CheckDate", checkDate);

        TsUserSetting objtsusersettings = (TsUserSetting) printBeanSession.get(TsUserSetting.class, 1);
        Blob blob = objtsusersettings.getCompanyLogo();
        imageStream = blob.getBinaryStream();
        //params.put("companyLogo", imageStream);

        itsLogger.info("Check Date: " + checkDate);
        ServletOutputStream out = theResponse.getOutputStream();
        String fileName = theRequest.getParameter("fileName");
        theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        theResponse.setContentType("application/pdf");
        connection = connectionProvider.getConnection();
        String path_JRXML = theRequest.getSession().getServletContext()
                .getRealPath("/resources/jasper_reports/PrintChecksfinal.jrxml");
        //String path_JRXML = theRequest.getSession().getServletContext().getRealPath("/resources/jasper_reports/CheckMICR.jrxml");
        JasperReport report = JasperCompileManager.compileReport(path_JRXML);
        JasperPrint print = JasperFillManager.fillReport(report, params, connection);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(print, baos);
        out.write(baos.toByteArray());
        out.flush();
        out.close();
    } catch (Exception e) {
        itsLogger.error(e.getMessage(), e);
        BankingException aBankingException = new BankingException(e.getMessage(), e);
    } finally {
        try {
            if (imageStream != null) {
                imageStream.close();
            }
            if (connectionProvider != null) {
                connectionProvider.closeConnection(connection);
                connectionProvider = null;
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        printBeanSession.flush();
        printBeanSession.close();

    }
}

From source file:com.topsec.tsm.sim.report.web.ReportController.java

/**
 *  // ww  w . java2s  .com
 * @param sid ?
 */
@RequestMapping("expMstReport")
public void expMstReport(SID sid, HttpServletRequest request, HttpServletResponse response,
        HttpSession session) {
    long start = System.currentTimeMillis();
    ReportBean bean = new ReportBean();
    bean = ReportUiUtil.tidyFormBean(bean, request);
    ExpStruct exp = new ExpStruct();
    exp.setMstrptid(bean.getMstrptid());
    exp.setDvc(bean.getDvcaddress());
    exp.setRptTimeS(bean.getTalStartTime());
    exp.setRptTimeE(bean.getTalEndTime());
    exp.setTop(bean.getTalTop());
    String viewItem = StringUtil.toString(request.getParameter("viewItem"), "");
    bean.setViewItem(viewItem);
    // ?
    if (bean.getViewItem().indexOf("2") < 0) {
        exp.setRptType(ReportUiConfig.rptDirection);
        String[] time = ReportUiUtil.getExpTime("month");
        exp.setRptTimeS(time[0]);
        exp.setRptTimeE(time[1]);
    } else {
        exp.setRptType(ReportUiUtil.rptTypeByTime(bean.getTalStartTime(), bean.getTalEndTime()));
    }

    if (sid == null) {
        exp.setRptUser("System");
    } else {
        exp.setRptUser(sid.getUserName());
    }
    String expType = request.getParameter("exprpt");
    if (expType.equals("pdf")) {
        response.setContentType("application/pdf");
    } else if (expType.equals("rtf")) {
        response.setContentType("application/msword");
    } else if (expType.equals("excel")) {
        response.setContentType("application/vnd.ms-excel");
    } else if (expType.equals("doc")) {
        response.setContentType("application/msword");
    } else if (expType.equals("docx")) {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    } else if (expType.equals("html")) {
        response.setContentType("application/x-javascript;charset=utf-8");
    }
    exp.setFileType(expType);
    javax.servlet.ServletOutputStream out = null;
    ExpMstRpt expMst = new ExpMstRpt();
    try {
        SID.setCurrentUser(sid);
        long time1 = System.currentTimeMillis();
        RptMasterTbService rptMasterTbImp = (RptMasterTbService) SpringContextServlet.springCtx
                .getBean(ReportUiConfig.MstBean);
        LinkedHashMap<String, List> expmap = ReportModel.expMstReport(rptMasterTbImp, exp, request);
        long time2 = System.currentTimeMillis();
        String title = exp.getRptName();
        //response.setCharacterEncoding("UTF-8");

        String filePath = null;
        String htmlName = null;
        String zipFileName = null;
        String tempName = null;
        if (expType.equalsIgnoreCase("html")) {
            StringBuffer html = new StringBuffer();
            exp.setHtml(html);
            filePath = ReportUiUtil.getSysPath();
            filePath = filePath.substring(0, filePath.length() - 16) + "htmlExp/";
            ExpMstRpt.setFliePath(filePath + "exphtml/" + "html/");
            HtmlAndFileUtil.createPath(filePath);
            HtmlAndFileUtil.clearPath(filePath);
            HtmlAndFileUtil.createPath(filePath + "exphtml/" + "html/");
            tempName = StringUtil.currentDateToString("yyyyMMddHHmmss");
            htmlName = tempName + ".htm";
            zipFileName = title + tempName + ReportUiUtil.getFileSuffix(expType);
        }
        List<JasperPrint> jasperPrintList = expMst.creMstRpt(expmap, request, exp);
        long time3 = System.currentTimeMillis();

        System.out.println((time1 - start) + "  " + (time2 - time1) + "  " + (time3 - time2));

        JRAbstractExporter exporter = ReportUiUtil.getJRExporter(exp.getFileType());
        exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList);

        if (expType.equalsIgnoreCase("html")) {
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8") + tempName
                            + ReportUiUtil.getFileSuffix(expType));
        } else {
            String userAgent = request.getHeader("User-Agent");
            String fileName = null;
            if (userAgent.indexOf("Firefox") > 0) {
                fileName = java.net.URLEncoder.encode(title, "UTF-8")
                        + StringUtil.currentDateToString("yyyyMMddHHmmss")
                        + ReportUiUtil.getFileSuffix(expType);
                response.setHeader("Content-Disposition", "attachment; filename*=\"utf8' '" + fileName + "\"");
            } else {
                fileName = java.net.URLEncoder.encode(title, "UTF-8")
                        + StringUtil.currentDateToString("yyyyMMddHHmmss")
                        + ReportUiUtil.getFileSuffix(expType);
                response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            }
        }
        out = response.getOutputStream();
        if (expType.equals("excel")) {
            exporter.setParameter(JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
            exporter.setParameter(JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.FALSE);
            exporter.setParameter(JExcelApiExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);
        } else if (expType.equals("pdf")) {
            exporter.setParameter(JRPdfExporterParameter.FORCE_LINEBREAK_POLICY, Boolean.TRUE);// 
        } else if (expType.equals("docx")) {

        }
        if (!expType.equalsIgnoreCase("html")) {
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
            exporter.exportReport();
            out.flush();
        } else {
            String html = exp.getHtml().toString();
            HtmlAndFileUtil.writeContent(HtmlAndFileUtil.createFile(filePath + "exphtml/" + "html/" + htmlName),
                    html);
            HtmlAndFileUtil.compressFloderChangeToZip(filePath + "exphtml/", filePath, zipFileName);
            HtmlAndFileUtil.outzipFile(filePath + zipFileName, out);
        }

    } catch (Exception e) {
        logger.error(":", e);
    } finally {
        clearTmpImage(expMst);
        ObjectUtils.close(out);
        SID.removeCurrentUser();
    }
}

From source file:org.exist.security.realm.openid.AuthenticatorOpenIdServlet.java

public String authRequest(String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
        throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
        ServletOutputStream out = httpResp.getOutputStream();
        httpResp.setContentType("text/html; charset=\"UTF-8\"");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        out.print("<html><head>");
        out.print("<title>OpenIDServlet Error</title>");
        out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
        out.print("<body><div id=\"container\"><h1>Error found</h1>");

        out.print("<h2>Message:");
        out.print("OpenID realm wasn't initialized.");
        out.print("</h2>");

        //out.print(HTTPUtils.printStackTraceHTML(t));

        out.print("</div></body></html>");
        return null;
    }//from ww w  .j  a  va2  s.c o m
    try {
        String returnAfterAuthentication = httpReq.getParameter("return_to");

        // configure the return_to URL where your application will receive
        // the authentication responses from the OpenID provider
        String returnToUrl = httpReq.getRequestURL().toString() + "?is_return=true&exist_return="
                + returnAfterAuthentication;

        // perform discovery on the user-supplied identifier
        List<?> discoveries = manager.discover(userSuppliedString);

        // attempt to associate with the OpenID provider
        // and retrieve one service endpoint for authentication
        DiscoveryInformation discovered = manager.associate(discoveries);

        // store the discovery information in the user's session
        httpReq.getSession().setAttribute("openid-disc", discovered);

        // obtain a AuthRequest message to be sent to the OpenID provider
        AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

        if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
            SRegRequest sregReq = SRegRequest.createFetchRequest();

            sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

            authReq.addExtension(sregReq);
        } else {

            FetchRequest fetch = FetchRequest.createFetchRequest();

            fetch.addAttribute(AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

            // wants up to three email addresses
            fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

            authReq.addExtension(fetch);
        }

        if (!discovered.isVersion2()) {
            // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
            // The only method supported in OpenID 1.x
            // redirect-URL usually limited ~2048 bytes
            httpResp.sendRedirect(authReq.getDestinationUrl(true));
            return null;

        } else {
            // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

            Object OPEndpoint = authReq.getDestinationUrl(false);

            ServletOutputStream out = httpResp.getOutputStream();

            httpResp.setContentType("text/html; charset=UTF-8");
            httpResp.addHeader("pragma", "no-cache");
            httpResp.addHeader("Cache-Control", "no-cache");

            out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            out.println("<head>");
            out.println("    <title>OpenID HTML FORM Redirection</title>");
            out.println("</head>");
            out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
            out.println("    <form name=\"openid-form-redirection\" action=\"" + OPEndpoint
                    + "\" method=\"post\" accept-charset=\"utf-8\">");

            Map<String, String> parameterMap = authReq.getParameterMap();
            for (Entry<String, String> entry : parameterMap.entrySet()) {
                out.println("   <input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\""
                        + entry.getValue() + "\"/>");
            }

            out.println("        <button type=\"submit\">Continue...</button>");
            out.println("    </form>");
            out.println("</body>");
            out.println("</html>");

            out.flush();
        }
    } catch (OpenIDException e) {
        // present error to the user
        LOG.debug("OpenIDException", e);

        ServletOutputStream out = httpResp.getOutputStream();
        httpResp.setContentType("text/html; charset=\"UTF-8\"");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        out.print("<html><head>");
        out.print("<title>OpenIDServlet Error</title>");
        out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
        out.print("<body><div id=\"container\"><h1>Error found</h1>");

        out.print("<h2>Message:");
        out.print(e.getMessage());
        out.print("</h2>");

        Throwable t = e.getCause();
        if (t != null) {
            // t can be null
            out.print(HTTPUtils.printStackTraceHTML(t));
        }

        out.print("</div></body></html>");
    }

    return null;
}

From source file:com.seer.datacruncher.profiler.spring.ProfilerInfoUpdateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();//  www  .j  a  va2 s .  com

    @SuppressWarnings("unchecked")
    Hashtable<String, String> dbParams = (Hashtable<String, String>) request.getSession(true)
            .getAttribute("dbConnectionData");
    if (dbParams != null) {
        request.setAttribute("serverName", CommonUtil.notNullValue(dbParams.get("Database_DSN")));
    }
    String selectedValue = CommonUtil.notNullValue(request.getParameter("selectedValue"));

    request.setAttribute("selectedValue", selectedValue);
    String tableName = CommonUtil.notNullValue(request.getParameter("parent"));

    request.setAttribute("parentValue", tableName);

    ObjectMapper mapper = new ObjectMapper();

    Vector vector = RdbmsConnection.getTable();

    int i = vector.indexOf(tableName);

    Vector avector[] = (Vector[]) null;
    avector = TableMetaInfo.populateTable(5, i, i + 1, avector);

    QueryDialog querydialog = new QueryDialog(1, tableName, avector);
    try {
        querydialog.executeAction("");
    } catch (Exception e) {
        e.printStackTrace();
    }

    String strColumnName = "";

    List<String> listPrimaryKeys = new ArrayList<String>();
    Map<String, Integer> mapColumnNames = new HashMap<String, Integer>();

    try {

        RdbmsConnection.openConn();
        DatabaseMetaData dbmd = RdbmsConnection.getMetaData();

        ResultSet resultset = dbmd.getPrimaryKeys(null, null, tableName);
        while (resultset.next()) {
            listPrimaryKeys.add(resultset.getString("COLUMN_NAME"));
        }

        resultset = dbmd.getColumns(null, null, tableName, null);

        while (resultset.next()) {
            strColumnName = resultset.getString(4);
            mapColumnNames.put(strColumnName, resultset.getInt(5));
        }

        RdbmsConnection.closeConn();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    Map<String, Integer> mapPrimaryKeys = new HashMap<String, Integer>();

    if (strColumnName.trim().length() > 0) {
        try {
            JSONArray array = new JSONArray(request.getParameter("data"));

            for (int count = 0; count < array.length(); count++) {
                JSONObject jsonObject = new JSONObject(array.get(count).toString());

                StringBuilder queryString = new StringBuilder();
                Iterator<String> keyIterator = jsonObject.keys();

                while (keyIterator.hasNext()) {
                    String strKey = keyIterator.next();

                    if (listPrimaryKeys.contains(strKey)) {
                        mapPrimaryKeys.put(strKey,
                                ((int) Double.parseDouble(jsonObject.get(strKey).toString())));
                        continue;
                    }
                    if (jsonObject.get(strKey) != null) {

                        if (mapColumnNames.get(strKey) == 4 || mapColumnNames.get(strKey) == 5
                                || mapColumnNames.get(strKey) == -6) {
                            queryString.append(
                                    strKey + "=" + Integer.parseInt(jsonObject.get(strKey).toString()) + ",");
                        } else if (mapColumnNames.get(strKey) == 2 || mapColumnNames.get(strKey) == 3
                                || mapColumnNames.get(strKey) == 7 || mapColumnNames.get(strKey) == 6
                                || mapColumnNames.get(strKey) == -5) {
                            queryString.append(strKey + "=" + jsonObject.get(strKey) + ",");
                        } else if (mapColumnNames.get(strKey) == 91 || mapColumnNames.get(strKey) == 92
                                || mapColumnNames.get(strKey) == 93) {
                            queryString.append(strKey + "=" + jsonObject.get(strKey) + ",");
                        } else if (mapColumnNames.get(strKey) == -7 || mapColumnNames.get(strKey) == 16
                                || mapColumnNames.get(strKey) == -3 || mapColumnNames.get(strKey) == -4) {
                            queryString.append(strKey + "=" + jsonObject.get(strKey) + ",");
                        } else if (mapColumnNames.get(strKey) == -1 || mapColumnNames.get(strKey) == 1
                                || mapColumnNames.get(strKey) == 12) {
                            queryString.append(strKey + "=\"" + jsonObject.get(strKey) + "\",");
                        }
                    }
                }
                StringBuilder whereClause = new StringBuilder(" where ");

                for (String primaryKey : listPrimaryKeys) {
                    whereClause.append(primaryKey + "=" + mapPrimaryKeys.get(primaryKey).intValue());
                    whereClause.append(" and ");
                }
                String strWhereClause = whereClause.toString();
                strWhereClause = strWhereClause.substring(0, strWhereClause.lastIndexOf("and"));

                queryString = new StringBuilder("UPDATE " + tableName + " SET ")
                        .append(queryString.toString().substring(0, queryString.toString().length() - 1));
                queryString.append(strWhereClause);

                RdbmsConnection.openConn();
                RdbmsConnection.executeUpdate(queryString.toString());
                RdbmsConnection.closeConn();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    Update update = new Update();
    update.setSuccess(true);

    GridUtil gridUtil = new GridUtil();
    gridUtil.generateGridData(querydialog.getTableGridDTO(), false, null);
    update.setResults(gridUtil.getData());

    out.write(mapper.writeValueAsBytes(update));
    out.flush();
    out.close();

    return null;
}

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

/**
 * Auto generated method comment/*from ww  w.  j a v a 2  s . c  o m*/
 * 
 * @param request
 * @param response
 * @param res
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response, List<Integer> res,
        String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;

    try {
        SimpleDateFormat sdf = Context.getDateFormat();
        outputStream = response.getOutputStream();
        ObsService os = Context.getObsService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        // header
        outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report", null) + ", : " + title);
        outputStream.println();
        if (request.getParameter("reason") != null
                && request.getParameter("reason").trim().compareTo("") != 0) {
            Integer conceptId = Integer.parseInt(request.getParameter("reason"));
            outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report.reasonofexit", null)
                    + ", : " + TransferOutInPatientTag.getConceptNameById("" + conceptId));
            // outputStream.println();
        }

        if (request.getParameter("location") != null
                && request.getParameter("location").trim().compareTo("") != 0) {
            Integer locationId = Integer.parseInt(request.getParameter("location"));
            outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report.location", null) + ", : "
                    + Context.getLocationService().getLocation(locationId).getName());
            outputStream.println();
        }
        outputStream.println("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdon", null)
                + ", : " + sdf.format(new Date()));// Report date
        outputStream.println("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdby", null)
                + ", : " + Context.getAuthenticatedUser().getPersonName());// Report

        outputStream.println(
                MohTracUtil.getMessage("tracpatienttransfer.report.numberofpatient", null) + ", " + res.size());
        outputStream.println();

        boolean hasRoleToViewPatientsNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

        // column header
        outputStream
                .println(MohTracUtil.getMessage("tracpatienttransfer.general.number", null) + ", "
                        + TransferOutInPatientTag
                                .getIdentifierTypeNameById(
                                        "" + TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
                        + ", "
                        + TransferOutInPatientTag.getIdentifierTypeNameById(""
                                + TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                        + ", "
                        + ((hasRoleToViewPatientsNames)
                                ? MohTracUtil.getMessage("tracpatienttransfer.general.names", null) + ", "
                                : "")
                        + MohTracUtil.getMessage("tracpatienttransfer.general.reasonofexit", null) + ", "
                        + MohTracUtil.getMessage("tracpatienttransfer.general.exitwhen", null)
                        + " ?(dd/MM/yyyy), "
                        // + MohTracUtil.getMessage("Encounter.provider", null)
                        // + ", "
                        + MohTracUtil.getMessage("Encounter.location", null) + "");
        outputStream.println();

        int ids = 0;

        log.info(">>>>>>>>>>>>>> Trying to create a CSV file...");

        for (Integer obsId : res) {
            // log.info(">>>>>>>>>>>>>> Trying to load obs#" + obsId);
            Obs obs = os.getObs(obsId);
            // log.info("----------------------------> It's ok for getObs");
            Integer patientId = obs.getPersonId();
            // log.info("----------------------------> It's ok for patientId");
            ids += 1;

            outputStream.println(ids + ","
                    + TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                            TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
                    + ","
                    + TransferOutInPatientTag
                            .personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                                    TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    + ","
                    + ((hasRoleToViewPatientsNames) ? TransferOutInPatientTag
                            .getPersonNames(patientId) + "," : "")
                    + TransferOutInPatientTag.conceptValueByObs(obs) + ""
                    + ((obs.getValueCoded().getConceptId()
                            .intValue() == TransferOutInPatientConstant.PATIENT_TRANSFERED_OUT)
                                    ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                            TransferOutInPatientConstant.TRANSFER_OUT_TO_A_LOCATION) + ")"
                                    : (obs.getValueCoded().getConceptId()
                                            .intValue() == TransferOutInPatientConstant.PATIENT_DEAD) ? " ("
                                                    + TransferOutInPatientTag.getObservationValueFromEncounter(
                                                            obs, TransferOutInPatientConstant.CAUSE_OF_DEATH)
                                                    + ")" : "")
                    + "," + new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(obs.getObsDatetime()) // + "," +
                    // TransferOutInPatientTag.getProviderByObs(obs)
                    + "," + obs.getLocation().getName() // + ","
            // + TransferOutInPatientTag.obsVoidedReason(obs)
            );
            log.info("----------------------------> It's ok for outputstream");
        }

        outputStream.flush();
        log.info(">>>>>>>>>>>>>> A CSV file was created successfully.");
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

From source file:org.joget.apps.app.controller.ConsoleWebController.java

@RequestMapping("/console/app/(*:appId)/(~:version)/message/generatepo/download")
public void consoleAppMessageGeneratePODownload(HttpServletResponse response,
        @RequestParam(value = "appId") String appId,
        @RequestParam(value = "version", required = false) String version,
        @RequestParam(value = "locale", required = false) String locale) throws IOException {
    ServletOutputStream output = null;
    try {/*from w  ww .jav  a2 s .co  m*/
        // verify app
        AppDefinition appDef = appService.getAppDefinition(appId, version);
        if (appDef == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // validate locale input
        SecurityUtil.validateStringInput(locale);

        // determine output filename
        String filename = appDef.getId() + "_" + appDef.getVersion() + "_" + locale + ".po";

        // set response headers
        response.setContentType("text/plain; charset=utf-8");
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);
        output = response.getOutputStream();

        appService.generatePO(appId, version, locale, output);
    } catch (Exception ex) {
        LogUtil.error(getClass().getName(), ex, "");
    } finally {
        if (output != null) {
            output.flush();
        }
    }
}