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:org.unitedinternet.cosmo.dav.impl.DavCard.java

public void writeHead(final HttpServletResponse response) throws IOException {
    Item content = (Item) getItem();//from  w w  w  . j a va  2 s .  c om
    final byte[] calendar = content.getCalendar().getBytes(StandardCharsets.UTF_8);

    response.setContentType(content.getMimetype());
    response.setContentLength(calendar.length);
    if (getModificationTime() >= 0) {
        response.addDateHeader(LAST_MODIFIED, getModificationTime());
    }
    if (getETag() != null) {
        response.setHeader(ETAG, getETag());
    }
}

From source file:nl.opengeogroep.filesetsync.server.stripes.FilesetGetActionBean.java

public Resolution get() throws Exception {

    Iterable<FileRecord> filesToStream;
    if (FILELIST_MIME_TYPE.equals(getContext().getRequest().getContentType())) {

        InputStream in = getContext().getRequest().getInputStream();
        if ("gzip".equals(getContext().getRequest().getHeader(HttpHeaders.CONTENT_ENCODING))) {
            in = new GZIPInputStream(in);
        }/*from ww w  .  j a  v  a2 s.  c om*/
        List<FileRecord> requestedFiles = Protocol.decodeFilelist(in);
        long totalSize = 0;
        int unacceptableFiles = 0;
        String canonicalFilesetPath = new File(getFileset().getPath()).getCanonicalPath();
        for (FileRecord fr : requestedFiles) {
            File localFile = new File(getLocalSubPath() + File.separator + fr.getName()).getCanonicalFile();

            if (!localFile.getCanonicalPath().startsWith(canonicalFilesetPath)) {
                unacceptableFiles++;
                log.warn("unacceptable file: not under fileset path: " + fr.getName());
                continue;
            } else if (!localFile.exists()
                    || !((localFile.isFile() && localFile.canRead()) || localFile.isDirectory())) {
                unacceptableFiles++;
                log.warn("unacceptable file: not existing, not a readable file or not a directory: "
                        + fr.getName());
                continue;
            }
            fr.setFile(localFile);
            if (localFile.isFile()) {
                totalSize += localFile.length();
            }
        }
        log.info(
                String.format("streaming %d files (total %.0f KB)%s", requestedFiles.size(), totalSize / 1024.0,
                        unacceptableFiles != 0
                                ? ", removed " + unacceptableFiles + " unacceptable requested files"
                                : ""));
        filesToStream = requestedFiles;
    } else {
        // check if path is single file
        final File f = new File(getLocalSubPath());
        if (f.isFile()) {
            return new StreamingResolution("application/octet-stream", new FileInputStream(f)) {
                @Override
                protected void applyHeaders(HttpServletResponse response) {
                    super.applyHeaders(response);
                    response.setContentLength((int) f.length());
                }
            };
        } else if (!f.isDirectory()) {
            return new ErrorMessageResolution("Error: path is not a file or directory");
        }

        log.info("recursively streaming " + getLocalSubPath());
        filesToStream = FileRecord.getFileRecordsInDir(getLocalSubPath(), null, new MutableInt());
    }

    return new MultiFileStreamingResolution(filesToStream);
}

From source file:ee.ria.xroad.proxy.testsuite.testcases.ServerProxyConnectionAborted3.java

@Override
public AbstractHandler getServerProxyHandler() {
    return new AbstractHandler() {
        @Override//from   www  .  ja  v a  2s.c o m
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException {
            // Read all of the request.
            IOUtils.readLines(request.getInputStream());

            response.setContentType("multipart/mixed; boundary=foobar");
            response.setContentLength(1000);
            response.getOutputStream().close();
            response.flushBuffer();
            baseRequest.setHandled(true);
        }
    };
}

From source file:de.itsvs.cwtrpc.security.RpcRedirectStrategy.java

protected void writeResponseText(HttpServletRequest request, HttpServletResponse response,
        String characterEncoding, String responseText) throws IOException {
    final byte[] responseBytes;

    responseBytes = responseText.getBytes(characterEncoding);
    response.setContentLength(responseBytes.length);
    response.getOutputStream().write(responseBytes);
}

From source file:info.toegepaste.www.service.PdfServiceImpl.java

