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:br.org.ipti.guigoh.util.DownloadService.java

public static synchronized void downloadFile(File file, String mimeType) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext context = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) context.getResponse();
    response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
    response.setContentLength((int) file.length());
    response.setContentType(mimeType);/* w w w  .j a  v a 2  s  .c o m*/
    try {
        OutputStream out;
        try (FileInputStream in = new FileInputStream(file)) {
            out = response.getOutputStream();
            byte[] buf = new byte[(int) file.length()];
            int count;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);
            }
        }
        out.flush();
        out.close();
        facesContext.responseComplete();
    } catch (IOException ex) {
        System.out.println("Error in downloadFile: " + ex.getMessage());
    }
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for exporting a single module
 * /* w w w .j a v a2 s .  c  o  m*/
 * @param module -The module to export
 * @param response
 */
public static void exportSingleModule(Module module, HttpServletResponse response) {
    File file = module.getFile();
    response.setContentLength(new Long(file.length()).intValue());
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    try {
        FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.eryansky.common.web.utils.DownloadUtils.java

/**
 * //from www .  j a v  a  2 s  .c  o m
 * @param request
 * @param response
 * @param inputStream ?
 * @param displayName ??
 * @throws IOException
 */
public static void download(HttpServletRequest request, HttpServletResponse response, InputStream inputStream,
        String displayName) throws IOException {
    response.reset();
    WebUtils.setNoCacheHeader(response);

    response.setContentType("application/x-download");
    response.setContentLength((int) inputStream.available());

    //        String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    //        displayFilename = displayFilename.replace(" ", "_");
    WebUtils.setDownloadableHeader(request, response, displayName);
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(inputStream);
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.display.FileDisplayController.java

public static void showFile(HttpServletResponse response, String path, String fileName, String contentType)
        throws IOException {
    File file = new File(path);
    response.setBufferSize((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

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

    byte[] bytes = new byte[(int) file.length()];
    FileInputStream fis = new FileInputStream(file);
    fis.read(bytes);//from ww  w. j  av  a 2  s. co m
    fis.close();

    FileCopyUtils.copy(bytes, response.getOutputStream());
}

From source file:jease.site.Streams.java

/**
 * Write given file to response.//from  ww w  .ja v a 2s.c  o m
 * 
 * If the given content type denotes a browser supported image, the image
 * will be automatically scaled if either "scale" is present as request
 * paramter or JEASE_IMAGE_LIMIT is set in Registry.
 */
public static void write(HttpServletRequest request, HttpServletResponse response, File file,
        String contentType) throws IOException {
    if (Images.isBrowserCompatible(contentType)) {
        int scale = NumberUtils.toInt(request.getParameter("scale"));
        if (scale > 0) {
            java.io.File scaledImage = Images.scale(file, scale);
            scaledImage.deleteOnExit();
            response.setContentType(contentType);
            response.setContentLength((int) scaledImage.length());
            Files.copy(scaledImage.toPath(), response.getOutputStream());
            return;
        }
        int limit = NumberUtils.toInt(Registry.getParameter(Names.JEASE_IMAGE_LIMIT));
        if (limit > 0) {
            java.io.File scaledImage = Images.limit(file, limit);
            scaledImage.deleteOnExit();
            response.setContentType(contentType);
            response.setContentLength((int) scaledImage.length());
            Files.copy(scaledImage.toPath(), response.getOutputStream());
            return;
        }

    }
    response.setContentType(contentType);
    response.setContentLength((int) file.length());
    Files.copy(file.toPath(), response.getOutputStream());
}

From source file:co.com.realtech.mariner.util.jsf.file.FileDownloader.java

/**
 * Descargar excel a travs del FacesContext.
 *
 * @param context//from  w ww .ja  v  a 2  s.c o m
 * @param bytes
 * @param nombreArchivo
 */
private static void descargarArchivo(FacesContext context, byte[] bytes, String nombreArchivo,
        String extension) {
    ExternalContext externalContext = context.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    try {
        try (ServletOutputStream servletOutputStream = response.getOutputStream()) {
            response.addHeader("Content-Type", "application/" + extension);
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + nombreArchivo + "." + extension);
            response.setContentLength(bytes.length);
            response.setContentType("application/" + extension);
            servletOutputStream.write(bytes);
            servletOutputStream.flush();
            context.responseComplete();
        }
    } catch (Exception e) {
        System.out.println("Error enviando reporte al cliente, error causado por " + e);
    }
}

From source file:com.lushapp.common.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String displayName,
        byte[] bytes) throws IOException {

    if (ArrayUtils.isEmpty(bytes)) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("??");
        return;/* ww w  .  j a  va2 s .  c  o  m*/
    }

    response.reset();
    WebUtils.setNoCacheHeader(response);

    response.setContentType("application/x-download");
    response.setContentLength((int) bytes.length);

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    WebUtils.setDownloadableHeader(request, response, displayFilename);
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new ByteArrayInputStream(bytes));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.ibm.jaggr.core.test.TestUtils.java

public static HttpServletResponse createMockResponse(final Map<String, String> responseAttributes) {
    HttpServletResponse mockResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    mockResponse.setContentLength(EasyMock.anyInt());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() throws Throwable {
            if (responseAttributes != null) {
                responseAttributes.put("Content-Length",
                        ((Integer) EasyMock.getCurrentArguments()[0]).toString());
            }/*from www  .  ja  v a  2  s .  c  o  m*/
            return null;
        }
    }).anyTimes();
    mockResponse.setStatus(EasyMock.anyInt());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() throws Throwable {
            if (responseAttributes != null) {
                responseAttributes.put("Status", ((Integer) EasyMock.getCurrentArguments()[0]).toString());
            }
            return null;
        }
    }).anyTimes();
    EasyMock.expect(mockResponse.getStatus()).andAnswer(new IAnswer<Integer>() {
        @Override
        public Integer answer() throws Throwable {
            int result = 0;
            if (responseAttributes != null) {
                result = Integer.parseInt(responseAttributes.get("Status"));
            }
            return result;
        }
    }).anyTimes();

    return mockResponse;
}

