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:dk.itst.oiosaml.sp.service.LogoutServiceSOAPHandler.java

/**
 * Return the <LogoutResponse> to the caller
 * /*from w  ww .j  av  a  2s.c  o  m*/
 * @param response
 *            The {@link HttpServletResponse}
 * @param logoutResponse
 *            The <LogoutResponse> to return to the caller
 */
private void returnResponse(HttpServletResponse response, OIOLogoutResponse logoutResponse,
        Credential credential) {
    logoutResponse.sign(credential);

    // Build output...
    String envelope = logoutResponse.toSoapEnvelope();

    if (log.isDebugEnabled())
        log.debug("Response..: " + envelope);

    byte[] b;
    try {
        b = envelope.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new WrappedException(Layer.CLIENT, e);
    }
    response.setContentLength(b.length);
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/xml");
    response.setStatus(HttpServletResponse.SC_OK);
    try {
        response.getOutputStream().write(b);
    } catch (IOException e) {
        throw new WrappedException(Layer.CLIENT, e);
    }
}

From source file:in.arun.faces.fo.pdf.FoOutputStream.java

@Override
public void close() throws IOException {
    if (closed) {
        throw new IOException("Stream has already been closed");
    }//from  w w  w.j a v a2 s  . co m

    closed = true;
    PdfResult result = buildPdf(this);

    FacesContext context = FacesContext.getCurrentInstance();

    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

    response.reset();

    String fileName;
    if (null == (fileName = request.getParameter("output"))) {
        fileName = FilenameUtils.getBaseName(request.getRequestURL().toString());
    }

    fileName += ".pdf";

    response.setContentType(result.contentType);
    response.setContentLength(result.content.length);
    response.setHeader("content-disposition", "inline; FileName=\"" + fileName + "\"");

    OutputStream outputStream = response.getOutputStream();
    outputStream.write(result.content);
    outputStream.flush();

    context.responseComplete();
}

From source file:mx.gob.cfe.documentos.web.DepuracionController.java

/**
 * Metodo utilizado para generrar el pdf
 *
 * @param tipo//from  w  w  w .  ja  v a 2  s.  c o  m
 * @param documentos
 * @param response
 * @throws JRException
 * @throws IOException
 */
private void generaReporte(String tipo, List<Documento> documentos, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(documentos);
        response.setContentType("application/pdf");
        Date fecha = new Date();
        response.addHeader("Content-Disposition",
                "attachment; filename=" + fecha.toString() + "depuracion.pdf");
        break;

    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}

From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletResponse response, String currentFileDownloadPath) {
    LOG.info(DOWNLOADING_FILE_FROM_PATH + currentFileDownloadPath);
    DataInputStream inputStream = null;
    ServletOutputStream outStream = null;
    try {/*ww  w  .  j  a va  2 s .c  om*/
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = APPLICATION_OCTET_STREAM;
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName + CLOSING_QUOTES);
        byte[] byteBuffer = new byte[1024];
        inputStream = new DataInputStream(new FileInputStream(file));
        length = inputStream.read(byteBuffer);
        while ((inputStream != null) && (length != -1)) {
            outStream.write(byteBuffer, 0, length);
            length = inputStream.read(byteBuffer);
        }
        LOG.info(DOWNLOAD_COMPLETED_FOR_FILEPATH + currentFileDownloadPath);
    } catch (IOException e) {
        LOG.error(EXCEPTION_OCCURED_WHILE_DOWNLOADING_A_FILE_FROM_THE_FILE_PATH + currentFileDownloadPath);
        LOG.error(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_INPUT_STREAM_FOR_FILE_DOWNLOAD);
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_FLUSH_OUTPUT_STREAM_FOR_DOWNLOAD);
            }
            try {
                outStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_OUTPUT_STREAM_FOR_DOWNLOAD);
            }

        }
    }
}

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

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

    if (mediaType != null) {
        // 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  a va 2s  .c o  m
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    }
}

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

@RequestMapping
public void exportQuestions(@RequestParam("courseId") Long id, HttpServletRequest req,
        HttpServletResponse res) {
    String result = "";
    Course course = courseDao.get(id);/*from  w  ww. j a va2  s.c  o m*/
    if (course == null) {
        throw new RuntimeException("Course not found");
    }
    userProfileBo.checkEditAuthorization(course);
    result = importerBo.exportCourseQuestions(course);
    OutputStream out = null;
    try {
        byte[] contentBytes = result.getBytes("UTF-8");
        out = res.getOutputStream();
        res.setContentType("text/plain");
        res.setContentLength(contentBytes.length);
        res.setHeader("Content-Disposition",
                " attachment; filename=\"" + course.getName() + "_questions.txt\"");
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        out.write(contentBytes);
        out.flush();
    } catch (Exception ex) {
        logger.error("Can't export questions for course " + course.getName() + " (" + course.getId() + ")", ex);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:no.dusken.common.plugin.control.web.PluginResourceController.java

@RequestMapping(value = "/pluginresources.do", method = RequestMethod.GET)
public void get(String path, HttpServletResponse response) throws PageNotFoundException {
    String name = "/no/dusken/plugin/content/" + path;
    String filetype = path.substring(path.lastIndexOf("."));
    boolean isAllowedFiletype = allowedFileTypes.contains(filetype);

    if (!isAllowedFiletype) {
        throw new PageNotFoundException(filetype + " not allowed");
    }/*from www.  j a va  2 s. c  om*/

    InputStream inputStream = getClass().getResourceAsStream(name);

    if (inputStream != null) {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, output);
            response.setContentLength(output.size());
            response.setContentType(getContentType(filetype));
            response.setHeader("Cache-Control", "public, max-age=2505600");
            IOUtils.copy(new ByteArrayInputStream(output.toByteArray()), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        throw new PageNotFoundException(path);
    }
}

From source file:CounterServer.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    int count = 1;
    Integer i = (Integer) session.getAttribute(COUNTER_KEY);
    if (i != null) {
        count = i.intValue() + 5;/*from w  w w  .jav  a 2 s  . c o m*/
    }
    session.setAttribute(COUNTER_KEY, new Integer(count));
    DataInputStream in = new DataInputStream(req.getInputStream());
    resp.setContentType("application/octet-stream");
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.writeInt(count);
    out.flush();
    byte[] buf = byteOut.toByteArray();
    resp.setContentLength(buf.length);
    ServletOutputStream servletOut = resp.getOutputStream();
    servletOut.write(buf);
    servletOut.close();
}

From source file:mx.gob.cfe.documentos.web.DocumentoController.java

private void generaReporte(String tipo, List<Documento> documentos, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(documentos);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=documento.pdf");
        break;/*from w w w.j a  v a  2  s  .c  o m*/

    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}

From source file:net.siegmar.japtproxy.misc.IOHandler.java

protected void setHeader(final HttpServletResponse res, final FetchedResource fetchedResource) {
    final String contentType = fetchedResource.getContentType();
    final long contentLength = fetchedResource.getContentLength();
    final long remoteModification = fetchedResource.getLastModified();

    if (contentType != null) {
        res.setContentType(contentType);
    }/*w  w w  .j  a v a2 s.  co m*/

    if (contentLength != -1) {
        res.setContentLength((int) contentLength);
    }

    if (remoteModification != 0) {
        res.setDateHeader(HttpHeaderConstants.LAST_MODIFIED, remoteModification);
    }
}