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:ru.mystamps.web.controller.ImageController.java

@GetMapping(Url.GET_IMAGE_PAGE)
public void getImage(@PathVariable("id") Integer imageId, HttpServletResponse response) throws IOException {

    if (imageId == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from  w ww .j  a  v  a  2 s.  c o  m
    }

    ImageDto image = imageService.get(imageId);
    if (image == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // TODO: set content disposition
    response.setContentType("image/" + image.getType().toLowerCase());
    response.setContentLength(image.getData().length);

    response.getOutputStream().write(image.getData());
}

From source file:com.all.tracker.controllers.VersionController.java

private void setHeaders(HttpServletResponse response, Version version) throws IOException {
    File updateFile = version.getUpdateFile();
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(APPLICATION_OCTET_STREAM);
    response.setContentLength((int) updateFile.length());
    response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + updateFile.getName());
    response.setHeader(CONTENT_MD5, version.getMd5Checksum());
}

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

private void graph(String termRefId, String mediaType, String orientation, String callback,
        HttpServletResponse response) {
    GraphOrientation graphOrientation = GraphOrientation.TB;

    if (orientation != null) {
        try {//from ww  w .  j  a va2 s.com
            graphOrientation = GraphOrientation.valueOf(orientation);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentLength(0);
            return;
        }
    }

    if (mediaType == null) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
        return;
    }

    try {
        String content = graphService.createGraph(termRefId, graphOrientation);
        // JSONP support
        if (callback != null) {
            StringBuilder builder = new StringBuilder(callback.length() + content.length() + 5);
            builder.append(callback);
            builder.append("(\"");
            builder.append(StringEscapeUtils.escapeJavaScript(content));
            builder.append("\");");
            content = builder.toString();
            mediaType = "application/javascript";
        }

        byte[] contentBytes = content.getBytes("UTF-8");

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType(mediaType + ";charset=utf-8");
        response.setHeader("Cache-Control", "public, max-age=0");
        response.getOutputStream().write(contentBytes);
    } catch (EntityNotFoundException e) {
        log("Failed to find term with reference id: " + termRefId, e);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } catch (Exception e) {
        log("Failed to create graph for term " + termRefId, e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
    }
}

From source file:fr.putnami.pwt.plugin.spring.file.server.controller.FileTransfertController.java

@RequestMapping(value = "/file/download/{fileId}", method = RequestMethod.GET)
public void downloadFile(@PathVariable String fileId, HttpServletRequest request,
        HttpServletResponse response) {
    try {/*w  ww .  ja  v a 2  s  .c  o  m*/
        FileDto fileBean = this.store.getFileBean(fileId);
        if (fileBean == null) {
            throw new RuntimeException("Aucun fichier trouver " + fileId);
        }
        InputStream is = this.store.read(fileId);
        response.setContentType(fileBean.getMime());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileBean.getName() + "\"");
        response.setContentLength((int) fileBean.getContentLength());
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        throw new RuntimeException("IOError writing file to output stream", ex);
    }
}

From source file:com.threewks.thundr.view.jsonp.JsonpViewResolver.java

@Override
public void resolve(HttpServletRequest req, HttpServletResponse resp, JsonpView viewResult) {
    Object output = viewResult.getOutput();
    try {/*from  w  w w . java2 s  .  c o m*/
        Gson create = gsonBuilder.create();
        JsonElement jsonElement = Cast.as(output, JsonElement.class);
        String json = jsonElement == null ? create.toJson(output) : create.toJson(jsonElement);
        String jsonp = wrapJsonInCallback(req, json);

        String encoding = viewResult.getCharacterEncoding();
        resp.setContentLength(jsonp.getBytes(encoding).length);
        BaseView.applyToResponse(viewResult, resp);
        resp.getWriter().write(jsonp);
    } catch (Exception e) {
        throw new ViewResolutionException(e, "Failed to generate JSONP output for object '%s': %s",
                output.toString(), e.getMessage());
    }
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

protected void streamWebService(HttpServletResponse response, String data) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.setContentLength(data.getBytes(Constants.SYSTEM_ENCODING).length);
    OutputStream outputStream = response.getOutputStream();
    outputStream.write(data.getBytes(Constants.SYSTEM_ENCODING));
    outputStream.flush();/* w  w w.ja  va  2  s  .  c  o m*/
}

