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:com.funtl.framework.smoke.core.modules.act.service.ActModelService.java

/**
 * modelxml//from  w  w  w  .  j  ava2 s  .  c o m
 *
 * @throws IOException
 * @throws JsonProcessingException
 */
public void export(String id, HttpServletResponse response) {
    try {
        Model modelData = repositoryService.getModel(id);
        BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
        JsonNode editorNode = new ObjectMapper()
                .readTree(repositoryService.getModelEditorSource(modelData.getId()));
        BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
        BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
        byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

        ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
        IOUtils.copy(in, response.getOutputStream());
        String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.flushBuffer();
    } catch (Exception e) {
        throw new ActivitiException("modelxmlID=" + id, e);
    }

}

From source file:de.whs.poodle.repositories.ImageRepository.java

public void writeImageToHttpResponse(int imageId, HttpServletResponse response) {
    jdbc.query("SELECT mimetype,data FROM uploaded_image WHERE id = ?", new Object[] { imageId },

            // use ResultSetExtractor so we can check whether a row even existed (NotFoundException)
            new ResultSetExtractor<Void>() {

                @Override//from   w w  w  .ja v  a  2  s.c  om
                public Void extractData(ResultSet rs) throws SQLException {
                    if (!rs.next()) // image doesn't exist
                        throw new NotFoundException();

                    String mimeType = rs.getString("mimetype");
                    response.setContentType(mimeType);

                    // write input stream from DB into http response
                    try (InputStream in = rs.getBinaryStream("data");
                            OutputStream out = response.getOutputStream();) {
                        StreamUtils.copy(in, out);
                        response.flushBuffer();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    return null;
                }

            });
}

From source file:org.kaaproject.avro.ui.sandbox.services.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();

    try {/*from w  ww .ja v  a 2s .co  m*/
        FileItemIterator iterator = upload.getItemIterator(request);
        if (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            String name = item.getFieldName();

            logger.debug("Uploading file '{}' with item name '{}'", item.getName(), name);

            InputStream stream = item.openStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Streams.copy(stream, out, true);

            byte[] data = out.toByteArray();

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(new String(data));
            response.flushBuffer();
        } else {
            logger.error("No file found in post request!");
            throw new RuntimeException("No file found in post request!");
        }
    } catch (Exception e) {
        logger.error("Unexpected error in FileUploadServlet.doPost: ", e);
        throw new RuntimeException(e);
    }
}

From source file:architecture.ee.web.spring.controller.SecureDownloadController.java

@RequestMapping(value = "/logo/{logoId}", method = RequestMethod.GET)
@ResponseBody//w  w w.ja  v  a 2 s  .c  o  m
public void handleLogo(@PathVariable("logoId") Long logoId,
        @RequestParam(value = "width", defaultValue = "0", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "0", required = false) Integer height,
        HttpServletResponse response) throws IOException {

    try {
        LogoImage image = logoManager.getLogoImageById(logoId);

        if (image != null) {
            InputStream input;
            String contentType;
            int contentLength;
            if (width > 0 && width > 0) {
                input = logoManager.getImageThumbnailInputStream(image, width, height);
                contentType = image.getThumbnailContentType();
                contentLength = image.getThumbnailSize();
            } else {
                input = logoManager.getImageInputStream(image);
                contentType = image.getImageContentType();
                contentLength = image.getImageSize();
            }
            response.setContentType(contentType);
            response.setContentLength(contentLength);
            IOUtils.copy(input, response.getOutputStream());
            response.flushBuffer();
        }

    } catch (Exception e) {
        log.warn(e);
        response.setStatus(301);
        String url = ApplicationHelper.getApplicationProperty("components.download.images.no-logo-url",
                "/images/common/what-to-know-before-getting-logo-design.png");
        response.addHeader("Location", url);
    }
}

From source file:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the image with input image id from cache and stores it in output
 * stream.// w ww  .j  av a 2s.c  o m
 *
 * @param imgId
 *            Id of captured image
 * @param deviceId
 *            Device mac address
 * @param response
 *            httpservelet response
 * @param session
 *            http sssion
 * @throws IOException
 */
