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.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {/*  w  w w. jav a2 s  .  c  o m*/
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:be.fedict.eid.dss.webapp.DocumentViewerServlet.java

@Override
protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    LOG.debug("doGet");

    String resource = request.getParameter(RESOURCE_PARAM);
    if (null != resource) {

        // download/view request
        handleDownloadRequest(resource, request, response);
        return;//from  w  ww  .j  a  v  a2  s  .  c om
    }

    // get browser plugins
    List<String> plugins = BrowserInfoServlet.getPlugins(request.getSession());
    for (String plugin : plugins) {
        LOG.debug("Plugin: " + plugin);
    }

    // get browser mimeTypes
    List<MimeType> mimeTypes = BrowserInfoServlet.getMimeTypes(request.getSession());
    for (MimeType mimeType : mimeTypes) {
        LOG.debug("MimeTypes: type=" + mimeType.getType() + " plugin=" + mimeType.getPlugin());
    }

    HttpSession httpSession = request.getSession();
    DocumentRepository documentRepository = new DocumentRepository(httpSession);
    String contentType = documentRepository.getDocumentContentType();
    if (null == contentType) {
        response.setContentType("text/plain");
        PrintWriter printWriter = response.getWriter();
        printWriter.println("No document to be signed.");
        return;
    }

    byte[] documentData = documentRepository.getDocument();

    DSSDocumentService documentService = super.findDocumentService(contentType);
    if (null != documentService) {
        LOG.debug("document visualization transformation");
        String language = (String) httpSession.getAttribute(View.LANGUAGE_SESSION_ATTRIBUTE);
        DocumentVisualization documentVisualization;
        try {
            documentVisualization = documentService.visualizeDocument(documentData, language, mimeTypes,
                    "./document?" + RESOURCE_PARAM + "=");
        } catch (Exception e) {
            throw new ServletException("error visualizing the document: " + e.getMessage(), e);
        }
        if (null != documentVisualization) {
            contentType = documentVisualization.getBrowserContentType();
            documentData = documentVisualization.getBrowserData();
        }
    }

    setResponseHeaders(request, response);

    response.setContentType(contentType);
    response.setContentLength(documentData.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(documentData);
    out.flush();
}

From source file:com.liferay.arquillian.DeployerServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {//from   w  w w  . j  av a2s  .co  m
        InputStream bundleInputStream = getUploadedBundleInputStream(request);

        BundleContext bundleContext = _bundle.getBundleContext();

        Bundle newBundle = bundleContext.installBundle(_deployerServletInstallLocation, bundleInputStream);

        newBundle.start();

        Filter bundleContextFilter = bundleContext
                .createFilter("(&(objectClass=com.liferay.httpservice.internal.servlet."
                        + "BundleServletContext)(bundle.id=" + newBundle.getBundleId() + "))");

        ServiceTracker servletContextServiceTracker = new ServiceTracker(bundleContext, bundleContextFilter,
                null);

        servletContextServiceTracker.open();

        ServletContext servletContext = (ServletContext) servletContextServiceTracker
                .waitForService(_installTimeout);

        Servlet arquillianServletRunner = waitForServlet(servletContext, "ArquillianServletRunner",
                _installTimeout);

        if (arquillianServletRunner == null) {
            throw new TimeoutException(
                    "The arquillian servlet runner is taking more than " + _installTimeout + " to deploy");
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(TEXT);
        response.setHeader(_contextPathHeader, servletContext.getContextPath());
    } catch (Exception e) {
        signalError(e, response);
    } finally {
        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.flush();
    }
}

From source file:org.betaconceptframework.astroboa.console.filter.BinaryChannelDynamicFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    String absoluteBinaryChannelPath = createAbsoluteBinaryChannelPath(httpServletRequest.getContextPath(),
            httpServletRequest.getRequestURI());

    if (StringUtils.isNotBlank(absoluteBinaryChannelPath)) {

        InputStream contentAsStream = null;

        try {//from  w  w w  . j  a va 2  s. c o  m
            contentAsStream = new FileInputStream(absoluteBinaryChannelPath);

            if (contentAsStream != null) {
                ServletOutputStream servletOutputStream = response.getOutputStream();

                IOUtils.copy(contentAsStream, servletOutputStream);

                servletOutputStream.flush();

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

            //Close Stream
            if (contentAsStream != null) {
                try {
                    contentAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else
                chain.doFilter(request, response);
        }
    } else
        chain.doFilter(request, response);

}

From source file:org.kuali.ole.module.purap.document.web.struts.PrintAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //get parameters
    String poDocNumber = request.getParameter("poDocNumber");
    Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId"));
    if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) {
        throw new RuntimeException();
    }/*from w w w . j a  v a  2 s .c o  m*/

    // doc service - get this doc
    PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class)
            .getByDocumentHeaderId(poDocNumber);
    DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class)
            .getDocumentAuthorizer(po);

    if (!documentAuthorizer.canInitiate(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER,
            GlobalVariables.getUserSession().getPerson())) {
        throw new DocumentInitiationException(OLEKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] {
                GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" });
    }

    // get the vendor quote
    PurchaseOrderVendorQuote poVendorQuote = null;
    for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) {
        if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) {
            poVendorQuote = vendorQuote;
            break;
        }
    }

    if (poVendorQuote == null) {
        throw new RuntimeException();
    }

    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");

        // call the print service
        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            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:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java