@Override
public void exportPdf(File temp) throws FileNotFoundException, IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.setHeader("Content-Disposition", "attachment; filename=rapport.pdf");
    response.setContentLength((int) temp.length());

    ServletOutputStream out = null;/*ww w.ja  v a  2  s .c  om*/

    FileInputStream input = new FileInputStream(temp);
    byte[] buffer = new byte[1024];
    out = response.getOutputStream();
    int i = 0;
    while ((i = input.read(buffer)) != -1) {
        out.write(buffer);
        out.flush();
    }

    fc.responseComplete();
}

From source file:com.ogaclejapan.dotapk.controller.ApkApiController.java

@RequestMapping(value = "/{name:.+}", method = RequestMethod.GET)
public void download(@PathVariable String name, HttpServletResponse response) throws Exception {
    log.info("download: " + name);

    Resource file = new FileSystemResource(apkManager.getByName(name));
    response.setContentType("application/vnd.android.package-archive");
    response.setContentLength((int) FileUtils.sizeOf(file.getFile()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFile().getName() + "\"");
    FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());

}

From source file:cn.vlabs.clb.server.ui.frameservice.image.handler.GetImageContentHandler.java

private void writeFileContentToResponse(GridFSDBFile dbfile, HttpServletRequest request,
        HttpServletResponse response) {
    OutputStream os = null;/*from  ww w.ja v a  2  s  . co m*/
    try {
        long start = System.currentTimeMillis();
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) dbfile.getLength());
        response.setContentType("application/x-download");
        String filename = dbfile.getFilename();
        if (filename == null) {
            filename = "file" + dbfile.getId();
        }
        String headerValue = ResponseHeaderUtils.buildResponseHeader(request, filename, true);
        response.setHeader("Content-Disposition", headerValue);
        response.setHeader("Content-Length", dbfile.getLength() + "");
        os = response.getOutputStream();
        dbfile.writeTo(os);
        long end = System.currentTimeMillis();
        LOG.info("Read image content using stream mode for image [" + dbfile.getId() + "], use time "
                + (end - start) + "ms");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:com.sr.controller.MahasiswaController.java

@RequestMapping("/lihatfoto")
public void lihatfoto(@RequestParam("nim") String nim, HttpServletRequest request,
        HttpServletResponse response) {
    try {//from w  w  w.jav a 2  s . c  o  m
        Blob blob = mhs.getFotoByNim(nim);
        response.setContentType("image/jpg");
        response.setContentLength((int) blob.length());
        InputStream inputStream = blob.getBinaryStream();
        OutputStream os = response.getOutputStream();
        byte buf[] = new byte[(int) blob.length()];
        inputStream.read(buf);
        os.write(buf);
        os.close();
    } catch (IOException ex) {
        System.out.println("IOException " + ex.getMessage());
    } catch (SQLException ex) {
        System.out.println("SQLException " + ex.getMessage());
    } catch (NullPointerException ex) {
        System.out.println("NullPointerException " + ex.getMessage());
        //buat custom 404 kalau bisa hahahahaha
    }
}

From source file:com.wavemaker.runtime.server.view.DownloadView.java

private void sendDownloadable(Downloadable downloadable, HttpServletResponse response) throws IOException {
    InputStream contents = downloadable.getContents();
    try {/* ww  w . j ava  2s. c  om*/
        response.setContentType(downloadable.getContentType());
        if (downloadable.getContentLength() != null) {
            response.setContentLength(downloadable.getContentLength());
        }
        if (downloadable.getFileName() != null) {
            response.setHeader("Content-disposition",
                    "attachment; filename=\"" + downloadable.getFileName() + "\"");
        }
        IOUtils.copy(contents, response.getOutputStream());
    } finally {
        contents.close();
    }
}

From source file:com.casker.portfolio.controller.FileController.java

/**
 *  //w w  w .  j  ava 2  s.  co  m
 * 
 * @return
 */
@ResponseBody
@RequestMapping("/portfolio/{portfolioNo}/{imageType}")
public void editPassword(HttpServletResponse response, @PathVariable long portfolioNo,
        @PathVariable String imageType) throws Exception {

    Portfolio portfolio = portfolioService.getPortfolioDetail(portfolioNo);

    File file = portfolioService.getImageFile(portfolio, imageType);

    response.setContentLength((int) file.length());

    String fileName = URLEncoder.encode(file.getName(), "utf-8");

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

    InputStream inputStream = new FileInputStream(file);
    IOUtils.copy(inputStream, response.getOutputStream());
    IOUtils.closeQuietly(inputStream);

    response.flushBuffer();
}