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.amalto.core.servlet.ExportServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException {
    XmlServer server = Util.getXmlServerCtrlLocal();
    String clusterName = getParameter(request, PARAMETER_CLUSTER, true);
    int start = Integer.parseInt(getParameter(request, PARAMETER_START, true));
    int end = Integer.parseInt(getParameter(request, PARAMETER_END, true));
    boolean includeMetadata = Boolean
            .parseBoolean(getParameter(request, PARAMETER_INCLUDE_METADATA, false, "false")); //$NON-NLS-1$

    ServletOutputStream outputStream;
    try {/*  w  ww . j  a  v  a 2s . c  om*/
        outputStream = resp.getOutputStream();
    } catch (IOException e) {
        throw new ServletException(e);
    }

    try {
        resp.setContentType("text/xml");
        server.exportDocuments(clusterName, start, end, includeMetadata, outputStream);
    } catch (XtentisException e) {
        throw new ServletException(e);
    } finally {
        try {
            outputStream.flush();
        } catch (IOException e) {
            LOGGER.error("Error during flush", e);
        }
    }
}

From source file:org.apache.myfaces.renderkit.html.util.MyFacesResourceLoader.java

/**
 * Copy the content of the specified input stream to the servlet response.
 *///from w w  w .  ja  v a2s.  c om
protected void writeResource(HttpServletRequest request, HttpServletResponse response, InputStream in)
        throws IOException {
    ServletOutputStream out = response.getOutputStream();
    try {
        byte[] buffer = new byte[1024];
        for (int size = in.read(buffer); size != -1; size = in.read(buffer)) {
            out.write(buffer, 0, size);
        }
        out.flush();
    } catch (IOException e) {
        // This happens sometimes with Microsft Internet Explorer. It would
        // appear (guess) that when javascript creates multiple dom nodes
        // referring to the same remote resource then IE stupidly opens 
        // multiple sockets and requests that resource multiple times. But
        // when the first request completes, it then realises its stupidity
        // and forcibly closes all the other sockets. But here we are trying
        // to service those requests, and so get a "broken pipe" failure 
        // on write. The only thing to do here is to silently ignore the issue,
        // ie suppress the exception. Note that it is also possible for the
        // above code to succeed (ie this exception clause is not run) but
        // for a later flush to get the "broken pipe"; this is either due
        // just to timing, or possibly IE is closing sockets after receiving
        // a complete file for some types (gif?) rather than waiting for the
        // server to close it. We throw a special exception here to inform
        // callers that they should NOT flush anything - though that is
        // dangerous no matter what IOException subclass is thrown.
        log.debug("Unable to send resource data to client", e);
        throw new ResourceLoader.ClosedSocketException();
    }
}

From source file:org.hyperic.hq.ui.servlet.ImageServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from   ww w. j  a  v a  2s.  c om*/
        // parse the parameters
        log.debug("Parsing parameters.");

        parseParameters(request);

        // image format
        String imageFormat = parseStringParameter(request, IMAGE_FORMAT_PARAM, getDefaultImageFormat(),
                VALID_IMAGE_FORMATS);
        if (log.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer("Parameters:");
            sb.append("\n\t");
            sb.append(IMAGE_FORMAT_PARAM).append(": ").append(imageFormat);
            log.debug(sb.toString());
        }

        Object imgObj = createImage(request);

        // render the chart
        log.debug("Rendering image.");
        ServletOutputStream out = response.getOutputStream();
        if (imageFormat.equals(IMAGE_FORMAT_PNG)) {
            response.setContentType("image/png");
            renderPngImage(out, imgObj);
        } else {
            response.setContentType("image/jpeg");
            renderJpegImage(out, imgObj);
        }
        out.flush();
    } catch (IOException e) {
        // it's okay to ignore this one
        log.debug("Error writing image to response.", e);
    } catch (Exception e) {
        log.error("Unknown error.", e);
        throw new ServletException("Unknown error.", e);
    }
}

From source file:opendap.bes.dap4Responders.FileAccess.java

private void sendDatasetFile(String dataSourceId, HttpServletResponse response)
        throws IOException, BESError, BadConfigurationException, PPTException {
    log.debug("sendDatasetFile() - Sending dataset file \"" + dataSourceId + "\"");

    String downloadFileName = Scrub.fileName(dataSourceId.substring(dataSourceId.lastIndexOf("/") + 1));

    log.debug("respondToHttpGetRequest() - downloadFileName: " + downloadFileName);

    String contentDisposition = " attachment; filename=\"" + downloadFileName + "\"";

    response.setHeader("Content-Disposition", contentDisposition);

    String suffix = ReqInfo.getSuffix(dataSourceId);

    if (suffix != null) {
        String mType = MimeTypes.getMimeType(suffix);

        if (mType != null)
            response.setContentType(mType);

        log.debug("respondToHttpGetRequest() -    MIME type: " + mType + "  ");
    }/*from   www.  ja  v  a  2  s  .c om*/

    ByteArrayOutputStream erros = new ByteArrayOutputStream();
    BesApi besApi = getBesApi();

    ServletOutputStream sos = response.getOutputStream();
    if (!besApi.writeFile(dataSourceId, sos, erros)) {
        String msg = new String(erros.toByteArray());
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
    }

    sos.flush();
    log.debug("Sent {}", getServiceTitle());

}

