Example usage for javax.servlet.http HttpServletResponse flushBuffer

List of usage examples for javax.servlet.http HttpServletResponse flushBuffer

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse flushBuffer.

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:de.unirostock.sems.cbarchive.web.servlet.DownloadServlet.java

private void downloadArchive(HttpServletRequest request, HttpServletResponse response, UserManager user,
        String archive) throws IOException {

    // filters for omex extension
    //      ( is just there for the browser to name the downloaded file correctly)
    if (archive.endsWith("." + COMBINEARCHIVE_FILE_EXT))
        // just removes the file extension -> we get the archiveId
        archive = archive.substring(0, archive.length() - (COMBINEARCHIVE_FILE_EXT.length() + 1));

    File archiveFile = null;/*from  w w w  .  j a v a  2  s .c o m*/
    String archiveName = null;
    try {
        archiveFile = user.getArchiveFile(archive);
        archiveName = user.getArchive(archive, false).getName();
    } catch (FileNotFoundException | CombineArchiveWebException e) {
        LOGGER.warn(e, MessageFormat.format(
                "FileNotFound Exception, while handling donwload request for Archive {1} in Workspace {0}",
                user.getWorkingDir(), archive));
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    }

    // set MIME-Type to something downloadable
    response.setContentType("application/octet-stream");

    // set Content-Length
    response.setContentLength((int) archiveFile.length());

    // set the filename of the downloaded file
    response.addHeader("Content-Disposition",
            MessageFormat.format("inline; filename=\"{0}.{1}\"", archiveName, COMBINEARCHIVE_FILE_EXT));

    // print the file to the output stream
    try {
        OutputStream output = response.getOutputStream();
        InputStream input = new FileInputStream(archiveFile);

        // copy the streams
        IOUtils.copy(input, output);

        // flush'n'close
        output.flush();
        output.close();
        input.close();

        response.flushBuffer();
    } catch (IOException e) {
        LOGGER.error(e, MessageFormat.format(
                "IOException, while copying streams by handling donwload request for Archive {1} in Workspace {0}",
                user.getWorkingDir(), archive));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IOException while sending the file.");
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response,
        Resource resource) throws IOException {
    try {//from  w w  w .  j  a v  a  2  s .  c  om
        if (!request.getMethod().equals(HttpMethod.HEAD.asString())) {

            String ifms = request.getHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
            if (ifms != null) {

                long ifmsl = request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
                if (ifmsl != -1) {
                    if (resource.lastModified() / 1000 <= ifmsl / 1000) {
                        response.reset();
                        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                        response.flushBuffer();
                        return false;
                    }
                }
            }

            // Parse the if[un]modified dates and compare to resource
            long date = request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString());

            if (date != -1) {
                if (resource.lastModified() / 1000 > date / 1000) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return false;
                }
            }
        }
    } catch (IllegalArgumentException iae) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
            return false;
        }
        throw iae;
    }
    return true;
}

From source file:com.rmn.qa.servlet.BmpServlet.java

