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:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print a particular selected PO Quote as a PDF.
 *
 * @param mapping  An ActionMapping/*from  ww w . jav  a2s . c  o  m*/
 * @param form     An ActionForm -- The PO Quote must be selected here.
 * @param request  The HttpServletRequest
 * @param response The HttpServletResponse
 * @return An ActionForward
 * @throws Exception
 */
public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // String poDocId = request.getParameter("docId");
    // PurchaseOrderDocument po = (PurchaseOrderDocument)
    // SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId);
    // Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId"));
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
    PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    poVendorQuote.setTransmitPrintDisplayed(false);
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            poVendorQuote.setPdfDisplayedToUserOnce(false);

            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(OLEConstants.MAPPING_BASIC);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        // sbContentDispValue.append("inline");
        sbContentDispValue.append("attachment");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

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

/**
 * Auto generated method comment/*  www.j a  va 2  s.co  m*/
 * 
 * @param request
 * @param response
 * @param patientList
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportInfantsTestResumeToCSVFile(HttpServletRequest request, HttpServletResponse response,
        List<Object> patientList, String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        Patient p;
        Patient mother;
        PatientService ps = Context.getPatientService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title);
        outputStream.println("Number of Patients: " + patientList.size());
        outputStream.println();
        outputStream.println(
                "No. ,Identifier, Names, Mother's Names, Gender, Birthdate, Infant Feeding method, PCR Test Result, Ser. Test 9 months Result, Ser. Test 18 months Result");
        outputStream.println();

        int ids = 0;

        Encounter cpnEnc;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;

            p = ps.getPatient(Integer.parseInt(o[0].toString()));
            mother = pmtctTag.getChildMother(p.getPatientId());

            cpnEnc = pmtctTag.getCPNEncounterInfo(p.getPatientId());

            ids += 1;
            outputStream.println(ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + ","
                    + p.getPersonName() + "," + mother.getPersonName() + "," + p.getGender() + ","
                    + sdf.format(p.getBirthdate()) + ","
                    + pmtctTag.lastObsValueByConceptId(p.getPatientId(), PMTCTConstants.INFANT_FEEDING_METHOD)
                    + "," + pmtctTag.getConceptNameById("" + o[4]) + ","
                    + pmtctTag.getConceptNameById("" + o[5]) + "," + pmtctTag.getConceptNameById("" + o[6]));
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

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

