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:OutSimplePdf.java

public void makePdf(HttpServletRequest request, HttpServletResponse response, String methodGetPost) {
    try {//from   www .j  a va  2 s. c  om
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();
        document.add(new Paragraph("some text"));
        document.close();

        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        response.setContentLength(baos.size());

        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (Exception e2) {
        System.out.println("Error in " + getClass().getName() + "\n" + e2);
    }
}

From source file:org.kaaproject.kaa.sandbox.web.servlet.ProjectFileServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ProjectDataKey key = extractKey(request);
    if (key != null) {
        try {/*from  w  ww  . j a  v a 2s. com*/
            FileData fileData = cacheService.getProjectFile(key);
            if (fileData != null) {
                if (fileData.getContentType() != null) {
                    response.setContentType(fileData.getContentType());
                }
                ServletUtils.prepareDisposition(request, response, fileData.getFileName());
                response.setContentLength(fileData.getFileData().length);
                response.setBufferSize(BUFFER);
                response.getOutputStream().write(fileData.getFileData());
                response.flushBuffer();
            } else {
                logger.error("File data not found in cache for requested parameters: projectId [{}]  type [{}]",
                        key.getProjectId(), key.getProjectDataType());
            }
        } catch (Exception e) {
            logger.error("Unexpected error in ProjectFileServlet.doGet: ", e);
        }
    }
}

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

/**
 * Descargar archivo a travs del FacesContext.
 *
 * @param context/*from w w w .  j av  a 2  s . c o  m*/
 * @param bytes
 * @param nombreArchivo
 */
public void descargarArchivoFacesContext(FacesContext context, byte[] bytes, String nombreArchivo) {
    ExternalContext externalContext = context.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    try {
        if (bytes == null) {
            System.out.println("Bytes nulos en respuesta de PDF");
        } else {
            try (ServletOutputStream servletOutputStream = response.getOutputStream()) {
                response.addHeader("Content-Type", "application/pdf");
                response.addHeader("Content-Disposition", "attachment; filename=" + nombreArchivo + ".pdf");
                response.setContentLength(bytes.length);
                response.setContentType("application/pdf");
                servletOutputStream.write(bytes);
                servletOutputStream.flush();
                context.responseComplete();
            }
        }
    } catch (Exception e) {
        System.out.println("Error enviando archivo PDF, error causado por " + e);
    }
}

From source file:info.magnolia.cms.servlets.ResourceDispatcher.java

/**
 * @param path path for nodedata in jcr repository
 * @param hm   Hierarchy manager/*from  www . ja v  a 2s  .  c om*/
 * @param res  HttpServletResponse
 * @return InputStream or <code>null</code> if nodeData is not found
 */
private InputStream getNodedataAstream(String path, HierarchyManager hm, HttpServletResponse res) {
    if (log.isDebugEnabled()) {
        log.debug("getAtomAsStream for path \"" + path + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }
    try {
        NodeData atom = hm.getNodeData(path);
        if (atom != null) {
            if (atom.getType() == PropertyType.BINARY) {

                String sizeString = atom.getAttribute("size"); //$NON-NLS-1$
                if (NumberUtils.isNumber(sizeString)) {
                    res.setContentLength(Integer.parseInt(sizeString));
                }
            }

            Value value = atom.getValue();
            if (value != null) {
                return value.getStream();
            }
        }

        log.warn("Resource not found: [" + path + "]"); //$NON-NLS-1$ //$NON-NLS-2$

    } catch (PathNotFoundException e) {
        log.warn("Resource not found: [" + path + "]"); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (RepositoryException e) {
        log.error("RepositoryException while reading Resource [" + path + "]", e); //$NON-NLS-1$ //$NON-NLS-2$
    }
    return null;
}

From source file:com.github.matthesrieke.realty.CrawlerServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");

    String itemsMarkup = createGroupedItemsMarkup();
    String content = this.listTemplate.toString().replace("${entries}", itemsMarkup).replace("${meta}",
            createMetaMarkup());//from   w w w  . j a va  2 s .c om

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

    resp.setContentLength(bytes.length);
    resp.setCharacterEncoding("UTF-8");
    resp.setStatus(HttpStatus.SC_OK);

    resp.getOutputStream().write(bytes);
    resp.getOutputStream().flush();
}

From source file:com.doitnext.http.router.RestRouterServlet.java

@Override
public void dumpEndpoints(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    List<String> endpointPaths = new ArrayList<String>();
    for (Route route : this.routes) {
        endpointPaths.add(route.getPathTemplate().getLexicalPath());
    }/*from  ww  w .j  ava  2  s  .  c om*/
    resp.setStatus(200);
    byte bytes[] = objectMapper.writeValueAsBytes(endpointPaths);
    resp.setContentLength(bytes.length);
    resp.setContentType("application/json");
    resp.getOutputStream().write(bytes);
    resp.getOutputStream().close();
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.WebMVCController.java

@RequestMapping(value = "/dowanload/backup/{fileName}", method = { RequestMethod.GET }, produces = {
        "application/zip" })
public void downloadBackup(@PathVariable("fileName") String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {//from w ww . j  av  a2s.  c o  m
        String dir = Configuration.getInstance().getBackupLocation();
        File zip = new File(dir, fileName + ".zip");
        response.setContentType("application/zip");
        response.setContentLength((int) zip.length());
        OutputStream os = response.getOutputStream();
        os.write(IOUtils.toByteArray(new FileInputStream(zip)));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sastix.cms.server.controllers.ResourceController.java

@RequestMapping(value = "/v" + Constants.REST_API_1_0 + "/" + Constants.GET_DATA, method = RequestMethod.POST)
public byte[] getData(@Valid @RequestBody DataDTO dataDTO, HttpServletResponse response, BindingResult result)
        throws ContentValidationException, ResourceAccessError, IOException {
    LOG.trace(Constants.GET_DATA);// w  ww. j a  v a2 s .  co  m
    final Path responseFile = resourceService.getDataPath(dataDTO);
    final byte[] responseData = Files.readAllBytes(responseFile);
    final String mimeType = tika.detect(responseData);
    response.setContentType(mimeType);
    response.setContentLength(responseData.length);
    return responseData;
}

From source file:br.com.hslife.orcamento.controller.ArquivoController.java

public void baixarArquivo() {
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();/*ww  w  .ja v  a2s.c  o  m*/
    try {
        response.setContentType(entity.getContentType());
        response.setHeader("Content-Disposition", "attachment; filename=" + entity.getNomeArquivo());
        response.setContentLength(entity.getDados().length);
        ServletOutputStream output = response.getOutputStream();
        output.write(entity.getDados(), 0, entity.getDados().length);
        FacesContext.getCurrentInstance().responseComplete();
    } catch (Exception e) {
        errorMessage(e.getMessage());
    }
}

From source file:org.n52.sensorweb.series.policy.editor.ctrl.DownloadController.java

/**
 * Method for handling file download request from client
 *//*w  w w  .  j  ava2s  .  c o  m*/
@RequestMapping(method = RequestMethod.GET)
public void doDownload(HttpServletResponse response) throws IOException {

    File downloadFile = new File(permissionsXmlPath);
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    String mimeType = sc.getMimeType(permissionsXmlPath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();

}