From source file:ee.ria.xroad.common.request.DummyCentralServiceHandler.java

private static void sendErrorResponse(HttpServletResponse response, String faultCode, String faultString,
        String faultActor, String faultDetail) throws IOException {
    String soapMessageXml = SoapFault.createFaultXml(faultCode, faultString, faultActor, faultDetail);

    String encoding = StandardCharsets.UTF_8.name();
    byte[] messageBytes = soapMessageXml.getBytes(encoding);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MimeTypes.TEXT_XML);
    response.setContentLength(messageBytes.length);
    response.setHeader("SOAPAction", "");
    response.setCharacterEncoding(encoding);
    response.getOutputStream().write(messageBytes);
}

From source file:ch.ralscha.extdirectspring.util.ExtDirectSpringUtil.java

/**
 * Checks etag and sends back HTTP status 304 if not modified. If modified sets
 * content type and content length, adds cache headers (
 * {@link #addCacheHeaders(HttpServletResponse, String, Integer)}), writes the data
 * into the {@link HttpServletResponse#getOutputStream()} and flushes it.
 *
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @param data the response data//from  w w  w.  ja v a  2s . c o  m
 * @param contentType the content type of the data (i.e.
 * "application/javascript;charset=UTF-8")
 * @throws IOException
 */
public static void handleCacheableResponse(HttpServletRequest request, HttpServletResponse response,
        byte[] data, String contentType) throws IOException {
    String ifNoneMatch = request.getHeader("If-None-Match");
    String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\"";

    if (etag.equals(ifNoneMatch)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setContentType(contentType);
    response.setContentLength(data.length);

    addCacheHeaders(response, etag, 6);

    @SuppressWarnings("resource")
    ServletOutputStream out = response.getOutputStream();
    out.write(data);
    out.flush();
}