Example usage for javax.servlet.http HttpServletResponse getBufferSize

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

Introduction

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

Prototype

public int getBufferSize();

Source Link

Document

Returns the actual buffer size used for the response.

Usage

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/view")
public String view(Model model, @RequestParam("fileId") String fileId, HttpServletResponse response)
        throws Exception {
    StringBuilder stringBuilder = null;

    FileDTO fileDTO;/*from ww  w . ja  va2  s .com*/
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;

    BufferedInputStream bufferdInputStream = null;
    ServletOutputStream servletOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();
    try {
        if (StringUtils.isNotEmpty(repositoryPath)) {
            // FILE_SYSTEM
            stringBuilder = new StringBuilder();
            stringBuilder.append(repositoryPath);
            if (!repositoryPath.endsWith(File.separator)) {
                stringBuilder.append(File.separator);
            }
            stringBuilder.append(uniqueFilename);
            File file = new File(stringBuilder.toString());
            inputStream = new FileInputStream(file);
        } else {
            // DATABASE
            byte[] bytes = new byte[] {};
            if (fileDTO.getFileSize() > 0) {
                bytes = fileDTO.getBytes();
            }
            inputStream = new ByteArrayInputStream(bytes);

        }
        response.setContentType(fileDTO.getContentType());

        // set response contenttype, header
        String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
        logger.debug("realFilename: {}", realFilename);
        logger.debug("encodedRealFilename: {}", encodedRealFilename);
        logger.debug("character encoding: {}", response.getCharacterEncoding());
        logger.debug("content type: {}", response.getContentType());
        logger.debug("bufferSize: {}", response.getBufferSize());
        logger.debug("locale: {}", response.getLocale());

        bufferdInputStream = new BufferedInputStream(inputStream);
        servletOutputStream = response.getOutputStream();
        bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
        int bytesRead;
        byte buffer[] = new byte[2048];
        while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        // flush stream
        bufferedOutputStream.flush();

        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    } finally {
        // close stream
        inputStream.close();
        bufferdInputStream.close();
        servletOutputStream.close();
        bufferedOutputStream.close();
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ?? ??.//  w  w  w. j av a 2  s.c  o  m
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void view(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    response.setContentType(fileDTO.getContentType());

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ??  ./*from   www  .j  a v  a  2s  .c  om*/
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);
    }

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);

    response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
    sb.setLength(0);
    if (request.getHeader(HttpRequestHeaderConstants.USER_AGENT).indexOf("MSIE5.5") > -1) {
        sb.append("filename=");
    } else {
        sb.append("attachment; filename=");
    }
    sb.append(encodedRealFilename);
    response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());

    logger.debug("header: {}", sb.toString());
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

From source file:org.codelabor.system.file.web.spring.controller.FileController.java

@RequestMapping("/download")
public void download(@RequestHeader("User-Agent") String userAgent, @RequestParam("fileId") String fileId,
        HttpServletResponse response) throws Exception {
    FileDTO fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;

    StringBuilder sb = new StringBuilder();
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.append(repositoryPath);//from w w  w .ja  va  2s .c  o m
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);

    response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
    sb.setLength(0);
    if (userAgent.indexOf("MSIE5.5") > -1) {
        sb.append("filename=");
    } else {
        sb.append("attachment; filename=");
    }
    sb.append(encodedRealFilename);
    response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());
    logger.debug("header: {}", sb.toString());
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

From source file:org.codelabor.system.file.web.spring.controller.FileController.java

@RequestMapping("/view")
public void view(@RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception {
    StringBuilder stringBuilder = null;

    FileDTO fileDTO;//from w ww  .j  a  va  2s.  com
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        stringBuilder = new StringBuilder();
        stringBuilder.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            stringBuilder.append(File.separator);
        }
        stringBuilder.append(uniqueFilename);
        File file = new File(stringBuilder.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    response.setContentType(fileDTO.getContentType());

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

From source file:org.codelabor.system.file.web.struts.action.FileDownloadAction.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug(paramMap.toString());// www .  jav a2s . c o m
    String fileId = (String) paramMap.get("fileId");

    StreamInfo streamInfo = null;
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servlet.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    FileDTO fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();

    StringBuilder sb = new StringBuilder();

    // FILE_SYSTEM
    if (StringUtils.isNotEmpty(repositoryPath)) {
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        streamInfo = new FileStreamInfo(org.codelabor.system.file.FileConstants.CONTENT_TYPE, file);
        // DATABASE
    } else {
        byte[] bytes = fileDTO.getBytes();
        streamInfo = new ByteArrayStreamInfo(org.codelabor.system.file.FileConstants.CONTENT_TYPE, bytes);
    }
    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);

    response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
    sb.setLength(0);
    if (request.getHeader(HttpRequestHeaderConstants.USER_AGENT).indexOf("MSIE5.5") > -1) {
        sb.append("filename=");
    } else {
        sb.append("attachment; filename=");
    }
    // stringBuilder.append("\"");
    sb.append(encodedRealFilename);
    // stringBuilder.append("\"");
    response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());

    logger.debug("header: {}", sb.toString());
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());
    return streamInfo;
}

From source file:org.codelabor.system.file.web.struts.action.FileUploadAction.java

public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServlet().getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;/*from w  w w . ja  va2 s  .  c  om*/
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    response.setContentType(fileDTO.getContentType());

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
    return null;
}

From source file:org.dd4t.mvc.controllers.AbstractBinaryController.java