/**
 * //from  w  w w.  j a v a 2s  .co m
 * {@inheritDoc}
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(200);

    StringBuilder builder = new StringBuilder();

    builder.append("<html>");
    builder.append("<head>");

    builder.append("<title>BrowserMobProxy instances</title>");

    builder.append("</head>");

    builder.append("<body>");
    builder.append("<H1>Grid Hub ");
    builder.append(coreVersion).append(coreRevision);
    builder.append("</H1>");
    Map<String, ProxyHolder> proxyMap = BmpProxyRegistry.getInstance().getProxyMap();
    DateFormat df = DateFormat.getDateTimeInstance();
    if (proxyMap.isEmpty()) {
        builder.append("No BrowserMobProxy instances currently running.");
    } else {
        for (Entry<String, ProxyHolder> entry : proxyMap.entrySet()) {
            StringBuilder localBuilder = new StringBuilder();
            ProxyHolder holder = entry.getValue();
            String uuid = entry.getKey();
            localBuilder.append("<fieldset>");
            localBuilder.append("<legend>BrowserMobProxy for test id ").append(uuid).append("</legend>");
            localBuilder.append("listening on ").append(holder.getProxy().getPort()).append("<br/>");
            localBuilder.append("started at ").append(df.format(new Date(holder.getCreated()))).append("<br/>");
            localBuilder.append("</fieldset>");
            builder.append(localBuilder.toString());
        }
    }
    try (InputStream in = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));) {
        ByteStreams.copy(in, response.getOutputStream());
    } finally {
        response.flushBuffer();
    }
}

From source file:org.agnitas.web.MailingStatAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//from   w w  w .  j a v  a 2 s  .co  m
 *
 * @param form
 * @param req
 * @param res
 * @param mapping The ActionMapping used to select this instance
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 * @return destination
 */

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws IOException, ServletException {

    MailingStatForm aForm = null;
    ActionMessages errors = new ActionMessages();
    ActionForward destination = null;

    if (!this.checkLogon(req))
        return mapping.findForward("logon");

    if (form != null) {
        aForm = (MailingStatForm) form;
    } else {
        aForm = new MailingStatForm();
    }

    AgnUtils.logger().info("Action: " + aForm.getAction());

    if (!allowed("stats.mailing", req)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
        saveErrors(req, errors);
        return null;
    }

    try {
        switch (aForm.getAction()) {

        case ACTION_LIST:
            destination = mapping.findForward("list");
            break;

        case ACTION_MAILINGSTAT:
            if (aForm.isStatInProgress() == false) {
                if (aForm.isStatReady()) {
                    destination = mapping.findForward("mailing_stat");
                    aForm.setStatReady(false);
                    break;
                } else {
                    // display splash in browser
                    RequestDispatcher dp = req.getRequestDispatcher(mapping.findForward("splash").getPath());
                    dp.forward(req, res);
                    res.flushBuffer();
                    destination = null;
                    // get stats
                    aForm.setStatInProgress(true);
                    loadMailingStat(aForm, req);

                    aForm.setStatInProgress(false);
                    aForm.setStatReady(true);
                    break;
                }

            }
            break;

        case ACTION_SPLASH:
            if (aForm.isStatReady()) {
                destination = mapping.findForward("mailing_stat");
            }
            // just display splash
            destination = mapping.findForward("splash");
            break;

        case ACTION_OPENEDSTAT_SPLASH:
            if (aForm.isStatReady()) {
                destination = mapping.findForward("opened_stat");
            }
            // just display splash
            destination = mapping.findForward("splash");
            break;

        case ACTION_BOUNCESTAT_SPLASH:
            if (aForm.isStatReady()) {
                destination = mapping.findForward("bounce_stat");
            }
            // just display splash
            destination = mapping.findForward("splash");
            break;

        case ACTION_WEEKSTAT:
            loadWeekStat(aForm, req);
            destination = mapping.findForward("week_stat");
            break;

        case ACTION_DAYSTAT:
            loadDayStat(aForm, req);
            destination = mapping.findForward("day_stat");
            break;

        case ACTION_CLEAN_QUESTION:
            destination = mapping.findForward("clean_question");
            break;

        case ACTION_CLEAN:
            cleanAdminClicks(aForm, req);
            loadMailingStat(aForm, req);
            destination = mapping.findForward("mailing_stat");
            break;

        case ACTION_OPENEDSTAT:
            if (aForm.isStatInProgress() == false) {
                if (aForm.isStatReady()) {
                    destination = mapping.findForward("opened_stat");
                    aForm.setStatReady(false);
                    break;
                } else {
                    RequestDispatcher dp = req.getRequestDispatcher(mapping.findForward("splash").getPath());
                    dp.forward(req, res);
                    res.flushBuffer();
                    destination = null;
                    // get stats
                    aForm.setStatInProgress(true);
                    loadOpenedStat(aForm, req);
                    aForm.setStatInProgress(false);
                    aForm.setStatReady(true);
                    break;
                }
            }
            break;

        case ACTION_BOUNCESTAT:
            if (aForm.isStatInProgress() == false) {
                if (aForm.isStatReady()) {
                    destination = mapping.findForward("bounce_stat");
                    aForm.setStatReady(false);
                    break;
                } else {
                    RequestDispatcher dp = req.getRequestDispatcher(mapping.findForward("splash").getPath());
                    dp.forward(req, res);
                    res.flushBuffer();
                    destination = null;
                    // get stats
                    aForm.setStatInProgress(true);
                    loadBounceStat(aForm, req);
                    aForm.setStatInProgress(false);
                    aForm.setStatReady(true);
                    break;
                }
            }
            break;
        case ACTION_BOUNCE:
            destination = mapping.findForward("bounce");
            break;

        case ACTION_OPEN_TIME:
            loadOpenWeekStat(aForm, req);
            destination = mapping.findForward("open_week");
            break;

        case ACTION_OPEN_DAYSTAT:
            loadOpenDayStat(aForm, req);
            destination = mapping.findForward("open_day");
            break;

        default:
            aForm.setAction(MailingStatAction.ACTION_MAILINGSTAT);
            loadMailingStat(aForm, req);
            destination = mapping.findForward("list");
        }
    } catch (Exception e) {
        AgnUtils.logger().error("execute: " + e + "\n" + AgnUtils.getStackTrace(e));
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception"));
    }

    if (destination != null && "list".equals(destination.getName())) {
        try {
            req.setAttribute("mailingStatlist", getMailingStats(req));
            setNumberOfRows(req, aForm);
        } catch (Exception e) {
            AgnUtils.logger().error("mailingStatlist: " + e + "\n" + AgnUtils.getStackTrace(e));
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception"));
        }
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(req, errors);
    }

    return destination;
}