From source file:com.feilong.servlet.http.ResponseDownloadUtil.java

/**
 *  download response header.// ww w  .j  a v  a 2  s.c  o  m
 *
 * @param saveFileName
 *            the save file name
 * @param contentLength
 *            the content length
 * @param contentType
 *            ?,;,? <code>null</code>,,?? {@link #resolverContentType(String, String)}
 * @param contentDisposition
 *            ?,;,? <code>null</code>,,?? {@link #resolverContentDisposition(String, String)}
 * @param response
 *            the response
 */
private static void setDownloadResponseHeader(String saveFileName, Number contentLength, String contentType,
        String contentDisposition, HttpServletResponse response) {

    //response
    //getResponsegetWriter()??,??,?response.resetresetBuffer.
    //getOutputStream() has already been called for this response
    //jsp??,response.getOutputStream()??:java.lang.IllegalStateException:getOutputStream() has already been called for this response,Exception
    response.reset();

    //*************************************************************************
    response.addHeader(HttpHeaders.CONTENT_DISPOSITION,
            resolverContentDisposition(saveFileName, contentDisposition));

    // ===================== Default MIME Type Mappings =================== -->
    //??,?,????.????,???,
    response.setContentType(resolverContentType(saveFileName, contentType));

    if (isNotNullOrEmpty(contentLength)) {
        response.setContentLength(contentLength.intValue());
    }

    //************************about buffer***********************************************************

    //?:??,?,.
    //??,?:
    //JSP??
    //
    //JSPout.flush()response.flushbuffer()

    //:?,?,???,???.
    //XXX ?? response.setBufferSize(10240); ^_^

    //see org.apache.commons.io.IOUtils.copyLarge(InputStream, OutputStream) javadoc
    //This method buffers the input internally, so there is no need to use a BufferedInputStream
}

From source file:io.manasobi.license.LicenseController.java

@RequestMapping(value = "/download", method = RequestMethod.POST)
@ResponseBody/*from   w  ww.j a v  a 2 s.com*/
public void download(String genKey, HttpServletResponse response) {

    LicenseDetails licenseDetails = licenseService.findLiceseDetails(genKey);

    String licenseKey = licenseDetails.getKey();
    String licenseFileName = licenseDetails.getLicense().getSiteName() + ".cer";

    StringReader reader = new StringReader(licenseKey);
    OutputStream outStream = null;

    try {

        response.setContentLength(licenseKey.length());
        response.setContentType("application/download; utf-8");

        // response header
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", licenseFileName);

        response.setHeader(headerKey, headerValue);

        // Write response
        outStream = response.getOutputStream();

        IOUtils.copy(reader, outStream);

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(outStream);
    }

}

From source file:ee.pri.rl.blog.web.servlet.FileDownloadServlet.java

private void sendFile(String path, String calculatedTag, File directory, HttpServletResponse resp) {
    File file = new File(directory, path);

    String mimeType = getServletContext().getMimeType(path);
    if (mimeType == null) {
        mimeType = "application/octet-stream";
    }//  www .  j a v a2  s  .c  om

    resp.setHeader("ETag", calculatedTag);
    resp.setDateHeader("Date", System.currentTimeMillis());
    resp.setContentType(mimeType);
    resp.setContentLength((int) file.length());
    long liveTime = 3600 * 24 * 30;
    resp.setDateHeader("Expires", System.currentTimeMillis() + liveTime * 1000);
    resp.setHeader("Cache-Control", "public, max-age=" + liveTime);

    try {
        DataInputStream input = new DataInputStream(new FileInputStream(file));
        try {
            IOUtils.copy(input, resp.getOutputStream());
            resp.getOutputStream().flush();
            resp.getOutputStream().close();
        } catch (IOException e) {
            log.warn("Sending " + file + " failed", e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        if (input != null) {
            input.close();
        }
    } catch (IOException e) {
        log.warn("Sending " + file + " failed", e);
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e1) {
            log.warn("Sending response for " + file + " failed");
        }
    }
}