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:gov.nist.appvet.servlet.AppVetServlet.java

private void returnAppVetLog(HttpServletResponse response, String clientIpAddress) {
    try {//from   w  w  w.j a  va 2s. c  o  m
        String appVetLogPath = AppVetProperties.LOG_PATH;
        File logFile = new File(appVetLogPath);
        try {
            if (!logFile.exists()) {
                sendHttpResponse(null, null, null, clientIpAddress, "Could not locate AppVet log", response,
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, true);
                return;
            }
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "inline;filename=appvet_log.txt");
            response.setHeader("Cache-Control", "max-age=0");
            response.setContentLength((int) logFile.length());
            returnFile(response, logFile);
        } finally {
            logFile = null;
            appVetLogPath = null;
        }
    } catch (final Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:net.acesinc.convergentui.BaseFilter.java

protected void addResponseHeaders() {
    RequestContext context = RequestContext.getCurrentContext();
    HttpServletResponse servletResponse = context.getResponse();
    List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders();
    @SuppressWarnings("unchecked")
    List<String> rd = (List<String>) RequestContext.getCurrentContext().get("routingDebug");
    if (rd != null) {
        StringBuilder debugHeader = new StringBuilder();
        for (String it : rd) {
            debugHeader.append("[[[" + it + "]]]");
        }//  ww w.j a  va2 s  .  co  m
        if (INCLUDE_DEBUG_HEADER.get()) {
            servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader.toString());
        }
    }
    if (zuulResponseHeaders != null) {
        for (Pair<String, String> it : zuulResponseHeaders) {
            servletResponse.addHeader(it.first(), it.second());
        }
    }
    RequestContext ctx = RequestContext.getCurrentContext();
    Integer contentLength = ctx.getOriginContentLength();
    // Only inserts Content-Length if origin provides it and origin response is not
    // gzipped
    if (SET_CONTENT_LENGTH.get()) {
        if (contentLength != null && !ctx.getResponseGZipped()) {
            servletResponse.setContentLength(contentLength);
        }
    }
}

From source file:UploadDownloadFile.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);/*  w  w w  .j  a  v  a 2 s.c  om*/
    System.out.println("--> doGet -->");
    String filePath;

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    File file = new File(filePath + File.separator + fileName);

    System.out.println("download file = " + file);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

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

@SuppressWarnings("resource")
public void exportarLancamentos() {
    if (listEntity == null || listEntity.isEmpty()) {
        warnMessage("Listagem vazio. Nada a exportar.");
    }/*w  ww. j  av a2s . co  m*/

    try {

        HSSFWorkbook excel = new HSSFWorkbook();
        HSSFSheet planilha = excel.createSheet("lancamentoConta");

        HSSFRow linha = planilha.createRow(0);

        HSSFCell celula = linha.createCell(0);
        celula.setCellValue("Data");
        celula = linha.createCell(1);
        celula.setCellValue("Histrico");
        celula = linha.createCell(2);
        celula.setCellValue("Valor");

        int linhaIndex = 1;
        for (LancamentoConta l : listEntity) {
            linha = planilha.createRow(linhaIndex);

            celula = linha.createCell(0);
            celula.setCellValue(Util.formataDataHora(l.getDataPagamento(), Util.DATA));

            celula = linha.createCell(1);
            celula.setCellValue(l.getDescricao());

            celula = linha.createCell(2);
            celula.setCellValue(l.getValorPago());

            linhaIndex++;
        }

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=lancamentoConta.xls");
        response.setContentLength(excel.getBytes().length);
        ServletOutputStream output = response.getOutputStream();
        output.write(excel.getBytes(), 0, excel.getBytes().length);
        FacesContext.getCurrentInstance().responseComplete();

    } catch (IOException e) {
        errorMessage(e.getMessage());
    }
}

From source file:com.krawler.spring.crm.caseModule.CrmCustomerCaseController.java

public ModelAndView downloadFile(HttpServletRequest request, HttpServletResponse response) {
    Map model = new HashMap();
    String responseMessage = "";

    try {//  w  w w .  j a va 2 s  .c  o  m
        if ((String) request.getSession().getAttribute(Constants.SESSION_CUSTOMER_ID) != null) {
            String caseId = request.getParameter("caseid");
            String docid = request.getParameter("docid");
            List<Docs> dl = crmCustomerCaseService.getDocument(docid);
            Docs doc = dl.get(0);
            String src = storageHandlerImpl.GetDocStorePath();
            src = src + "/" + doc.getStorename();//ht.get("userid").toString()
            File fp = new File(src);
            byte[] buff = new byte[(int) fp.length()];
            FileInputStream fis = new FileInputStream(fp);
            int read = fis.read(buff);
            javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
            response.setContentType(mmap.getContentType(src));
            response.setContentLength((int) fp.length());
            response.setHeader("Content-Disposition",
                    request.getParameter("dtype") + "; filename=\"" + doc.getDocname() + "\";");
            response.getOutputStream().write(buff);
            response.getOutputStream().flush();
            response.getOutputStream().close();

            request.setAttribute("casedetails", "true");
            request.setAttribute("caseid", caseId);

        } else {
            request.setAttribute("logout", "true");
        }
        responseMessage = "usercases/redirect";
    }

    catch (Exception e) {
        logger.warn(e.getMessage(), e);

    }
    return new ModelAndView(responseMessage, "model", model);
}

