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.jamwiki.servlets.ImageServlet.java

/**
 * Serve a file from the filesystem.  This is less efficient than serving the file
 * directly via Tomcat or Apache, but allows files to be stored outside of the
 * webapp and thus keeps wiki data (files) separate from application code.
 *///from   w  ww. ja v a2s.co  m
private void streamFileFromFileSystem(File file, HttpServletResponse response)
        throws ServletException, IOException {
    ServletOutputStream out = null;
    InputStream in = null;
    if (file.isDirectory() || !file.canRead()) {
        logger.debug("File does not exist: " + file.getAbsolutePath());
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
    if (mimeType == null) {
        mimeType = WikiFile.UNKNOWN_MIME_TYPE;
    }
    try {
        response.setContentType(mimeType);
        response.setContentLength((int) file.length());
        out = response.getOutputStream();
        in = new FileInputStream(file);
        IOUtils.copy(in, out);
        out.flush();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

/**
 * Stream an array of bytes to the browser
 * This method will close the ServletOutputStream when finished
 *
 * @param response HttpServletResponse object to get OutputStream from
 * @param bytes Byte array of content to stream
 * @param contentType The content type to pass to the browser
 * @param fileName the fileName to tell the browser we are downloading
 * @throws IOException// w ww.  j  a  v  a  2 s  .  c om
 */
public static void streamContentToBrowser(HttpServletResponse response, byte[] bytes, String contentType,
        String fileName) throws IOException {
    // tell the browser not the cache
    setResponseBrowserProxyNoCache(response);

    // set the response info
    response.setContentLength(bytes.length);
    if (contentType != null) {
        response.setContentType(contentType);
    }
    if (fileName != null) {
        setContentDisposition(response, fileName);
    }

    // create the streams
    OutputStream out = response.getOutputStream();
    InputStream in = new ByteArrayInputStream(bytes);

    // stream the content
    try {
        streamContent(out, in, bytes.length);
    } catch (IOException e) {
        in.close();
        out.close(); // should we close the ServletOutputStream on error??
        throw e;
    }

    // close the input stream
    in.close();

    // close the servlet output stream
    out.flush();
    out.close();
}

From source file:com.eviware.soapui.impl.wsdl.mock.WsdlMockRunner.java

public void returnFile(HttpServletResponse response, File file) throws FileNotFoundException, IOException {
    FileInputStream in = new FileInputStream(file);
    response.setStatus(HttpServletResponse.SC_OK);
    long length = file.length();
    response.setContentLength((int) length);
    response.setContentType(ContentTypeHandler.getContentTypeFromFilename(file.getName()));
    Tools.readAndWrite(in, length, response.getOutputStream());
    in.close();/*from ww w.j a  v a  2  s .c  o m*/
}

From source file:net.duckling.ddl.web.controller.pan.PanShareDownloadController.java

private void sendPreviewDoc(String filename, long size, String panShareId, HttpServletRequest request,
        HttpServletResponse response) {
    OutputStream os = null;/*from   w  w w  .j  a  v  a 2s. c o  m*/
    long p0 = System.currentTimeMillis();
    long tmpSize = size;
    try {
        response.setCharacterEncoding("utf-8");
        String headerValue = ResponseHeaderUtils.buildResponseHeader(request, filename, true);
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", headerValue);
        response.setContentLength((int) size);
        response.setHeader("Content-Length", tmpSize + "");
        os = response.getOutputStream();
        panService.getShareContent(panShareId, null, os);
    } catch (UnsupportedEncodingException e) {
        LOG.error("", e);
    } catch (MeePoException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } catch (Exception e) {
        LOG.error("", e);
    } finally {
        IOUtils.closeQuietly(os);
        long p1 = System.currentTimeMillis();
        LOG.info("Download document[name:" + filename + ",size:" + tmpSize + "] use time " + (p1 - p0));
    }

}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

/**
 * Streams content from InputStream to the ServletOutputStream
 * This method will close the ServletOutputStream when finished
 * This method does not close the InputSteam passed
 *
 * @param response HttpServletResponse object to get OutputStream from
 * @param in InputStream of the actual content
 * @param length Size (in bytes) of the content
 * @param contentType The content type to pass to the browser
 * @throws IOException//  w w w. j  a  va  2s .c  o m
 */
public static void streamContentToBrowser(HttpServletResponse response, InputStream in, int length,
        String contentType, String fileName) throws IOException {
    // tell the browser not the cache
    setResponseBrowserProxyNoCache(response);

    // set the response info
    response.setContentLength(length);
    if (contentType != null) {
        response.setContentType(contentType);
    }
    if (fileName != null) {
        setContentDisposition(response, fileName);
    }

    // stream the content
    OutputStream out = response.getOutputStream();
    try {
        streamContent(out, in, length);
    } catch (IOException e) {
        out.close();
        throw e;
    }

    // close the servlet output stream
    out.flush();
    out.close();
}

From source file:be.fedict.eid.applet.service.PdfServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    EIdData eIdData = (EIdData) httpSession.getAttribute("eid");

    byte[] document;
    try {//from  w  w  w .  ja v a2  s. co  m
        document = this.pdfGenerator.generatePdf(eIdData);
    } catch (DocumentException e) {
        throw new ServletException("PDF generator error: " + e.getMessage(), e);
    }

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

    response.setContentType("application/pdf");
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:be.fedict.eid.applet.service.VcardServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    EIdData eIdData = (EIdData) httpSession.getAttribute("eid");

    byte[] document;
    try {// w  w  w  . ja v a2  s  .c  o m
        document = this.vcardGenerator.generateVcard(eIdData);
    } catch (IOException e) {
        throw new ServletException("vCard generator error: " + e.getMessage(), e);
    }

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

    response.setContentType(VcardLight.MIME_TYPE);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:es.ucm.fdi.storage.web.StorageController.java

@RequestMapping(method = RequestMethod.GET, value = "/storage/**")
public void servirArchivos(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String ctxPath = request.getContextPath();
    String objectId = request.getRequestURI();
    objectId = objectId.substring(ctxPath.length() + "/storage/".length());
    int pos = objectId.indexOf('/');
    if (pos < 0) {
        response.sendError(400, "Upps");
        return;//from   w  w  w .j a v  a  2 s .  c  o m
    }
    String bucket = objectId.substring(0, pos);
    String key = objectId.substring(pos + 1);
    StorageObject object = storage.getObject(bucket, key);
    String mimeType = object.getMimeType();
    long length = object.getContentLength();

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

    try {
        object.transferTo(response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        logger.error("Error writing file to output stream. bucket=>'{}', key=>'{}'", bucket, key, ex);
        response.sendError(500, "Upps");
    }
}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request/*from  w w w .  j a v a 2s .  c om*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();

            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }

            in.close();
            op.flush();
            op.close();
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:com.orangeandbronze.jblubble.sample.PersonController.java

@RequestMapping(method = RequestMethod.GET, value = "/{id}/photo")
public void servePhoto(@PathVariable("id") String id, WebRequest webRequest, HttpServletResponse response)
        throws BlobstoreException, IOException {
    Person person = getPersonById(id);//from   w w w  .j av  a 2 s  .  c  om
    if (person != null) {
        BlobKey photoId = person.getPhotoId();
        if (photoId != null) {
            BlobInfo blobInfo = blobstoreService.getBlobInfo(photoId);
            if (webRequest.checkNotModified(blobInfo.getDateCreated().getTime())) {
                return;
            }
            response.setContentType(blobInfo.getContentType());
            // In Servlet API 3.1, use #setContentLengthLong(long)
            response.setContentLength((int) blobInfo.getSize());
            response.setDateHeader("Last-Modified", blobInfo.getDateCreated().getTime());
            // response.addHeader("Cache-Control", "must-revalidate, max-age=3600");
            blobstoreService.serveBlob(photoId, response.getOutputStream());
            return;
        }
    }
    throw new IllegalArgumentException();
}