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.sshdemo.common.report.manage.web.RepositoryAction.java

public void download() {
    PrintWriter pw = null;/*from   w  w w  .jav a  2 s . c o m*/
    InputStream in = null;
    try {
        if (getRepositoryId() != null) {
            Repository repository = reportFac.findRepositoryById(getRepositoryId());
            String type = repository.getType();
            byte[] bytes = repository.getEntity();

            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentLength(bytes.length);

            if (type.toLowerCase().equals("pdf")) {
                response.setContentType("application/pdf");
            } else if (type.toLowerCase().equals("png")) {
                response.setContentType("image/png");
            }

            pw = response.getWriter();
            in = new ByteArrayInputStream(bytes);
            int len = 0;
            while ((len = in.read()) > -1) {
                pw.write(len);
            }
            pw.flush();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (pw != null) {
            try {
                pw.close();
                pw = null;
            } catch (Exception e) {
            }
        }
        if (in != null) {
            try {
                in.close();
                in = null;
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.nominanuda.springmvc.HttpEntityView.java

public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    response.setContentType(getContentType());
    InputStream is = entity.getContent();
    byte[] b = io.readAndClose(is);
    response.setContentLength(b.length);
    response.getOutputStream().write(b);
}

From source file:org.efs.openreports.actions.ReportViewerAction.java

public String execute() {
    JasperPrint jasperPrint = (JasperPrint) ActionContext.getContext().getSession().get(ORStatics.JASPERPRINT);

    report = (Report) ActionContext.getContext().getSession().get(ORStatics.REPORT);

    if (jasperPrint != null && jasperPrint.getPages() != null) {
        pageCount = jasperPrint.getPages().size();
    }// w  ww  . j  a va 2s .c om

    if (!"image".equals(submitType))
        return SUCCESS;

    byte[] imageData = null;

    if (jasperPrint != null) {
        try {
            BufferedImage image = (BufferedImage) JasperPrintManager.printPageToImage(jasperPrint,
                    pageIndex - 1, zoom);
            imageData = new SunPNGEncoderAdapter().encode(image);
        } catch (Exception e) {
            addActionError(e.getMessage());
            log.error(e.toString());
        }
    }

    if (imageData != null) {

        HttpServletResponse response = ServletActionContext.getResponse();

        try {
            response.setContentLength(imageData.length);
            ServletOutputStream ouputStream = response.getOutputStream();
            ouputStream.write(imageData, 0, imageData.length);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException ioe) {
            log.warn(ioe.toString());
        }
    }

    return NONE;
}

From source file:com.asual.summer.sample.web.TechnologyController.java

@RequestMapping("/image/{value}")
public void image(@PathVariable("value") String value, HttpServletResponse response) throws IOException {
    Image image = Technology.findImage(value);
    if (image != null) {
        response.setContentLength(image.getBytes().length);
        response.setContentType(image.getContentType());
        response.getOutputStream().write(image.getBytes());
    } else {//w w w . j  a v  a  2s .co m
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:org.ktunaxa.referral.server.mvc.InMemoryCmisDocumentView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Document doc = cmisService.getById((String) model.get(DOCUMENT_ID));
    response.setContentType(doc.getContentStreamMimeType());
    response.setContentLength((int) doc.getContentStreamLength());
    if (SAVE.equals((String) model.get(TYPE))) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getName() + "\"");
    }/*from  w  w  w.  j  a  va2  s . c o m*/
    IOUtils.copy(doc.getContentStream().getStream(), response.getOutputStream());
}

From source file:edu.wisc.web.filter.ShallowEtagHeaderFilter.java

private void copyBodyToResponse(byte[] body, HttpServletResponse response) throws IOException {
    response.setContentLength(body.length);
    if (body.length > 0) {
        FileCopyUtils.copy(body, response.getOutputStream());
    }/*from  w w w  . ja va 2  s.  c  o m*/
}

From source file:com.geemvc.view.DefaultStreamViewHandler.java

@Override
public void handle(Result result, RequestContext requestCtx) throws ServletException, IOException {
    HttpServletResponse response = (HttpServletResponse) requestCtx.getResponse();

    if (result.length() > 0) {
        response.setContentLength((int) result.length());
    }/*w  w w  . java  2s . c  om*/

    if (result.filename() != null) {
        if (result.attachment()) {
            response.setHeader("Content-disposition", "attachment; filename=" + result.filename());
        } else {
            response.setHeader("Content-disposition", "filename=" + result.filename());
        }
    }

    if (result.contentType() != null) {
        response.setContentType(result.contentType());
    }

    if (result.rangeSupport()) {
        // TODO: range-support
    }

    if (result.result() != null) {
        RequestHandler requestHandler = requestCtx.requestHandler();
        Method handlerMethod = requestHandler.handlerMethod();

        if (configuration.isJaxRsEnabled()) {
            MessageBodyWriter mbw = injector.getInstance(Providers.class).getMessageBodyWriter(
                    handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(),
                    handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()));

            if (mbw != null
                    && mbw.isWriteable(handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(),
                            handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()))) {
                MultivaluedMap<String, Object> httpResponseHeaders = injector.getInstance(MultivaluedMap.class);

                mbw.writeTo(result.result(), handlerMethod.getReturnType(),
                        handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(),
                        MediaType.valueOf(response.getContentType()), httpResponseHeaders,
                        response.getOutputStream());
            } else {
                response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
            }
        } else {
            log.info(
                    "Unable to convert the result object of type '{}' to the media type '{}' as the JAX-RS runtime has been disabled.",
                    () -> result.result().getClass().getName(), () -> response.getContentType());
            response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

        return;
    }

    if (result.stream() != null) {
        IOUtils.copy(result.stream(), response.getOutputStream());
    } else if (result.reader() != null) {
        IOUtils.copy(result.reader(), response.getOutputStream(), result.characterEncoding());
    } else if (result.output() != null) {
        response.getOutputStream().write(result.output().getBytes());
    } else {
        throw new IllegalStateException(
                "You must provide either a stream, a reader or a string output when using Results.stream(). ");
    }
}

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

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    resp.setContentLength(0);
}

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

@Override
public AbstractHandler getServerProxyHandler() {
    return new AbstractHandler() {
        @Override//from   www  .  j  a  v  a2  s. 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("text/xml");
            response.setContentLength(1000);
            response.getOutputStream().close();
            response.flushBuffer();
            baseRequest.setHandled(true);
        }
    };
}

From source file:eu.planets_project.pp.plato.util.Downloader.java

/**
 * Starts a client side download. All information provided by parameters.
 *
 * @param file data file contains/*from   w  w w .j a  v  a2  s.c o  m*/
 * @param fileName name of the file (e.g. report.pdf)
 * @param contentType mime type of the content to be downloaded
 */
public void download(byte[] file, String fileName, String contentType) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext context = facesContext.getExternalContext();

    HttpServletResponse response = (HttpServletResponse) context.getResponse();
    response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    response.setContentLength((int) file.length);
    response.setContentType(contentType);

    try {
        ByteArrayInputStream in = new ByteArrayInputStream(file);
        OutputStream out = response.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.flush();
        out.close();
        facesContext.responseComplete();
    } catch (IOException ex) {
        log.error("Error in downloadFile: " + ex.getMessage());
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Download couldn't be executed");
        ex.printStackTrace();
    }
}