From source file:fr.insalyon.creatis.vip.core.server.rpc.GetFileServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from  w  w w. jav  a  2s.  c  o  m
        User user = CoreDAOFactory.getDAOFactory().getUserDAO()
                .getUserBySession(req.getParameter(CoreConstants.COOKIES_SESSION));

        String filepath = req.getParameter("filepath");

        if (filepath != null && !filepath.isEmpty()) {

            File file = new File(Server.getInstance().getWorkflowsPath() + filepath);

            boolean isDir = false;
            if (file.isDirectory()) {
                String zipName = file.getAbsolutePath() + ".zip";
                FolderZipper.zipFolder(file.getAbsolutePath(), zipName);
                filepath = zipName;
                file = new File(zipName);
                isDir = true;
            }

            logger.info("(" + user.getEmail() + ") Downloading file '" + filepath + "'.");
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();

            if (isDir) {
                FileUtils.deleteQuietly(file);
            }
        }

    } catch (DAOException ex) {
        throw new ServletException(ex);
    }
}

From source file:com.flipkart.poseidon.core.PoseidonServlet.java

private void buildResponse(PoseidonRequest request, PoseidonResponse poseidonResponse,
        HttpServletResponse httpResponse) throws BadRequestException, ElementNotFoundException,
        InternalErrorException, ProcessingException, IOException {
    application.handleRequest(request, poseidonResponse);

    setHeaders(poseidonResponse, httpResponse);
    setCookies(poseidonResponse, httpResponse);

    httpResponse.setContentType(poseidonResponse.getContentType().toString());
    int statusCode = poseidonResponse.getStatusCode();
    if (statusCode < 100) {
        statusCode = SC_OK;/*from   ww  w  .ja va2s .co m*/
    }
    httpResponse.setStatus(statusCode);
    Object responseObj = poseidonResponse.getResponse();
    if (responseObj != null) {
        if (responseObj instanceof String) {
            httpResponse.getWriter().println((String) responseObj);
        } else if (responseObj instanceof ByteArrayDataType) {
            byte[] rawBytes = ((ByteArrayDataType) responseObj).getRawBytes();
            // we override default response meta-data as the data is raw bytes
            httpResponse.setContentType(MediaType.OCTET_STREAM.toString());
            httpResponse.setContentLength(rawBytes.length);
            httpResponse.getOutputStream().write(rawBytes);
        } else {
            httpResponse.getWriter().println(configuration.getObjectMapper().writeValueAsString(responseObj));
        }
    }
}

From source file:com.rplt.studioMusik.controller.MemberController.java

@RequestMapping(value = "/cetakNota", method = RequestMethod.GET)
public String cetakNota(HttpServletResponse response) {
    //        Connection conn = DatabaseConnection.getmConnection();
    //            File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file
    File reportFile = new File(
            servletConfig.getServletContext().getRealPath("/resources/report/nota_persewaan.jasper"));

    //        Map<String, Object> params = new HashMap<String, Object>();
    //        params.put("P_KODESEWA", request.getParameter("kodeSewa"));

    byte[] bytes = persewaanStudioMusik.cetakNota(request.getParameter("kodeSewa"), reportFile);
    //        /*  www.  ja  v  a2 s. com*/
    //        try {
    //            bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    //        } catch (JRException ex) {
    //            Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    //        }

    response.setContentType("application/pdf");
    response.setContentLength(bytes.length);

    try {
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes, 0, bytes.length);
        outStream.flush();
        outStream.close();
    } catch (IOException ex) {
        Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "halaman-cetakNota-operator";
}

From source file:org.eurekastreams.server.service.servlets.GetThemeCssServlet.java

/**
 * {@inheritDoc}//from www  .ja va2 s.  c  om
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // grab items from spring context if not initialized, 500 error if unable
    try {
        initializeSpringObjects();
    } catch (Exception e) {
        httpError(HttpStatus.SC_INTERNAL_SERVER_ERROR, response);
        return;
    }

    // Convert request to theme uuid, 400 if error.
    String themeUuid = null;
    try {
        themeUuid = requestUriToThemeUuIdTransformer.transform(request.getRequestURI());

        // StringUtils.isEmpty checks for null or empty string, String.isEmtpy only checks length
        if (StringUtils.isEmpty(themeUuid)) {
            httpError(HttpStatus.SC_BAD_REQUEST, response);
            return;
        }
    } catch (Exception e) {
        httpError(HttpStatus.SC_BAD_REQUEST, response);
        return;
    }

    // get the string css by theme uuid, 404 on error.
    String themeCss = null;
    try {
        themeCss = getThemeCssByUuidMapper.execute(themeUuid);
    } catch (Exception e) {
        httpError(HttpStatus.SC_NOT_FOUND, response);
        return;
    }

    response.setContentType("text/css");
    response.setContentLength(themeCss.getBytes().length);

    PrintWriter out = response.getWriter();
    out.write(themeCss);
    out.flush();
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

private void writeOutResponse(ServiceContext context, String metadataUuid, String lang,
        HttpServletResponse response, FormatType formatType, byte[] formattedMetadata) throws Exception {
    response.setContentType(formatType.contentType);
    String filename = "metadata." + metadataUuid + formatType;
    response.addHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");
    response.setStatus(HttpServletResponse.SC_OK);
    if (formatType == FormatType.pdf) {
        writerAsPDF(context, response, formattedMetadata, lang);
    } else {/* w  w w. ja va 2s  .  c  o  m*/
        response.setCharacterEncoding(Constants.ENCODING);
        response.setContentType("text/html");
        response.setContentLength(formattedMetadata.length);
        response.setHeader("Cache-Control", "no-cache");
        response.getOutputStream().write(formattedMetadata);
    }
}