/**
 * Auto generated method comment//from w ww.j a v  a 2s  . com
 * 
 * @param request
 * @param response
 * @param patientList
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportGeneralStatisticsInCPNToCSVFile(HttpServletRequest request, HttpServletResponse response,
        List<Object> patientList, String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        Patient p;
        PatientService ps = Context.getPatientService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title);
        outputStream.println("Number of Patients: " + patientList.size());
        outputStream.println();
        outputStream.println(
                "No. ,Identifier, Names, Gender, BirthDay, Enrollment Date, CPN Date, HIV Status, DPA, Date of Confiment");
        outputStream.println();

        int ids = 0;

        Encounter cpnEnc;
        Encounter matEnc;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;

            p = ps.getPatient(Integer.parseInt(o[1].toString()));
            cpnEnc = pmtctTag.getCPNEncounterInfo(p.getPatientId());
            matEnc = pmtctTag.getMaternityEncounterInfo(p.getPatientId());

            ids += 1;
            outputStream.println(ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + ","
                    + p.getPersonName() + "," + p.getGender() + "," + sdf.format(p.getBirthdate()) + ","
                    + o[4].toString() + "," + sdf.format(cpnEnc.getEncounterDatetime()) + ","
                    + pmtctTag.lastObsValueByConceptId(p.getPatientId(), PMTCTConstants.RESULT_OF_HIV_TEST)
                    + "," + pmtctTag.observationValueByConcept(cpnEnc, PMTCTConstants.PREGNANT_DUE_DATE) + ","
                    + pmtctTag.observationValueByConcept(matEnc, PMTCTConstants.DATE_OF_CONFINEMENT));
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

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

public void exportGeneralStatisticsInMaternityToCSVFile(HttpServletRequest request,
        HttpServletResponse response, List<Object> patientList, String filename, String title)
        throws Exception {
    ServletOutputStream outputStream = null;
    try {//  w  w w  . ja  va 2s.c  om
        outputStream = response.getOutputStream();
        Patient p;
        PatientService ps = Context.getPatientService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title);
        outputStream.println("Number of Patients: " + patientList.size());
        outputStream.println();
        outputStream.println(
                "No. ,Identifier, Names, Enrollment Date, DPA, Date of Confiment, HIV Status, Child Born Status");
        outputStream.println();

        int ids = 0;

        Encounter cpnEnc;
        Encounter matEnc;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;

            p = ps.getPatient(Integer.parseInt(o[0].toString()));
            cpnEnc = pmtctTag.getCPNEncounterInfo(p.getPatientId());
            matEnc = pmtctTag.getMaternityEncounterInfo(p.getPatientId());

            ids += 1;
            outputStream.println(ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + ","
                    + p.getPersonName() + "," + o[3].toString() + ","
                    + pmtctTag.observationValueByConcept(cpnEnc, PMTCTConstants.PREGNANT_DUE_DATE) + ","
                    + pmtctTag.observationValueByConcept(matEnc, PMTCTConstants.DATE_OF_CONFINEMENT) + ","
                    + pmtctTag.lastObsValueByConceptId(p.getPatientId(), PMTCTConstants.RESULT_OF_HIV_TEST)
                    + "," + pmtctTag.observationValueByConcept(matEnc,
                            PMTCTConfigurationUtils.getBornStatusConceptId()));
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Prints the PDF only, as opposed to <code>firstTransmitPrintPo</code>, which calls this method (indirectly) to print the PDF,
 * and calls the doc handler to display the PO tabbed page.
 *
 * @param mapping An ActionMapping//  w w w . jav  a2 s.  co  m
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPurchaseOrderPDFOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    String poDocId = request.getParameter("docId");
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        // will throw validation exception if errors occur
        SpringContext.getBean(PurchaseOrderService.class).performPrintPurchaseOrderPDFOnly(poDocId, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(poDocId);
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print the list of PO Quote requests./*w ww.  j av a 2 s  .co m*/
 *
 * @param mapping An ActionMapping
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPoQuoteListOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String poDocId = request.getParameter("docId");
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_LIST_");
        sbFilename.append(poDocId);
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class)
                .printPurchaseOrderQuoteRequestsListPDF(poDocId, baosPDF);

        if (!success) {
            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(KFSConstants.MAPPING_PORTAL);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
 * Retransmit Document page to be retransmitted, then display the PDF to the browser.
 *
 * @param mapping An ActionMapping//  www .j av  a2s  .c  o  m
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String selectedItemIndexes = request.getParameter("selectedItemIndexes");
    String documentNumber = request.getParameter("poDocumentNumberForRetransmit");
    PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class)
            .getPurchaseOrderByDocumentNumber(documentNumber);
    String retransmitHeader = request.getParameter("retransmitHeader");

    // setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
    // the po from the form

    setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
    po.setRetransmitHeader(retransmitHeader);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // below method will throw ValidationException if errors are found
        SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        sbContentDispValue.append("inline");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
        return mapping.findForward(KFSConstants.MAPPING_ERROR);
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print a particular selected PO Quote as a PDF.
 *
 * @param mapping An ActionMapping/*  w w w.  j ava  2  s.c o  m*/
 * @param form An ActionForm -- The PO Quote must be selected here.
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // String poDocId = request.getParameter("docId");
    // PurchaseOrderDocument po = (PurchaseOrderDocument)
    // SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId);
    // Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId"));
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
    PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    poVendorQuote.setTransmitPrintDisplayed(false);
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            poVendorQuote.setPdfDisplayedToUserOnce(false);

            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(KFSConstants.MAPPING_BASIC);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        // sbContentDispValue.append("inline");
        sbContentDispValue.append("attachment");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.betaconceptframework.astroboa.resourceapi.filter.BinaryChannelLoaderFilter.java

