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.citrix.cpbm.portal.fragment.controllers.AbstractReportController.java

@RequestMapping(value = "/generate_CSV", method = RequestMethod.POST)
@ResponseBody/*ww  w.  j a  v a 2  s . c  o  m*/
public void generateCSV(@RequestParam(value = "csvdata", required = true) String csvdata, ModelMap modelMap,
        HttpServletResponse response) {
    logger.debug("###Entering generateCSV method @");

    response.setContentType("application/csv");
    response.setHeader("Content-Disposition", "attachment; filename=report.csv");
    response.addHeader("Cache-Control", "no-store, no-cache");
    OutputStream out;
    try {
        out = response.getOutputStream();
        response.setContentLength(csvdata.getBytes().length);
        out.write(csvdata.getBytes());
        out.flush();
        out.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    logger.debug("###Exiting generateCSV method @");
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

public void sendErrorResponse(String content, int errorStatus, HttpServletResponse response)
        throws IOException {

    response.setStatus(errorStatus);/*from   w w  w  . j  a  v a2s  .  c  o  m*/
    response.setCharacterEncoding(GlobalConstants.UTF_8);

    response.setContentType(GlobalConstants.MT_TEXT);

    byte[] bytes = content.getBytes(GlobalConstants.UTF_8);
    response.setContentLength(bytes.length);

    OutputStream os = response.getOutputStream();

    os.write(bytes);
    os.close();

}

From source file:org.esigate.servlet.impl.ResponseSender.java

void sendHeaders(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response) {
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    for (Header header : httpResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        response.addHeader(name, value);
    }//from   w w w.j  a  va 2 s . co  m

    // Copy new cookies
    Cookie[] newCookies = httpRequest.getNewCookies();

    for (int i = 0; i < newCookies.length; i++) {
        response.addHeader("Set-Cookie", CookieUtil.encodeCookie(newCookies[i]));
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        long contentLength = httpEntity.getContentLength();
        if (contentLength > -1 && contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }
        Header contentType = httpEntity.getContentType();
        if (contentType != null) {
            response.setContentType(contentType.getValue());
        }
        Header contentEncoding = httpEntity.getContentEncoding();
        if (contentEncoding != null) {
            response.setHeader(contentEncoding.getName(), contentEncoding.getValue());
        }
    }
}

From source file:com.ebay.pulsar.metric.servlet.MetricRestServlet.java

private void getCounters(final HttpServletRequest request, final String pathInfo,
        final HttpServletResponse response) throws Exception {
    String queryString = request.getQueryString();
    QueryParam queryParam = getCassandraQueryParam(queryString);
    ListenableFuture<List<Counter>> future = metricService.findCounters(
            (String) queryParam.getParameters().get(QueryParam.METRIC_NAME),
            (String) queryParam.getParameters().get(QueryParam.GROUP_ID));
    try {// www  . j  av  a 2 s  .co m
        List<Counter> counters = future.get(5000, TimeUnit.MILLISECONDS);
        String result = counterResultWriter.writeValueAsString(counters);
        response.getWriter().print(result);
        response.setContentLength(result.length());
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (TimeoutException e) {
        response.getWriter().print(QUERY_CASSANDRA_TIMEOUT);
        response.setContentLength(QUERY_CASSANDRA_TIMEOUT.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ExecutionException e) {
        response.getWriter().print(QUERY_CASSANDRA_ERROR);
        response.setContentLength(QUERY_CASSANDRA_ERROR.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:app.controller.ResourceController.java

@GetMapping(value = "/download/{resourceType:.*}")
public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam String filename,
        @PathVariable int resourceType) throws IOException {
    logger.info("---------------download resource-----------------");
    FileResource resource = new FileResource();
    int result = resourceService.download(filename, resourceType, resource);
    if (result != BaseResponse.COMMON_SUCCESS) {
        throw new ResourceNotFoundException();
    }//from   w  w w.  java  2  s . c  o m
    File file = resource.file;

    // get MIME type of the file
    ServletContext context = request.getServletContext();
    String mimeType = context.getMimeType(filename);
    if (mimeType == null) {
        mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
    }

    response.setContentType(mimeType);
    response.setContentLength((int) file.length());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    FileCopyUtils.copy(new BufferedInputStream(new FileInputStream(file)), out);
}

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

public synchronized void handleRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    try {/*from ww w.j  a va 2  s  .c  o m*/
        Thread.sleep(1000);
        String appCommand = req.getParameter("cmd");
        String tsStr = req.getParameter("ts");
        String digest = req.getParameter("digest");
        Check.illegalargument
                .assertTrue(digest.equals(digester.hmacSHA256(appCommand + tsStr).toBase64Classic()));
        DateTime ts = isoFmt.parseDateTime(tsStr);
        Check.illegalargument.assertTrue(ts.plus(timestampValidityMillis).isAfter(new DateTime()));
        if ("refresh_appctx".equals(appCommand)) {
            ((AbstractApplicationContext) applicationContext).refresh();
            res.setContentType(HttpProtocol.CT_TEXT_PLAIN_CS_UTF8);
            res.setContentLength(okMsg.length);
            res.getWriter().write(okMsg);
        } else {
            Check.illegalargument.fail();
        }
    } catch (Exception e) {
        res.setStatus(400);
        res.setContentType(HttpProtocol.CT_TEXT_PLAIN_CS_UTF8);
        res.setContentLength(badReqMsg.length);
        res.getWriter().write(badReqMsg);
    }
}

From source file:it.cilea.osd.jdyna.web.controller.FileServiceController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String idString = request.getPathInfo();
    String[] pathInfo = idString.split("/", 4);

    String folder = pathInfo[3];/*from  w ww  . j a v  a2 s  . c o m*/
    String fileName = request.getParameter("filename");

    File dir = new File(getPath() + File.separatorChar + folder);
    File file = new File(dir, fileName);

    if (file.getCanonicalPath().replace("\\", "/").startsWith(dir.getCanonicalPath().replace("\\", "/"))) {
        if (file.exists()) {
            InputStream is = null;
            try {
                is = new FileInputStream(file);

                response.setContentType(request.getSession().getServletContext().getMimeType(file.getName()));
                Long len = file.length();
                response.setContentLength(len.intValue());
                response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
                FileCopyUtils.copy(is, response.getOutputStream());
                response.getOutputStream().flush();
            } finally {
                if (is != null) {
                    is.close();
                }

            }
        } else {
            throw new RuntimeException("File doesn't exists!");
        }
    } else {
        throw new RuntimeException("No permission to download this file");
    }
    return null;
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.workflow.WorkflowTemplateHandler.java

public void sendFileToClient(HttpServletRequest request, HttpServletResponse response, String zipFileName,
        File workflowXml) {//from   w ww. j  a v  a 2 s .c o  m
    if (request.isSecure()) {
        PageHandler.setHeaderForHTTPSDownload(response);
    }
    FileInputStream fis = null;
    try {
        response.setContentType("application/zip");
        String attachment = "attachment; filename=\"" + UrlUtil.encode(zipFileName, "utf-8") + "\";";
        response.setHeader("Content-Disposition", attachment);
        response.setContentLength((int) workflowXml.length());
        byte[] inBuff = new byte[4096];
        fis = new FileInputStream(workflowXml);
        int bytesRead = 0;
        while ((bytesRead = fis.read(inBuff)) != -1) {
            response.getOutputStream().write(inBuff, 0, bytesRead);
        }

        if (bytesRead > 0) {
            response.getOutputStream().write(inBuff, 0, bytesRead);
        }

        fis.close();
    } catch (IOException e) {
        CATEGORY.error(e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                CATEGORY.error(e);
            }
        }
    }

}

From source file:com.npower.dl.OMADownloadServlet.java

public void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String uri = request.getRequestURI();
    log.info("Download Service: Download Content: uri: " + uri);

    String downloadID = DownloadFactory.parserDownloadID(uri);

    FumoDownloadUpdate download = new FumoDownloadUpdate();
    download.setDownloadID(downloadID);/*from  ww  w  .j a va 2  s  . co m*/
    try {
        byte[] content = download.getContent();
        if (content != null && content.length > 0) {
            log.info("Download Service: Request download ID: " + downloadID + ",Content size: "
                    + content.length);
            response.setContentType(download.getContentType());
            response.setContentLength(content.length);
            OutputStream out = response.getOutputStream();
            out.write(content);
            out.flush();
            //out.close();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
    }
}

From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java

private void setXmlContentInfo(HttpServletResponse responseIn, int lengthIn) {
    // make sure content type is set first!!!
    // otherwise content length gets ignored
    responseIn.setContentType(CONTENT_TYPE_TEXT_XML);
    responseIn.setContentLength(lengthIn);
}