From source file:com.eucalyptus.www.X509Download.java

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String code = request.getParameter(PARAMETER_CODE);
    String userName = request.getParameter(PARAMETER_USERNAME);
    String accountName = request.getParameter(PARAMETER_ACCOUNTNAME);
    String mimetype = "application/zip";
    if (accountName == null || "".equals(accountName)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "No account name provided", response);
        return;/*ww w . j a  v  a2s  .c o m*/
    }
    if (userName == null || "".equals(userName)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "No user name provided", response);
        return;
    }
    if (code == null || "".equals(code)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "Wrong user security code", response);
        return;
    }

    User user = null;
    try {
        Account account = Accounts.lookupAccountByName(accountName);
        user = account.lookupUserByName(userName);
        if (!user.isEnabled() || !RegistrationStatus.CONFIRMED.equals(user.getRegistrationStatus())) {
            hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response);
            return;
        }
    } catch (AuthException e) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "User does not exist", response);
        return;
    } catch (Exception e) {
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to retrieve user data", response);
        return;
    }
    try {
        if (!code.equals(user.resetToken())) {
            hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response);
            return;
        }
    } catch (Exception e) {
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can not reset user security code", response);
        return;
    }
    response.setContentType(mimetype);
    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + X509Download.NAME_SHORT + "-" + userName + "-x509.zip\"");
    LOG.info("pushing out the X509 certificate for user " + userName);

    byte[] x509zip = null;
    try {
        x509zip = getX509Zip(user);
    } catch (Exception e) {
        LOG.debug(e, e);
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to return user credentials", response);
        return;
    }
    try {
        ServletOutputStream op = response.getOutputStream();

        response.setContentLength(x509zip.length);

        op.write(x509zip);
        op.flush();

    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:com.jd.survey.web.reports.ReportController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "spss", produces = "text/html")
public void surveySPSSExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {//w w  w.  ja  v  a 2 s.  c o  m
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String metadataFileName = "survey" + surveyDefinitionId + ".sps";
        String dataFileName = "survey" + surveyDefinitionId + ".dat";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipfile = new ZipOutputStream(baos);

        //metadata    
        zipfile.putNextEntry(new ZipEntry(metadataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSMetadata(surveyDefinitionId, dataFileName));
        //data
        zipfile.putNextEntry(new ZipEntry(dataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSData(surveyDefinitionId));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinitionId + "_spss.zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(baos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apdplat.module.security.service.filter.JCaptchaFilter.java

protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response) {

    ServletUtils.setDisableCacheHeader(response);
    response.setContentType("image/png");
    ServletOutputStream out = null;
    try {//from www .  j  av a 2 s . co m
        out = response.getOutputStream();
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId,
                request.getLocale());
        //String writerNames[] = ImageIO.getWriterFormatNames();
        ImageIO.write(challenge, "png", out);
        out.flush();
    } catch (Exception e) {
        //org.apache.catalina.connector.ClientAbortException
        if (!"org.apache.catalina.connector.ClientAbortException".equals(e.getClass().getName())) {
            LOG.error("???", e);
        }
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            LOG.error("???", e);
        }
    }
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView rss(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {/*  w w  w  .  ja  v a 2 s.com*/
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        Channel channel = feedsBo.buildChannel(events, Utilities.getBaseUrl(req), buildChannelLink(req));
        // flush it in the res
        WireFeedOutput wfo = new WireFeedOutput();
        res.setHeader("Cache-Control", "no-store");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("text/xml");
        res.setCharacterEncoding("UTF-8");
        ServletOutputStream resOutputStream = res.getOutputStream();
        wfo.output(channel, new OutputStreamWriter(resOutputStream, "UTF-8"));
        resOutputStream.flush();
        resOutputStream.close();
    } catch (Exception exception) {
        logger.error("Error producing RSS", exception);
        throw exception;
    }
    return null;
}

From source file:com.mkmeier.quickerbooks.ProcessUwcu.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//w w  w.  ja va2  s  .  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    if (!ServletFileUpload.isMultipartContent(request)) {
        showForm(request, response);
    } else {

        ServletFileUploader up = new ServletFileUploader();
        up.parseRequest(request);

        File file = up.getFileMap().get("uwcuTxn");

        int depositAcctNum = Integer.parseInt(up.getFieldMap().get("depositAcct"));
        int creditCardAcctNum = Integer.parseInt(up.getFieldMap().get("ccAcct"));

        QbAccount depositAcct = getAccount(depositAcctNum);
        QbAccount creditCardAcct = getAccount(creditCardAcctNum);

        UwcuParser uwcuParser = new UwcuParser(file);
        List<UwcuTxn> txns;

        try {
            txns = uwcuParser.parse();
        } catch (UwcuException ex) {
            throw new ServletException(ex);
        }

        UwcuToIif uwcuToIif = new UwcuToIif(txns, depositAcct, creditCardAcct);
        File iifFile = uwcuToIif.getIifFile();

        response.setHeader("Content-Disposition", "attachement; filename=\"iifFile.iif\"");
        ServletOutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(iifFile);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
}

From source file:org.ikasan.console.web.controller.WiretapEventsSearchFormController.java

/**
 * Download the payload content as a file
 * // w w w.  ja  va  2  s. c om
 * TODO Improve Error handling?
 * 
 * @param wiretapEventId - The Event id of the wiretapped event to download
 * @param response - The HttpServletResponse object, content is streamed to
 *            this
 */
@RequestMapping("downloadPayloadContent.htm")
public void outputFile(@RequestParam("wiretapEventId") long wiretapEventId,
        final HttpServletResponse response) {
    this.logger.debug("inside downloadPayloadContent, wiretapEventId=[" + wiretapEventId + "]");
    WiretapEvent wiretapEvent = this.wiretapService.getWiretapEvent(new Long(wiretapEventId));
    String outgoingFileName = String.valueOf(wiretapEvent.getIdentifier());
    response.setContentType("application/download");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + outgoingFileName + "\"");
    try {
        ServletOutputStream op = response.getOutputStream();
        op.write(wiretapEvent.getEvent().toString().getBytes());
        op.flush();
    } catch (IOException e) {
        this.logger.error("Could not download payload content.", e);
    }
}