From source file:biz.astute.test.simulator.rest.SimulatorRestHandler.java

/**
 * {@inheritDoc}/* ww w .  j  a v a  2s  . c  o  m*/
 */
@Override
public final void handle(final String pTarget, final Request pBaseRequest, final HttpServletRequest pRequest,
        final HttpServletResponse pResponse) throws IOException, ServletException {

    // Lets set the default
    pResponse.setContentType("text/plain");

    try {

        DataResourceInterface dataResourceInterface = DataResourceFactory
                .getDataResource(new RequestContext(pRequest, pResponse));

        for (String header : dataResourceInterface
                .getProperties(DataResourceInterface.HEADER_RESPONSE_PREFIX)) {
            pResponse.setHeader(header.substring(DataResourceInterface.HEADER_RESPONSE_PREFIX.length() + 1),
                    dataResourceInterface.getPropertyValue(header));
        }

        String status = dataResourceInterface.getPropertyValue(DataResourceInterface.RESPONSE_STATUS);
        if (StringUtils.isEmpty(status)) {
            status = Integer.toString(HttpStatus.OK_200);
        }
        pResponse.setStatus(Integer.parseInt(status));
        String val = dataResourceInterface.getPropertyValue(DataResourceInterface.DATA_RESPONSE_VALUE);
        if (val == null) {

            try (InputStream inStream = dataResourceInterface
                    .getResourceData(DataResourceInterface.DATA_RESPONSE_RESOURCE);) {
                if (inStream != null) {
                    OutputStream outStream = pResponse.getOutputStream();
                    pResponse.setContentLength(IOUtils.copy(inStream, outStream));
                    outStream.flush();
                }
            }
        } else {
            pResponse.getWriter().print(val);
        }

    } catch (DataResourceException | NoSuchAlgorithmException execp) {
        LOGGER.log(Level.SEVERE, "Error Processing " + pRequest.getRequestURL(), execp);
        pResponse.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        pResponse.getWriter()
                .print("Error Processing " + pRequest.getRequestURL() + " - " + execp.getMessage());
    }
    pResponse.flushBuffer();
    pBaseRequest.setHandled(true);
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java

public ActionForward retrieveApprovedLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    final ApprovedLearningAgreementDocumentFile file = getDomainObject(request, "agreementId");
    final String hash = request.getParameter("hash");

    final MobilityIndividualApplicationProcess process = file.getProcess();
    final DegreeOfficePublicCandidacyHashCode candidacyHashCode = process.getCandidacyHashCode();
    if (candidacyHashCode.getValue().equals(hash)) {
        final byte[] content = file.getContent();
        response.setContentLength(content.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());

        final ServletOutputStream writer = response.getOutputStream();
        writer.write(content);/*  w ww . j  a  v  a  2  s.  c om*/
        writer.flush();
        writer.close();

        response.flushBuffer();
    }

    return null;
}