public void saveSnappedImage(String imgId, String deviceId, HttpServletResponse response, HttpSession session)
        throws IOException {

    String suffixName = getCurrentDateAndTime();
    String fileName = deviceId.toUpperCase() + "_" + suffixName + "." + IMG_FORMAT;

    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    BufferedImage img = imgCache.getItem(imgId);
    if (img != null) {
        OutputStream stream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(img, IMG_FORMAT, byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        stream.write(bytes);
        response.flushBuffer();
    } else {
        LOGGER.error("Could not retrieve the captured image!!!");
    }

}

From source file:com.mycompany.rboss.controller.OrderController.java

@RequestMapping(value = "/files/{id}", method = RequestMethod.GET)
public void getFile(@PathVariable("id") int fileName, HttpServletResponse response) {
    try {/*from w ww .  j av a2 s  . c  om*/
        NewClass nc = new NewClass();
        String path = servletContext.getRealPath("/WEB-INF/");
        System.out.println("in---->>>" + path);
        int i = path.indexOf("RBOSS");
        String npath = path.substring(0, i);
        String outp = npath + "RBOSS/";
        npath += "RBOSS/src/main/java/report/Order.jasper";
        // get your file as InputStream
        InputStream is = null;
        try {
            is = nc.getStream(fileName, npath, outp);
        } catch (JRException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        }
        // copy it to response's OutputStream
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        System.out.println("Error writing file to output stream. Filename was '" + fileName + "'");
        throw new RuntimeException("IOError writing file to output stream");
    }

}

From source file:com.qcadoo.mes.basic.controllers.WorkstationMultiUploadController.java

@RequestMapping(value = "/getAttachment.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER,
            BasicConstants.MODEL_WORKSTATION_ATTACHMENT);
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService//from www.j  a v  a 2s. c  om
            .getInputStream(attachment.getStringField(WorkstationAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(WorkstationAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(WorkstationAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

From source file:de.codecentric.batch.web.JobOperationsController.java

@RequestMapping(value = "/jobs/executions/{executionId}/log", method = RequestMethod.GET)
public void getLogFile(HttpServletResponse response, @PathVariable long executionId)
        throws NoSuchJobExecutionException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Get log file for job with executionId: " + executionId);
    }//w  ww.  j a v  a2  s  .  c  o m
    String loggingPath = createLoggingPath();
    JobExecution jobExecution = jobExplorer.getJobExecution(executionId);
    if (jobExecution == null) {
        throw new NoSuchJobExecutionException("JobExecution with id " + executionId + " not found.");
    }
    File downloadFile = new File(loggingPath + jobLogFileNameCreator.getName(jobExecution));
    InputStream is = new FileInputStream(downloadFile);
    FileCopyUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
}

From source file:com.qcadoo.mes.basic.controllers.SubassemblyMultiUploadController.java

@RequestMapping(value = "/getAttachmentForSubassembly.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER,
            BasicConstants.MODEL_SUBASSEMBLY_ATTACHMENT);
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService/*from w w w .  ja v  a2 s. co m*/
            .getInputStream(attachment.getStringField(SubassemblyAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(SubassemblyAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(SubassemblyAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

From source file:com.indeed.iupload.web.controller.AppController.java

@RequestMapping(value = "/repository/{repoId}/index/{indexName}/file/{fileStatus}/{fileName}", method = RequestMethod.GET)
public void executeDownloadFile(@PathVariable String repoId, @PathVariable String indexName,
        @PathVariable String fileStatus, @PathVariable String fileName, HttpServletResponse response) {
    try {//  ww  w  .j a  va  2 s .co m
        IndexRepository repository = getRepository(repoId);
        Index index = repository.find(indexName);
        FileInfo file = index.findFile(FileStatus.fromName(fileStatus), fileName);
        if (file == null) {
            throw new BadRequestException("file not found");
        }
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        InputStream is = file.getInputStream();
        try {
            org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
        } finally {
            Closeables2.closeQuietly(is, log);
        }
        response.flushBuffer();
    } catch (IOException e) {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    }
}