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:de.knurt.fam.template.controller.letter.LetterGeneratorShowLetter.java

private void processIntern(HttpServletResponse response, PostMethod post, String customid) {
    //  forward response got
    //  force "save as" in browser
    String downloadFilename = this.df.format(new Date()) + "-" + customid + ".pdf";
    response.setHeader("Content-Disposition", "attachment; filename=" + downloadFilename);
    //  it is a pdf
    response.setContentType("application/pdf");
    try {//from  w w w.jav a2s .  c  om
        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(post.getResponseBody());
        ouputStream.flush();
        ouputStream.close();
    } catch (IOException e) {
        FamLog.exception(e, 201106131408l);
    }
}

From source file:com.geminimobile.web.DownloadCSVController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String msisdn = (String) request.getParameter("msisdn");
    String startTime = (String) request.getParameter("starttime");
    String endTime = (String) request.getParameter("endtime");
    String market = (String) request.getParameter("market");
    String type = (String) request.getParameter("type");

    Date toDate = SearchCommand.m_sdf.parse(endTime);
    //String maxTimestamp = Long.toString(toDate.getTime());

    Date fromDate = SearchCommand.m_sdf.parse(startTime);
    //String minTimestamp = Long.toString(fromDate.getTime());

    CDRDataAccess cdrAccess = new CDRDataAccess();
    Vector<CDREntry> cdrs = cdrAccess.getCDRsByMSISDN(msisdn, fromDate.getTime(), toDate.getTime(), market,
            type, 100000); // 100,000 entries max

    //Vector<CDREntry> cdrs = (Vector<CDREntry>) request.getSession().getAttribute("cdrResults");

    StringBuffer sb = new StringBuffer();

    // Write column headers 
    sb.append("Date/Time,Market,Type,MSISDN,MO IP address,MT IP Address,Sender Domain,Recipient Domain\n");

    for (CDREntry entry : cdrs) {
        sb.append(entry.getDisplayTimestamp() + "," + entry.getMarket() + "," + entry.getType() + ","
                + entry.getMsisdn() + "," + entry.getMoIPAddress() + "," + entry.getMtIPAddress() + ","
                + entry.getSenderDomain() + "," + entry.getRecipientDomain() + "\n");
    }/*from w  w  w.jav  a 2  s . com*/

    String csvString = sb.toString();

    response.setBufferSize(sb.length());
    response.setContentLength(sb.length());

    response.setContentType("text/plain; charset=UTF-8");
    //response.setContentType( "text/csv" );
    //response.setContentType("application/ms-excel");
    //response.setHeader("Content-disposition", "attachment;filename=cdrResults.csv");
    response.setHeader("Content-Disposition", "attachment; filename=" + "cdrResults.csv" + ";");
    ServletOutputStream os = response.getOutputStream();

    os.write(csvString.getBytes());

    os.flush();
    os.close();

    return null;
}

From source file:com.octo.captcha.module.acegi.JCaptchaSoundController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse response)
        throws Exception {
    byte[] captchaChallengeAsWav = null;

    ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream();

    //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 = httpServletRequest.getSession().getId();

    AudioInputStream challenge = soundCaptchaService.getSoundChallengeForID(captchaId,
            httpServletRequest.getLocale());

    // a jpeg encoder
    AudioInputStream stream = (AudioInputStream) challenge;

    // call the ImageCaptchaService method to retrieve a captcha
    AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream);

    captchaChallengeAsWav = wavOutputStream.toByteArray();

    // configure cache  directives
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    //flush content in the response
    response.setContentType("audio/x-wav");
    ServletOutputStream responseOutputStream = response.getOutputStream();
    responseOutputStream.write(captchaChallengeAsWav);
    responseOutputStream.flush();
    responseOutputStream.close();/*from w  w w.  ja  v  a2 s  .  c  om*/
    return null;
}

From source file:com.tapas.evidence.fe.controller.CaptchaController.java

@RequestMapping("/captcha.jpg")
public void showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {//from   www . j a v a2  s .c om
        // 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());

        ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
    } catch (IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        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 = response.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:com.dreamwork.web.FrontJsonController.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    ServletOutputStream out = response.getOutputStream();

    String message = "Not supported";

    out.write(message.getBytes("UTF-8"));
    out.flush();

}

