Example usage for javax.servlet.http HttpServletResponse setContentLength

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

Introduction

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

Prototype

public void setContentLength(int len);

Source Link

Document

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

Usage

From source file:com.denimgroup.threadfix.webapp.controller.ToolsDownloadController.java

private String doDownload(HttpServletRequest request, HttpServletResponse response, String jarName) {

    String jarResource = JAR_DOWNLOAD_DIR + jarName;

    InputStream in = request.getServletContext().getResourceAsStream(jarResource);
    if (in == null) {
        exceptionLogService.storeExceptionLog(
                new ExceptionLog(new FileNotFoundException("File not found for download: " + jarResource)));
        return index();
    }/*from   www. ja v a  2  s.c o  m*/

    try {
        ServletOutputStream out = response.getOutputStream();
        int jarSize = request.getServletContext().getResource(jarResource).openConnection().getContentLength();

        if (jarName.endsWith(".jar"))
            response.setContentType("application/java-archive");
        else
            response.setContentType("application/octet-stream");
        ;
        response.setContentLength(jarSize);
        response.addHeader("Content-Disposition", "attachment; filename=\"" + jarName + "\"");

        IOUtils.copy(in, out);
        in.close();
        out.flush();
        out.close();
    } catch (IOException ioe) {
        exceptionLogService.storeExceptionLog(new ExceptionLog(ioe));
        return index();
    }
    return null;
}

From source file:guru.nidi.ramlproxy.core.MockServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final String pathInfo = req.getPathInfo();
    final int pos = pathInfo.lastIndexOf('/');
    final String path = pathInfo.substring(1, pos + 1);
    final String name = pathInfo.substring(pos + 1);
    final ServletOutputStream out = res.getOutputStream();
    final File targetDir = new File(mockDir, path);
    final File file = findFileOrParent(targetDir, name, req.getMethod());
    CommandDecorators.ALLOW_ORIGIN.set(req, res);
    if (file == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No or multiple file '" + name + "' found in directory '" + targetDir.getAbsolutePath() + "'");
        return;// ww w  .j av a 2s. c  o  m
    }
    handleMeta(req, res, file.getParentFile(), file.getName());
    res.setContentLength((int) file.length());
    res.setContentType(mineType(file));
    try (final InputStream in = new FileInputStream(file)) {
        copy(in, out);
    } catch (IOException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem delivering file '" + file.getAbsolutePath() + "': " + e);
    }
    out.flush();
}

From source file:org.gallery.web.controller.ImageController.java

@RequestMapping(value = "/thumbnail/{id}", params = { "size" }, method = RequestMethod.GET)
public void thumbnail(HttpServletResponse response, @PathVariable Long id, @RequestParam("size") int size) {
    ImageEntity entity = imageDao.getById(id);
    ThumbnailSize thumbnail_Enum = ThumbnailSize.valueOf(size);
    log.debug("size: %d", new Object[] { thumbnail_Enum.getSize() });
    String thumbnailFilename = thumbnail_Enum.getId() + entity.getNewFilename() + "."
            + thumbnail_Enum.getFormatName();

    File imageFile = new File(fileUploadDirectory + File.separatorChar + thumbnailFilename);

    response.setContentType("image/" + thumbnail_Enum.getFormatName());
    response.setContentLength((int) imageFile.length());
    try {/*from  w w w  . j  a  v  a2  s  . co  m*/
        InputStream is = new FileInputStream(imageFile);
        IOUtils.copy(is, response.getOutputStream());
        // IOUtils.copy(is, new
        // FileOutputStream("c:\\tmp\\thumbnail-"+thumbnail_Enum.getId()+"."+thumbnail_Enum.getFormatName()));
    } catch (IOException e) {
        log.error("Could not show thumbnail:" + id, e);
    }
}

From source file:de.yaio.services.webshot.server.controller.WebshotProvider.java

public void downloadResultFile(HttpServletRequest request, HttpServletResponse response, File downloadFile)
        throws IOException {
    // construct the complete absolute path of the file
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    ServletContext context = request.getServletContext();
    String mimeType = context.getMimeType(downloadFile.getAbsolutePath());

    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }/*from   w  w  w . j av  a 2s . com*/
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("MIME type: " + mimeType);
    }

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();
}

From source file:com.eryansky.common.web.servlet.RemoteContentServlet.java

