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:sys.core.manager.RecursosManager.java

public String viewReportePdf(HashMap hmParametros, String reporte, String nombreArchivo)
        throws FileNotFoundException, JRException, IOException, SQLException {
    InputStream ie = null;/*from   ww  w.  j  a  va 2s.  c  o  m*/
    Connection c = null;
    try {
        ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext()
                .getBean("applicationMBean");
        File file = new File(applicationMBean.getRutaJaspers());
        ie = new FileInputStream(new File(file, reporte + ".jasper"));
        c = applicationMBean.obtenerConexionDataBase();
        if (c != null) {
            logger.info("P_DIRECTORIO_REPORTES: " + file.getCanonicalPath() + File.separator);
            hmParametros.put("P_DIRECTORIO_REPORTES", file.getCanonicalPath() + File.separator);
            hmParametros.put(JRParameter.REPORT_LOCALE, new Locale("es_PE"));
            hmParametros.put(JRParameter.REPORT_TIME_ZONE, applicationMBean.getTimeZone());
            JasperPrint jasperPrint = JasperFillManager.fillReport(ie, hmParametros, c);
            logger.info("el jasperProcesado: " + jasperPrint.toString());
            byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.addHeader("Content-disposition", "attachment;filename=" + nombreArchivo);
            response.setContentLength(bytes.length);
            response.getOutputStream().write(bytes);
            response.setContentType("application/pdf");
            context.responseComplete();
        } else {
            logger.error("NO SE PUEDO EJECUTAR LA IMPRESION LA CONEXION ES NULA");
        }

        return null;
    } catch (JRException ex) {
        logger.error("Error al rellenar el reporte " + ex.getMessage());
        logger.error(ex);
    } catch (IOException ex) {
        logger.error("Error al leer el jasper " + ex.getMessage());
        logger.error(ex);
    } catch (Throwable ex) {
        logger.error("Otros errores con el jasper " + ex.getMessage());
        logger.error(ex);
    } finally {
        try {
            if (c != null) {
                c.close();
            }
            if (ie != null) {
                ie.close();
            }
        } catch (IOException ex) {
            logger.error(ex);
        }
        return null;
    }

}

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

@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);

    if (MEDIA_TYPE_JSON.equals(mediaType)) {
        // Preflight CORS support
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        response.setIntHeader("Access-Control-Max-Age", 60 * 60 * 24);
        response.setContentType(mediaType + ";charset=utf-8");
        response.setContentLength(0);
    } else {/*ww w  . j  av  a2  s  . c  om*/
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    }
}

From source file:com.benfante.minimark.controllers.ResultsController.java