From source file:net.bafeimao.umbrella.web.controller.CaptchaController.java

@RequestMapping("")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setDateHeader("Expires", 0);
    // 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");
    // return a jpeg
    response.setContentType("image/jpeg");
    // create the text for the image
    String capText = captchaProducer.createText();
    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    // write the data out
    ImageIO.write(bi, "jpg", out);

    try {/* w w w. j ava2s. c om*/
        out.flush();
    } finally {
        out.close();
    }

    return null;
}

From source file:com.ibm.watson.ta.retail.ImportHousingServlet.java

/**
 * Forward the request to the index.jsp file
 *
 * @param req the req/*from w w  w .j ava  2s . co m*/
 * @param resp the resp
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    logger.info("forwarding...");

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL;
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();

        Request newReq = Request.Get(uri);
        newReq.addHeader("Authorization", "Basic c2ltcGx5cmV0czpzaW1wbHlyZXRz");
        logger.log(Level.SEVERE, "My custom log:" + queryStr);

        Executor executor = Executor.newInstance();
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:org.chimi.s4s.controller.FileDownloadController.java

private void sendFile(boolean imageInline, FileSource source, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    response.setContentType(source.getMimeType());
    cacheStrategy.setCacheOption(source, response);
    response.setHeader("Content-Disposition", (imageInline ? "inline" : "attachment") + "; filename=\""
            + getHeaderFileName(source.getFileName(), request) + "\";");
    response.setContentLength((int) source.getLength());

    ServletOutputStream out = response.getOutputStream();
    source.write(out);/*from  w ww.java2  s  . co  m*/

    out.flush();
    out.close();
}

From source file:org.itracker.web.actions.admin.language.ExportLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    ActionMessages errors = new ActionMessages();

    if (!LoginUtilities.hasPermission(UserUtilities.PERMISSION_USER_ADMIN, request, response)) {
        return mapping.findForward("unauthorized");
    }//  w  ww  .j  av  a  2s  . c  o  m

    try {
        ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
                .getConfigurationService();

        String locale = (String) PropertyUtils.getSimpleProperty(form, "locale");
        if (locale != null && !locale.equals("")) {
            StringBuffer output = new StringBuffer(
                    "# ITracker language properties file for locale " + locale + "\n\n");

            List<NameValuePair> items = configurationService.getDefinedKeysAsArray(locale);
            for (int i = 0; i < items.size(); i++) {
                if (items.get(i).getName() != null && items.get(i).getValue() != null) {
                    output.append(
                            ITrackerResources.escapeUnicodeString(items.get(i).getName(), false) + "="
                                    + ITrackerResources.escapeUnicodeString(
                                            HTMLUtilities.escapeNewlines(items.get(i).getValue()), false)
                                    + "\n");
                }
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"ITracker"
                    + (locale.equals(ITrackerResources.BASE_LOCALE) ? "" : "_" + locale) + ".properties\"");
            response.setHeader("Content-Type", "application/x-itracker-language-export; charset=UTF-8");
            ServletOutputStream out = response.getOutputStream();
            out.print(output.toString());
            out.flush();
            return null;
        }
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidlocale"));
    } catch (RuntimeException e) {
        log.error("Exception while exporting language.", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    } catch (IllegalAccessException e) {
        log.error("Exception while exporting language.", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    } catch (InvocationTargetException e) {
        log.error("Exception while exporting language.", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    } catch (NoSuchMethodException e) {
        log.error("Exception while exporting language.", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
    }

    return mapping.findForward("error");
}

From source file:mx.com.quadrum.contratos.controller.busquedas.MuestraPdf.java

@RequestMapping(value = "muestraPdf/{idContrato}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) {
    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;//  ww w  .j a  v a  2  s. c o  m
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);

    Usuario usuario = (Usuario) session.getAttribute(USUARIO);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    File pdf = new File(
            USUARIOS + usuario.getMail() + "\\" + contrato.getNombre() + "\\" + contrato.getNombre() + ".pdf");
    try {
        InputStream in = new FileInputStream(pdf);
        byte[] data = new byte[in.available()];
        in.read(data);
        javax.servlet.ServletOutputStream servletoutputstream = response.getOutputStream();

        servletoutputstream.write(data);
        servletoutputstream.flush();
        servletoutputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}