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:de.iew.raspimotion.controllers.MotionJpegController.java

@RequestMapping(value = "image/{imagename:.+}")
public void imageAction(HttpServletResponse response, @PathVariable String imagename) throws Exception {
    Assert.isTrue(validateImagename(imagename));

    FileDescriptor file = this.fileDao.getFileLastCreated(imagename);

    if (file == null) {
        throw new NoSuchElementException("Image was not found");
    }// w  w  w  .j av  a  2  s . c  o  m

    sendCachingHeaders(response);
    response.setContentType("image/jpeg");
    response.setContentLength(new Long(file.getFilesize()).intValue());

    sendImageAsJpeg(file, response);
}

From source file:alfio.controller.api.admin.ResourceController.java

@RequestMapping(value = "/resource/{name:.*}", method = RequestMethod.GET)
public void outputContent(@PathVariable("name") String name, Principal principal, HttpServletResponse response)
        throws IOException {
    checkAccess(principal);//from   www .j av a  2s  . c  o m
    UploadedResource metadata = uploadedResourceManager.get(name);
    try (OutputStream os = response.getOutputStream()) {
        response.setContentType(metadata.getContentType());
        response.setContentLength(metadata.getContentSize());
        uploadedResourceManager.outputResource(name, os);
    }
}

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

private void sendPreviewDoc(String filename, long size, String remotePath, long version,
        HttpServletRequest request, HttpServletResponse response) {
    OutputStream os = null;/*from  w  w w. j a va  2 s .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.download(PanAclUtil.getInstance(request), remotePath, version, 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.shredzone.cilla.view.AbstractView.java

/**
 * Streams a {@link ResourceDataSource}. Also cares about setting proper HTTP response
 * headers./*ww  w. j a  va 2 s . c o  m*/
 *
 * @param ds
 *            {@link ResourceDataSource} to stream
 * @param req
 *            {@link HttpServletRequest}
 * @param resp
 *            {@link HttpServletResponse}
 */
protected void streamDataSource(ResourceDataSource ds, HttpServletRequest req, HttpServletResponse resp)
        throws ViewException {
    try {
        if (isNotModifiedSince(req, ds.getLastModified())) {
            throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED);
        }

        Long length = ds.getLength();
        if (length != null && length <= Integer.MAX_VALUE) {
            // Converting long to int is safe here...
            resp.setContentLength(length.intValue());
        }

        resp.setContentType(ds.getContentType());
        resp.setDateHeader("Last-Modified", ds.getLastModified().getTime());

        try (InputStream in = ds.getInputStream()) {
            FileCopyUtils.copy(in, resp.getOutputStream());
        }
    } catch (IOException ex) {
        throw new ViewException(ex);
    }
}

From source file:com.springsource.html5expense.controllers.ExpenseReportingApiController.java

@RequestMapping(value = "/receipts/{expenseId}")
public void renderMedia(HttpServletResponse httpServletResponse, OutputStream os,
        @PathVariable("expenseId") Integer expenseId) {

    Expense expense = service.getExpense(expenseId);
    httpServletResponse.setContentType(buildMimeTypeForExpense(expense));

    File f = service.retreiveReceipt(expenseId);
    InputStream is = null;/* www  .  ja  va  2s  .  c o m*/
    try {
        is = new FileInputStream(f);
        httpServletResponse.setContentLength((int) f.length());
        IOUtils.copyLarge(is, os);
    } catch (Exception e1) {
        log.error(e1);
    } finally {
        if (is != null)
            IOUtils.closeQuietly(is);
        if (os != null)
            IOUtils.closeQuietly(os);
    }
}

From source file:flex.messaging.services.http.proxy.ResponseFilter.java