private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket//from  w  ww.j a v  a  2 s .  com
    connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
    try {
        connection.connect();

        // ?
        InputStream input;
        try {
            input = connection.getInputStream();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

        // Header
        response.setContentType(connection.getContentType());
        if (connection.getContentLength() > 0) {
            response.setContentLength(connection.getContentLength());
        }

        // 
        OutputStream output = response.getOutputStream();
        try {
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            // ??InputStream.
            IOUtils.closeQuietly(input);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:annis.gui.servlets.BinaryServlet.java

private void responseStatus200(WebResource binaryRes, String mimeType, ServletOutputStream out,
        HttpServletResponse response) throws RemoteException, IOException {

    List<AnnisBinaryMetaData> allMeta = binaryRes.path("meta").get(new AnnisBinaryMetaDataListType());

    if (allMeta.size() > 0) {
        AnnisBinaryMetaData binaryMeta = allMeta.get(0);
        for (AnnisBinaryMetaData m : allMeta) {
            if (mimeType.equals(m.getMimeType())) {
                binaryMeta = m;//  ww w .j a  v a2s  . c om
                break;
            }
        }

        response.setStatus(200);
        response.setHeader("Accept-Ranges", "bytes");
        response.setContentType(binaryMeta.getMimeType());
        response.setHeader("Content-Range",
                "bytes 0-" + (binaryMeta.getLength() - 1) + "/" + binaryMeta.getLength());
        response.setContentLength(binaryMeta.getLength());

        getCompleteFile(binaryRes, mimeType, out);
    }
}

From source file:org.shredzone.cilla.view.ResourceView.java

/**
 * Streams a resource.//from ww  w  .j  ava 2 s. c  o m
 */
@View(pattern = "/resource/${#package}/${#name}", name = "resource")
public void resourceView(@PathPart("#package") String pack, @PathPart("#name") String name,
        HttpServletRequest req, HttpServletResponse resp) throws ViewException {
    if (pack.indexOf("..") > -1 || pack.indexOf('/') > -1 || name.indexOf("..") > -1
            || name.indexOf('/') > -1) {
        throw new PageNotFoundException("resource '" + pack + '/' + name + "' not found");
    }

    try {
        String key = setup(pack, name);

        String resourceEtag = etagMap.get(key);
        resp.setHeader("ETag", resourceEtag);

        String headerEtag = req.getHeader("If-None-Match");

        if (headerEtag != null && headerEtag.equals(resourceEtag)) {
            throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED);
        }

        if (isNotModifiedSince(req, lastModified)) {
            throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED);
        }

        resp.setContentLength(sizeMap.get(key));
        resp.setDateHeader("Last-Modified", lastModified.getTime());

        try (InputStream in = ResourceView.class.getResourceAsStream("/public/" + pack + '/' + name)) {
            FileCopyUtils.copy(in, resp.getOutputStream());
        }

    } catch (IOException ex) {
        throw new PageNotFoundException("resource '" + pack + '/' + name + "' not found");
    }
}

From source file:org.geowebcache.GeoWebCacheDispatcher.java

private void writeFixedResponse(HttpServletResponse response, int httpCode, String contentType,
        Resource resource, CacheResult cacheRes, int contentLength) {

    response.setStatus(httpCode);/* ww  w . j a va 2  s .co m*/
    response.setContentType(contentType);

    response.setContentLength((int) contentLength);
    if (resource != null) {
        try {
            OutputStream os = response.getOutputStream();
            resource.transferTo(Channels.newChannel(os));

            runtimeStats.log(contentLength, cacheRes);

        } catch (IOException ioe) {
            log.debug("Caught IOException: " + ioe.getMessage() + "\n\n" + ioe.toString());
        }
    }
}

From source file:no.dusken.common.view.FileView.java

protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // get the file from the map
    File file = (File) map.get("file");

    // check if it exists
    if (file == null || !file.exists() || !file.canRead()) {
        log.warn("Error reading: {}", file);
        try {// w  ww . ja  v a  2s  .c o  m
            response.sendError(404);
        } catch (IOException e) {
            log.error("Could not write to response", e);
        }
        return;
    }
    // give some info in the response
    String mimeType;
    if (file.getName().contains(".image")) {
        mimeType = "image/jpeg";

    } else {
        mimeType = getServletContext().getMimeType(file.getAbsolutePath());
    }
    response.setContentType(mimeType);
    // files does not change so often, allow three days caching
    response.setHeader("Cache-Control", "public, max-age=2505600");
    response.setContentLength((int) file.length());

    // start writing to the response
    OutputStream outputStream = response.getOutputStream();
    InputStream inputStream = new FileInputStream(file);
    IOUtils.copy(inputStream, outputStream);
}

From source file:cn.lhfei.fu.web.controller.TeacherController.java

/**
 * Method for handling file download request from client
 */// w  ww . jav  a 2  s  .  c o m
@RequestMapping(value = "downloadImg", method = RequestMethod.GET)
public void downloadImg(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id)
        throws IOException {
    try {
        HomeworkArchive homeworkArchive = homeworkArchiveService.read(id);
        if (null != homeworkArchive) {
            File file = new File(homeworkArchive.getArchivePath());
            String fileName = homeworkArchive.getArchiveName();
            //fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
            // get your file as InputStream
            InputStream is = new FileInputStream(file);
            response.setContentType("application/image;charset=UTF-8");
            response.setContentLength(new Long(file.length()).intValue());
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + fileName + ".jpg; charset=UTF-8");

            // copy it to response's OutputStream
            org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        }
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException("IOError writing file to output stream", ex);
    }
}