private void loadAndReturnContentOfBinaryChannel(String fileAccessInfo, HttpServletResponse httpServletResponse)
        throws IOException {

    BinaryChannelFileAccessInfoProcessor fileAccessInfoProcessor = new BinaryChannelFileAccessInfoProcessor(
            fileAccessInfo);//  w  w  w .  j a  va  2 s.  c o  m

    if (!fileAccessInfoProcessor.processFileAccessInfo()) {
        logger.warn("Invalid file access info " + fileAccessInfo);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        String repositoryId = fileAccessInfoProcessor.getRepositoryId();

        String fileName = fileAccessInfoProcessor.getFileName();

        String mimeType = fileAccessInfoProcessor.getMimeType();

        String width = fileAccessInfoProcessor.getWidth();

        String height = fileAccessInfoProcessor.getHeight();

        String contentDispositionType = fileAccessInfoProcessor.getContentDispositionType();

        String relativePathToStream = fileAccessInfoProcessor.getRelativePathToStream();

        //Check that repository home directory exists
        if (MapUtils.isEmpty(repositoryHomeDirectoriesPerRepositoryId) || StringUtils.isBlank(repositoryId)
                || !repositoryHomeDirectoriesPerRepositoryId.containsKey(repositoryId)) {
            logger.error("No available home directory exists for repository " + repositoryId);

            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            logger.debug("Ready to serve binary channel : path {}, mime-type: {}, filename :{}",
                    new Object[] { relativePathToStream, mimeType, fileName });

            File resource = null;
            try {
                //Load file
                resource = new File(repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator
                        + relativePathToStream);

                if (!resource.exists()) {
                    logger.warn("Could not locate resource "
                            + repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator
                            + relativePathToStream);
                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                } else {

                    //It may well be the case where filename and mime type are not provided
                    //in file access info (especially if binary channel is unmanaged).
                    //In this cases obtain filename and mime type from resource
                    if (StringUtils.isBlank(fileName)) {
                        fileName = resource.getName();
                    }

                    if (StringUtils.isBlank(mimeType)) {
                        mimeType = new MimetypesFileTypeMap().getContentType(resource);
                    }

                    ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

                    httpServletResponse.setDateHeader("Last-Modified", resource.lastModified());
                    httpServletResponse.setContentType(mimeType);

                    String processedFilename = org.betaconceptframework.utility.FilenameUtils
                            .convertFilenameGreekCharactersToEnglishAndReplaceInvalidCharacters(fileName);

                    //
                    byte[] resourceByteArray = FileUtils.readFileToByteArray(resource);

                    if (StringUtils.isNotBlank(mimeType) && mimeType.startsWith("image/")) {

                        resourceByteArray = resizeImageResource(resourceByteArray, mimeType, width, height);

                        httpServletResponse.setHeader("Content-Disposition",
                                contentDispositionType + ";filename=" + (width != null ? "W" + width : "")
                                        + (height != null ? "H" + height : "")
                                        + (width != null || height != null ? "-" : "") + processedFilename);

                    } else {
                        //Resource is not an image. Set charset encoding 
                        httpServletResponse.setCharacterEncoding("UTF-8");
                    }

                    if (!httpServletResponse.containsHeader("Content-Disposition")) {
                        httpServletResponse.setHeader("Content-Disposition",
                                contentDispositionType + ";filename=" + processedFilename);
                    }

                    httpServletResponse.setHeader("ETag",
                            ContentApiUtils.createETag(resource.lastModified(), resourceByteArray.length));
                    httpServletResponse.setContentLength(resourceByteArray.length);

                    try {
                        IOUtils.write(resourceByteArray, servletOutputStream);

                        servletOutputStream.flush();
                    } catch (Exception e) {
                        //Something went wrong while writing data to stream.
                        //Just log to debug and not to warn
                        logger.debug("", e);
                        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    }
                }
            } catch (Exception e) {
                logger.error("", e);
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
    }
}