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:mx.com.quadrum.contratos.controller.busquedas.MuestraPdf.java

@RequestMapping(value = "muestraPdf/{idContrato}/{idEmpleado}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato,
        @PathVariable("idEmpleado") Integer idEmpleado, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {/*w  ww  . j  a v a 2s  . c o  m*/

    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    Usuario usuario = usuarioService.buscarPorId(idEmpleado);
    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();
    }

}

From source file:org.chos.transaction.passport.controller.CaptchaController.java

@RequestMapping(value = "/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedImage bi = new BufferedImage(40, 18, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    String c = generate();/*from  w w  w  . j  a va2 s .  com*/
    g.setColor(Color.white);
    g.fillRect(1, 1, 38, 16);

    g.setColor(generateColor());
    g.drawString(c, 4, 13);
    response.setContentType("image/jpeg");
    ServletOutputStream os = response.getOutputStream();
    //      os.write(b)
    //      ImageIO.createImageOutputStream(os);
    ImageIO.write(bi, "jpg", os);
    os.flush();
    os.close();
    request.getSession().setAttribute("captcha", c);
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Write response as file stream when you want to provide download functionality.
 * Note that by using this method the response as HTML will not be generated and
 * the response will be what you have defined.
 *
 * @param file - File to be written on response.
 * @param bufferSize - Buffer size to write the response. Example 2048 bytes.
 * @throws IOException/*from  w ww .ja va2  s.  c  om*/
 */
public static void writeResponseAsFileStream(File file, int bufferSize) throws IOException {
    WebContext context = getCurrentInstance();
    if (context != null && file != null && bufferSize > 0) {
        context.responseWritten = true;
        context.response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
        context.response.addHeader("Content-Length", Long.toString(file.length()));
        context.response.setContentLength((int) file.length());

        String mimetype = getApplication().getMimeType(file.getName());
        context.response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");

        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = context.response.getOutputStream();

        try {
            int i;
            byte[] buffer = new byte[bufferSize];
            while ((i = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, i);
            }
        } finally {
            outputStream.flush();
            fileInputStream.close();
        }
    }
}

From source file:org.fenixedu.bennu.core.filters.CloseTransactionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {//from  w ww  . j  a  v  a  2s . c  om
        doChain(request, response, chain);
    } catch (Error t) {
        t.printStackTrace();
        InputStream resource = request.getServletContext().getResourceAsStream("/error.html");
        if (resource != null) {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("text/html");
            IOUtils.copy(resource, outputStream);
            outputStream.flush();
        } else {
            throw t;
        }
    }
}

From source file:com.haulmont.restapi.controllers.FileDownloadController.java