@Override
public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from   w  w w .j  a  v  a  2  s  . co  m*/
        // We always return xhtml in utf-8
        response.setContentType("application/xhtml+xml");
        response.setCharacterEncoding("utf-8");

        // Default filename just in case none is found in form
        String filename = defaultFilename;

        // Commons file upload
        ServletFileUpload upload = new ServletFileUpload();

        // Go through upload items
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // Parse form fields
                String fieldname = item.getFieldName();

                if ("chartFilename".equals(fieldname)) {
                    // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default
                    // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
                    //   "The parts are sent to the processing agent in the same order the
                    //    corresponding controls appear in the document stream."
                    filename = Streams.asString(stream, "utf-8");
                } else if ("chartDataXML".equals(fieldname)) {
                    log.info("Doing form bounce");
                    String filenameAscii = formSafeAscii(filename);
                    String fileNameUtf = formSafeUtfName(filename);
                    String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''"
                            + fileNameUtf;
                    response.setHeader("Content-Disposition", cdh);
                    ServletOutputStream out = response.getOutputStream();
                    Streams.copy(stream, out, false);
                    out.flush();
                    // No more processing needed (prevent BOTH form AND upload from happening)
                    return;
                }
            } else {
                // Handle upload
                log.info("Doing file bounce");
                ServletOutputStream out = response.getOutputStream();
                Streams.copy(stream, out, false);
                out.flush();
                // No more processing needed (prevent BOTH form AND upload from happening)
                return;
            }
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:com.ningpai.common.util.CaptchaController.java

@RequestMapping("/captcha")
public void writeCaptcha(HttpServletRequest request, HttpServletResponse response) {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {//from ww w .  ja v a 2 s  .  com
        // get the session id that will identify the generated captcha.
        // the same id must be used to validate the response, the session id is a good candidate!
        String captchaId = request.getSession().getId();
        BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());
        try {
            ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
        } catch (IOException e) {
        }
    } catch (IllegalArgumentException e) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e1) {
        }
        return;
    } catch (CaptchaServiceException e) {
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e1) {
        }
        return;
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // flush it in the response
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);

    ServletOutputStream responseOutputStream;
    try {
        responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    } catch (IOException e) {
    }

}

From source file:com.controlj.green.bulktrend.trendserver.SearchServlet.java

private void writeErrorInRow(HttpServletResponse resp, String msg) throws IOException {
    ServletOutputStream out = resp.getOutputStream();
    out.println("<tr><td colspan=\"100\">Error: " + msg + "</td></tr>");
    out.flush();
}

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

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //get parameters
    String poDocNumber = request.getParameter("poDocNumber");
    Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId"));
    if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) {
        throw new RuntimeException();
    }/*from www . j  av a2 s.co m*/

    // doc service - get this doc
    PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class)
            .getByDocumentHeaderId(poDocNumber);
    DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class)
            .getDocumentAuthorizer(po);

    if (!(documentAuthorizer.canInitiate(KFSConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER,
            GlobalVariables.getUserSession().getPerson())
            || documentAuthorizer.canInitiate(
                    KFSConstants.FinancialDocumentTypeCodes.CONTRACT_MANAGER_ASSIGNMENT,
                    GlobalVariables.getUserSession().getPerson()))) {
        throw new DocumentInitiationException(KFSKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] {
                GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" });
    }

    // get the vendor quote
    PurchaseOrderVendorQuote poVendorQuote = null;
    for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) {
        if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) {
            poVendorQuote = vendorQuote;
            break;
        }
    }

    if (poVendorQuote == null) {
        throw new RuntimeException();
    }

    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");

        // call the print service
        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            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:gov.utah.dts.det.ccl.actions.facility.information.license.LicensesPrintAction.java

@Action(value = "print-license-cert")
public void doPrintCertificate() {
    loadLicense();/*from   ww w.  j  av  a2s .c  o m*/

    try {
        ByteArrayOutputStream ba = LicenseCertificate.generate(license, request);
        if (ba != null && ba.size() > 0) {
            // This is where the response is set
            String filename = "license_certificate.pdf";
            response.setContentLength(ba.size());
            response.setContentType("application/pdf");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");

            ServletOutputStream out = response.getOutputStream();
            ba.writeTo(out);
            out.flush();
        }
    } catch (Exception ex) {
        // Generate an error pdf
        ByteArrayOutputStream ba = null;
        try {
            ba = new ByteArrayOutputStream();
            Document document = new Document(PageSize.A4, 50, 50, 100, 100);
            @SuppressWarnings("unused")
            PdfWriter writer = PdfWriter.getInstance(document, ba);
            document.open();
            document.add(new Paragraph("An error occurred while generating the letter document.",
                    FontFactory.getFont("Times-Roman", 12, Font.NORMAL)));
            document.close();
            if (ba != null && ba.size() > 0) {
                // This is where the response is set
                // String filename = getTrackingRecordScreening().getPerson().getFirstAndLastName() + " - " +
                // screeningLetter.getLetterType() + ".pdf";
                response.setContentLength(ba.size());
                response.setContentType("application/pdf");
                response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                // response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
                response.setHeader("Content-disposition", "attachment");

                ServletOutputStream out = response.getOutputStream();
                ba.writeTo(out);
                out.flush();
            }

        } catch (Exception e) {
            log.error("AN ERROR OCCURRED GENERATING ERROR PDF DOCUMENT: " + e);
        }
    }
}