private void fillResponse(final HttpServletRequest request, final HttpServletResponse response,
        final Binary binary, final String path, int resizeToWidth) throws IOException {
    InputStream content = null;//from  w  ww . java2  s.  c om

    try {
        final long contentLength;
        if (isUseBinaryStorage()) {
            // Check last modified dates
            File binaryFile = new File(path);
            if (!binaryFile.exists() || binary.getLastPublishedDate().isAfter(binaryFile.lastModified())) {
                if (resizeToWidth == -1) {
                    saveBinary(binary, binaryFile);
                } else {
                    File tempBinary = new File(path + ".tmp");
                    saveBinary(binary, tempBinary);
                    content = new FileInputStream(tempBinary);
                    BufferedImage before = ImageIO.read(content);
                    int w = before.getWidth();
                    int h = before.getHeight();
                    float factor = (float) resizeToWidth / w;
                    int newH = Math.round(factor * h);

                    BufferedImage after = new BufferedImage(resizeToWidth, newH, BufferedImage.TYPE_INT_RGB);
                    Graphics g = after.createGraphics();
                    g.drawImage(before, 0, 0, resizeToWidth, newH, null);
                    g.dispose();

                    ImageIO.write(after, getImageType(path), binaryFile);
                }
            }
            content = new FileInputStream(binaryFile);
            contentLength = binaryFile.length();
        } else {
            content = binary.getBinaryData().getInputStream();
            contentLength = binary.getBinaryData().getDataSize();
        }

        response.setContentType(getContentType(binary, path, request));
        response.setHeader(CONTENT_LENGTH, Long.toString(contentLength));
        response.setHeader(LAST_MODIFIED, createDateFormat().format(binary.getLastPublishedDate().toDate()));
        response.setStatus(HttpStatus.OK.value());

        // Write binary data to output stream
        byte[] buffer = new byte[response.getBufferSize()];
        int len;
        while ((len = content.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException e) {
                LOG.error("Failed to close binary input stream", e);
            }
        }
    }
}

From source file:org.nema.medical.mint.server.controller.StudyBinaryItemsController.java

@RequestMapping("/studies/{uuid}/{type}/binaryitems/{seq}")
public void studiesBinaryItems(final HttpServletResponse res, HttpServletRequest req,
        @PathVariable("uuid") final String uuid, @PathVariable("type") final String type,
        @PathVariable("seq") final String seq) throws IOException {

    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;/*ww  w  . ja v a  2  s.  c  o  m*/
    }

    final File studyRoot = new File(studiesRoot, uuid);

    final Iterator<Integer> itemList;
    try {
        itemList = parseItemList(seq, type, studyRoot);
    } catch (final NumberFormatException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid binary item requested: NaN");
        return;
    }

    if (!itemList.hasNext()) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unable to retrieve binary items. See server log for details.");
        LOG.error("Unable to locate binary items: " + seq + " or there are no binary items.");
        return;
    }

    LOG.debug("output buffer size was " + res.getBufferSize());
    res.setBufferSize(binaryItemResponseBufferSize);
    LOG.debug("output buffer size is now " + res.getBufferSize());
    final OutputStream out = res.getOutputStream();

    int i = itemList.next();

    File file = new File(
            studyRoot + "/" + type + "/binaryitems/" + i + "." + StorageUtil.BINARY_FILE_EXTENSION);
    if (!file.exists() || !file.canRead()) {
        final File newFile = new File(studyRoot + "/" + type + "/binaryitems/" + i + "."
                + StorageUtil.EXCLUDED_BINARY_FILE_EXTENSION);
        if (newFile.exists() && newFile.canRead()) {
            file = newFile;
        } else {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Unable to retrieve requested binary items. See server error log.");
            LOG.error("BinaryItemsFile " + file + " does not exist");
            return;
        }
    }

    // write the appropriate header
    final boolean multipart = itemList.hasNext();
    if (multipart) {
        res.setContentType("multipart/x-mixed-replace; boundary=\"" + MP_BOUNDARY + "\"");
        out.write(("--" + MP_BOUNDARY).getBytes());

        final long itemsize = file.length();
        String index = Integer.toString(i);
        out.write("\nContent-Type: application/octet-stream\n".getBytes());
        out.write(("Content-ID: <" + index + "@" + uuid + ">\n").getBytes());
        out.write(("Content-Length: " + itemsize + "\n\n").getBytes());
    } else {
        res.setContentType("application/octet-stream");
        res.setContentLength((int) file.length());
    }

    out.flush();
    streamBinaryItem(file, out, binaryItemStreamBufferSize);

    if (multipart) {
        out.write(("\n--" + MP_BOUNDARY).getBytes());
    }

    for (; itemList.hasNext();) {
        i = itemList.next();

        file = new File(studyRoot + "/" + type + "/binaryitems/" + i + "." + StorageUtil.BINARY_FILE_EXTENSION);
        if (!file.exists() || !file.canRead()) {
            final File newFile = new File(studyRoot + "/" + type + "/binaryitems/" + i + "."
                    + StorageUtil.EXCLUDED_BINARY_FILE_EXTENSION);
            if (newFile.exists() && newFile.canRead()) {
                file = newFile;
            } else {
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Unable to retrieve requested binary items. See server error log.");
                LOG.error("BinaryItemsFile " + file + " does not exist");
                return;
            }

        }

        final long itemsize = file.length();
        String index = Integer.toString(i);
        out.write("\nContent-Type: application/octet-stream\n".getBytes());
        out.write(("Content-ID: <" + index + "@" + uuid + ">\n").getBytes());
        out.write(("Content-Length: " + itemsize + "\n\n").getBytes());

        streamBinaryItem(file, out, binaryItemStreamBufferSize);

        out.write(("\n--" + MP_BOUNDARY).getBytes());
    }

    if (multipart) {
        out.write("--".getBytes());
    }

    out.flush();
}