protected void downloadFromMiddlewareAndWriteResponse(FileDescriptor fd, HttpServletResponse response)
        throws IOException {
    ServletOutputStream os = response.getOutputStream();
    try (InputStream is = fileLoader.openStream(fd)) {
        IOUtils.copy(is, os);/*from  w  w  w. j av a2  s.  c  o m*/
        os.flush();
    } catch (FileStorageException e) {
        throw new RestAPIException("Unable to download file from FileStorage",
                "Unable to download file from FileStorage: " + fd.getId(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.octo.captcha.module.struts.image.RenderImageCaptchaAction.java

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    ImageCaptchaService service = (ImageCaptchaService) CaptchaServicePlugin.getInstance().getService();
    String captchaID = CaptchaModuleConfigHelper.getId(httpServletRequest);
    //(String) theRequest.getParameter(captchaIDParameterName);

    // call the ManageableImageCaptchaService methods
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/*from   w  w w. jav  a2s .com*/
        BufferedImage challenge = service.getImageChallengeForID(captchaID, httpServletRequest.getLocale());
        // the output stream to render the captcha image as jpeg into

        // a jpeg encoder
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
        jpegEncoder.encode(challenge);
    } catch (IllegalArgumentException e) {
        // log a security warning and return a 404...
        if (log.isWarnEnabled()) {
            log.warn("There was a try from " + httpServletRequest.getRemoteAddr()
                    + " to render an URL without ID" + " or with a too long one");
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            log.error("should never pass here!");
            return actionMapping.findForward("error");
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        log.warn("Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        // log.error("should never pass here!");
        return actionMapping.findForward("error");
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
    // log.error("should never pass here!");
    return null;
}

From source file:com.rplt.studioMusik.controller.OwnerController.java

@RequestMapping(value = "/lihatlaporan")
public String lihatLaporan(ModelMap model, HttpServletResponse response) {
    String tanggalAwal = request.getParameter("tanggalAwal").toUpperCase();
    String tanggalAkhir = request.getParameter("tanggalAkhir").toUpperCase();

    //        List<PersewaanStudioMusik> dataListByMonth = persewaanStudioMusik.getDataListByMonth(tanggalAwal, tanggalAkhir);
    //        //from w  w  w  .  j  av  a 2  s  .c  om
    //        model.addAttribute("bulan", tanggalAwal);
    //        model.addAttribute("tahun", tanggalAkhir);
    //        model.addAttribute("dataListByMonth", dataListByMonth);

    Connection conn = DatabaseConnection.getmConnection();
    //            File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file
    File reportFile = new File(
            servletConfig.getServletContext().getRealPath("/resources/report/laporan_pemasukan.jasper"));

    Map parameters = new HashMap();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("TANGGAL_AWAL", tanggalAwal);
    params.put("TANGGAL_AKHIR", tanggalAkhir);
    byte[] bytes = null;
    try {
        bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    } catch (JRException ex) {
        Logger.getLogger(OperatorController.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.setContentType("application/pdf");
    response.setContentLength(bytes.length);

    try {
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes, 0, bytes.length);
        outStream.flush();
        outStream.close();
    } catch (IOException ex) {
        Logger.getLogger(OperatorController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "halaman-cetakReport-owner";
}

From source file:fr.aliasource.webmail.server.export.ExportConversationImpl.java

/**
 * The actual business logic./* w w w .ja  v a2 s  .  c  om*/
 * 
 * @param requ
 *            the request object
 * @param resp
 *            the response object
 * @throws IOException
 * @throws ServletException
 */
public void service(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
    logger.info("Export conversation called.");

    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String uri = req.getRequestURI();
    String convAndMessageIds = extractConversationIdFromRequestURI(uri);
    MessageId messageId = getMessageIdPart(convAndMessageIds);
    ConversationId conversationId = getConversationIdPart(convAndMessageIds);

    String folder = conversationId.getSourceFolder();

    logger.info("Conversation id: " + conversationId.getConversationId() + " folder: " + folder + " uri: " + uri
            + "Message id: " + messageId);

    Folder f = new Folder(folder, folder);
    ConversationReference cr = account.findConversation(conversationId);
    ClientMessage[] cm = null;
    if (messageId == null) {
        cm = account.fetchMessages(f, cr.getMessageIds());
    } else {
        cm = account.fetchMessages(f, Arrays.asList(messageId));
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ConversationExporter exporter = new ConversationExporter(
            req.getContextPath() + "/minig/images/logo_print.jpg");
    try {
        if (req.getRequestURI().endsWith(".html")) {
            exporter.exportToHtml(account, cr, cm, baos);
            response.setContentType("text/html");
        } else {
            exporter.exportToPdf(account, cr, cm, baos);
            response.setContentType("application/pdf");
        }
    } catch (ConversationExporterException e) {
        logger.error("Cannot render conversation", e);
        throw new ServletException(e);
    }

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");

    response.setContentLength(baos.size());
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();

}

From source file:org.efs.openreports.actions.admin.DataExportAction.java

public String execute() {
    try {/*w  w  w .  j  a v a  2s .  com*/
        if (!submitOk) {
            reports = reportProvider.getReports();
            return SUCCESS;
        }

        XStream xStream = new XStream();
        xStream.omitField(BasicDataSource.class, "logWriter");
        xStream.omitField(Report.class, "id");
        xStream.omitField(ReportAlert.class, "id");
        xStream.omitField(ReportChart.class, "id");
        xStream.omitField(ReportParameter.class, "id");
        xStream.omitField(ReportExportOption.class, "id");

        List<Report> selectedReports = new ArrayList<Report>();

        for (int i = 0; i < reportIds.length; i++) {
            Report report = reportProvider.getReport(new Integer(reportIds[i]));
            selectedReports.add(report);
        }

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setHeader("Content-disposition", "inline; filename=or-report-export.xml");
        response.setContentType("application/xml");

        ServletOutputStream outputStream = response.getOutputStream();

        xStream.toXML(selectedReports, outputStream);

        outputStream.flush();
        outputStream.close();

        return NONE;
    } catch (Exception e) {
        addActionError(e.toString());
        return INPUT;
    }
}

From source file:org.primeframework.mvc.action.result.JSONResult.java

public void execute(JSON json) throws IOException, ServletException {
    ActionInvocation current = actionInvocationStore.getCurrent();
    Object action = current.action;
    if (action == null) {
        throw new PrimeException(
                "There is no action class and somehow we got into the JSONResult code. Bad mojo!");
    }/*www  . j  a  v  a  2 s .  com*/

    ActionConfiguration configuration = current.configuration;
    if (configuration == null) {
        throw new PrimeException(
                "The action [" + action.getClass() + "] has no configuration. This should be impossible!");
    }

    // If there are error messages, put them in a well known container and render that instead of looking for the
    // @JSONResponse annotation
    Object jacksonObject;
    List<Message> messages = messageStore.get(MessageScope.REQUEST);
    if (messages.size() > 0) {
        jacksonObject = convertErrors(messages);
    } else {
        JacksonActionConfiguration jacksonActionConfiguration = (JacksonActionConfiguration) configuration.additionalConfiguration
                .get(JacksonActionConfiguration.class);
        if (jacksonActionConfiguration == null || jacksonActionConfiguration.responseMember == null) {
            throw new PrimeException("The action [" + action.getClass()
                    + "] is missing a field annotated with @JSONResponse. This is used to figure out what to send back in the response.");
        }

        jacksonObject = expressionEvaluator.getValue(jacksonActionConfiguration.responseMember, action);
        if (jacksonObject == null) {
            throw new PrimeException("The @JSONResponse field [" + jacksonActionConfiguration.responseMember
                    + "] in the action [" + action.getClass() + "] is null. It cannot be null!");
        }
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    objectMapper.writeValue(baos, jacksonObject);

    byte[] result = baos.toByteArray();
    response.setStatus(json.status());
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.setContentLength(result.length);

    if (!isCurrentActionHeadRequest(current)) {
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result);
        outputStream.flush();
    }
}