@RequestMapping
public void xls(@RequestParam("id") Long id, HttpServletRequest req, HttpServletResponse res, Locale locale) {
    Assessment assessment = assessmentDao.get(id);
    userProfileBo.checkEditAuthorization(assessment);
    List<AssessmentFilling> assessments = assessmentFillingDao
            .findByAssessmentIdOrderByLastNameAndFirstNameAndIdentifier(id);
    OutputStream out = null;/*from w  w  w . j  a va 2  s .  c om*/
    try {
        byte[] xlsBytes = excelResultBuilder.buildXls(assessments, locale);
        out = res.getOutputStream();
        res.setContentType("application/vnd.ms-excel");
        res.setContentLength(xlsBytes.length);
        res.setHeader("Content-Disposition", " attachment; filename=\"" + assessment.getTitle() + ".xls\"");
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        out.write(xlsBytes);
        out.flush();
    } catch (Exception ex) {
        logger.error("Can't build XLS file for " + assessment.getTitle(), ex);
        ex.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:gr.abiss.calipso.tiers.controller.AbstractModelWithAttachmentsController.java

@ApiOperation(value = "Get an uploaded file")
@RequestMapping(value = "{subjectId}/uploads/{propertyName}/files/{id}", method = RequestMethod.GET)
public void getFile(HttpServletResponse response, @PathVariable String subjectId,
        @PathVariable String propertyName, @PathVariable String id) {
    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    BinaryFile file = binaryFileService.findById(id);
    File fileFile = new File(fileUploadDirectory + file.getParentPath() + "/" + file.getNewFilename());
    response.setContentType(file.getContentType());
    response.setContentLength(file.getSize().intValue());
    try {/* w w  w .  j  ava 2  s  . com*/
        InputStream is = new FileInputStream(fileFile);
        IOUtils.copy(is, response.getOutputStream());
    } catch (IOException e) {
        LOGGER.error("Could not show picture " + id, e);
    }
}

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

private void getMetrics(final HttpServletRequest request, final String pathInfo,
        final HttpServletResponse response) throws Exception {
    String queryString = request.getQueryString();
    QueryParam queryParam = getCassandraQueryParam(queryString);
    ListenableFuture<List<RawNumericMetric>> future = metricService.findData(queryParam);

    try {//from  w ww .j  a  va  2 s .  c o m
        List<RawNumericMetric> metrics = future.get(5000, TimeUnit.MILLISECONDS);
        String result = metricResultWriter.writeValueAsString(metrics);
        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:com.github.zhanhb.ckfinder.download.PathPartial.java

private void setContentLengthLong(HttpServletResponse response, long length) {
    if (HAS_METHOD_CONTENT_LENGTH_LONG) {
        response.setContentLengthLong(length);
    } else if (length <= Integer.MAX_VALUE) {
        response.setContentLength((int) length);
    } else {//from   w w w.  j a  v a 2  s. c  o m
        response.setHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(length));
    }
}

From source file:org.shareok.data.webserv.WebUtil.java

public static void setupFileDownload(HttpServletResponse response, String downloadPath) {
    try {/*from   ww w  .  j a va  2 s . co  m*/
        File file = new File(downloadPath);
        if (!file.exists()) {
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
        while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
        response.setHeader("Content-Disposition",
                String.format("attachment; filename=\"" + file.getName() + "\""));

        /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
        //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

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

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        //Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException ioex) {
        logger.error("Cannot set up a file download.", ioex);
    }
}

From source file:gr.abiss.calipso.tiers.controller.AbstractModelWithAttachmentsController.java

@RequestMapping(value = "{subjectId}/uploads/{propertyName}/thumbs/{id}", method = RequestMethod.GET)
@ApiOperation(value = "Get file thumb/preview image of a file upload   ")
public void thumbnail(HttpServletResponse response, @PathVariable String subjectId,
        @PathVariable String propertyName, @PathVariable String id) {
    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    BinaryFile file = binaryFileService.findById(id);
    File fileFile = new File(fileUploadDirectory + file.getParentPath() + "/" + file.getThumbnailFilename());
    response.setContentType(file.getContentType());
    response.setContentLength(file.getThumbnailSize().intValue());
    try {/*from ww  w.  j  a  va2 s .  c  o m*/
        InputStream is = new FileInputStream(fileFile);
        IOUtils.copy(is, response.getOutputStream());
    } catch (IOException e) {
        LOGGER.error("Could not show thumbnail " + id, e);
    }
}

From source file:be.fedict.eid.dss.portal.DownloadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    HttpSession httpSession = request.getSession();
    byte[] document = (byte[]) httpSession.getAttribute(this.documentSessionAttribute);

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    if (false == request.getScheme().equals("https")) {
        // else the download fails in IE
        response.setHeader("Pragma", "no-cache"); // http 1.0
    } else {//from   w  ww . j a  v  a 2s  .  com
        response.setHeader("Pragma", "public");
    }
    response.setDateHeader("Expires", -1);
    response.setContentLength(document.length);

    String contentType = (String) httpSession.getAttribute(this.contentTypeSessionAttribute);
    LOG.debug("content-type: " + contentType);
    response.setContentType(contentType);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}