From source file:org.fenixedu.academic.ui.struts.action.administrativeOffice.lists.StudentListByDegreeDA.java

public ActionForward exportInfoToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {

    final SearchStudentsByDegreeParametersBean searchBean = getOrCreateSearchParametersBean();
    if (searchBean == null) {
        return null;
    }//from   www . jav a2 s. c om
    final List<RegistrationWithStateForExecutionYearBean> registrations = search(searchBean);

    try {
        String filename = getResourceMessage("label.students");

        Degree degree = searchBean.getDegree();
        DegreeType degreeType = searchBean.getDegreeType();
        ExecutionYear executionYear = searchBean.getExecutionYear();
        if (degree != null) {
            filename += "_" + degree.getNameFor(executionYear).getContent().replace(' ', '_');
        } else if (degreeType != null) {
            filename += "_" + degreeType.getName().getContent().replace(' ', '_');
        }
        filename += "_" + executionYear.getYear();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
        ServletOutputStream writer = response.getOutputStream();

        final String param = request.getParameter("extendedInfo");
        boolean extendedInfo = param != null && param.length() > 0 && Boolean.valueOf(param).booleanValue();

        exportToXls(registrations, writer, searchBean, extendedInfo);
        writer.flush();
        response.flushBuffer();
        return null;

    } catch (IOException e) {
        throw new FenixServiceException();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.lists.StudentListByDegreeDA.java

public ActionForward exportInfoToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {

    final SearchStudentsByDegreeParametersBean searchBean = getOrCreateSearchParametersBean();
    if (searchBean == null) {
        return null;
    }//from  ww  w  . j a  v a 2s.c  om
    final List<RegistrationWithStateForExecutionYearBean> registrations = search(searchBean);

    try {
        String filename = getResourceMessage("label.students");

        Degree degree = searchBean.getDegree();
        DegreeType degreeType = searchBean.getDegreeType();
        ExecutionYear executionYear = searchBean.getExecutionYear();
        if (degree != null) {
            filename += "_" + degree.getNameFor(executionYear).getContent().replace(' ', '_');
        } else if (degreeType != null) {
            filename += "_" + degreeType.getLocalizedName().replace(' ', '_');
        }
        filename += "_" + executionYear.getYear();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
        ServletOutputStream writer = response.getOutputStream();

        final String param = request.getParameter("extendedInfo");
        boolean extendedInfo = param != null && param.length() > 0 && Boolean.valueOf(param).booleanValue();

        exportToXls(registrations, writer, searchBean, extendedInfo);
        writer.flush();
        response.flushBuffer();
        return null;

    } catch (IOException e) {
        throw new FenixServiceException();
    }
}

From source file:org.apache.sling.servlets.resolver.internal.SlingServletResolver.java

private void handleError(final Servlet errorHandler, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {

    request.setAttribute(SlingConstants.ERROR_REQUEST_URI, request.getRequestURI());

    // if there is no explicitly known error causing servlet, use
    // the name of the error handler servlet
    if (request.getAttribute(SlingConstants.ERROR_SERVLET_NAME) == null) {
        request.setAttribute(SlingConstants.ERROR_SERVLET_NAME,
                errorHandler.getServletConfig().getServletName());
    }/*from  w  w  w. j  a  va 2s  .c  o  m*/

    // Let the error handler servlet process the request and
    // forward all exceptions if it fails.
    // Before SLING-4143 we only forwarded IOExceptions.
    try {
        errorHandler.service(request, response);
        // commit the response
        response.flushBuffer();
        // close the response (SLING-2724)
        response.getWriter().close();
    } catch (final Throwable t) {
        LOGGER.error("Calling the error handler resulted in an error", t);
        LOGGER.error("Original error " + request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE),
                (Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION));
        final IOException x = new IOException("Error handler failed: " + t.getClass().getName());
        x.initCause(t);
        throw x;
    }
}