protected void writeResponse(ProxyContext context) {
    try {// w w  w  .ja v  a  2s .  c  o m
        InputStream in = context.getHttpMethod().getResponseBodyAsStream();

        if (in == null) {
            throw new ProxyException(NULL_RESPONSE_STREAM);
        }

        int length = (int) context.getHttpMethod().getResponseContentLength();

        // Stream response directly to client
        if (context.streamResponseToClient()) {
            HttpServletResponse clientResponse = FlexContext.getHttpResponse();

            if (clientResponse != null) {
                OutputStream out = clientResponse.getOutputStream();
                if (length != -1) {
                    clientResponse.setContentLength(length);
                }

                writeStreamedResponse(in, out, context);
            } else {
                throw new ProxyException(CANNOT_STREAM_NOT_HTTP);
            }
        } else {
            writeResponseAsString(in, length, context);
        }
    } catch (IOException ioe) {
        ProxyException pe = new ProxyException();
        pe.setMessage(ERROR_WRITING_RESPONSE, new Object[] { ioe.getMessage() });
        throw pe;
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.TermsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    if (mediaType == null || !MEDIA_TYPE_JSON.equals(mediaType)) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    } else if (pathInfo != null && pathInfo.length() > 1) {
        String referenceId = pathInfo.substring(1);
        serialize(referenceId, response);
    } else {//from www .  j  a  va  2s  . c  o  m
        // perform search using query string params
        String name = StringUtils.trimToNull(request.getParameter("name"));
        String ontology = StringUtils.trimToNull(request.getParameter("ontology"));
        boolean includeSynonyms = Boolean.parseBoolean(request.getParameter("synonyms"));
        int maxResults = Integer.MAX_VALUE;

        try {
            maxResults = Integer.parseInt(request.getParameter("max"));
            if (maxResults <= 0) {
                maxResults = Integer.MAX_VALUE;
            }
        } catch (Exception e) {
            maxResults = Integer.MAX_VALUE;
        }

        serialize(name, ontology, includeSynonyms, maxResults, response);
    }
}

From source file:net.bpelunit.framework.control.ws.WebServiceHandler.java

private void sendResponse(HttpServletResponse response, int code, String body) throws IOException {

    response.setContentType(BPELUnitConstants.TEXT_XML_CONTENT_TYPE);
    response.setStatus(code);//from   w  ww .j av  a  2 s  . c  om

    if (body == null) {
        body = "";
    }
    ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(2048);
    try {
        writer.write(body);
        writer.flush();

        response.setContentLength(writer.size());
        writer.writeTo(response.getOutputStream());
    } finally {
        writer.close();
        writer.destroy();
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java

private void serialize(String ontologyName, HttpServletResponse response) {
    try {/*from   w  w w  .j a  va  2 s .  c o m*/
        Ontology ontology = ontologyDAO.loadByName(ontologyName);
        if (ontology == null || ontology.isCodelist()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentLength(0);
        } else {
            Collection<Term> terms = termDAO.loadAll(ontology);
            OntologyDelegate delegate = new OntologyDelegate(ontology, terms);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType(MEDIA_TYPE_JSON + ";charset=utf-8");
            response.setHeader("Cache-Control", "public, max-age=0");

            // As per jackson javadocs - Encoding will be UTF-8
            mapper.writeValue(response.getOutputStream(), delegate);
        }
    } catch (Exception e) {
        log("Failed to serialize ontology to JSON", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
    }
}

From source file:com.poscoict.license.web.controller.DownloadView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) model.get("downloadFile");

    File file = (File) map.get("file");
    String fileName = "";
    if (map.get("fileName") != null)
        fileName = (String) map.get("fileName");
    else/*  ww w  .ja  v  a 2s  .  c o m*/
        fileName = file.getName();

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

    String header = getBrowser(request);

    if (header.contains("MSIE")) {

        String docName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

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

    } else if (header.contains("Firefox")) {

        String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

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

    } else if (header.contains("Opera")) {

        String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

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

    } else if (header.contains("Chrome")) {

        String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

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

    }

    response.setHeader("Content-Type", "application/octet-stream");

    response.setHeader("Content-Transfer-Encoding", "binary;");

    response.setHeader("Pragma", "no-cache;");

    response.setHeader("Expires", "-1;");

    OutputStream out = response.getOutputStream();
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(file);
        FileCopyUtils.copy(fis, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
            }
        }
    }
    out.flush();
}