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.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java

private void serializeAll(HttpServletResponse response) {
    try {//www.j  a  v a2 s. com
        List<Ontology> all = ontologyDAO.loadByStatus(EnumSet.of(Status.APPROVED));
        List<Ontology> ontologies = new ArrayList<Ontology>();

        for (Ontology ontology : all) {
            if (!ontology.isCodelist()) {
                ontologies.add(ontology);
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType(MEDIA_TYPE_JSON + ";charset=utf-8");
        response.setHeader("Cache-Control", "public, max-age=0");

        // As per jackson javadocs - Encoding will be UTF-8
        mapper.writeValue(response.getOutputStream(), ontologies);

    } catch (Exception e) {
        log("Failed to serialize ontologies to JSON", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
    }
}

From source file:com.autoupdater.server.controllers.FrontEndAPIController.java

/**
 * Send file to client./*  w ww  .ja  v  a  2 s. com*/
 * 
 * Runs on GET /server/api/download/{updateID} request.
 * 
 * @param updateID
 *            update's ID
 * @param response
 *            response to be sent
 * @param request
 *            received by servlet
 */
@SuppressWarnings("resource")
@RequestMapping(value = "/download/{updateID}", method = GET)
public @ResponseBody void getFile(@PathVariable("updateID") int updateID, HttpServletResponse response,
        HttpServletRequest request) {
    InputStream is = null;
    try {
        logger.debug("Received request: GET /api/download/" + updateID);

        Update update = updateService.findById(updateID);
        if (update == null) {
            logger.debug("Response 404, Update not found for: GET /api/list_updates/" + updateID);
            sendError(response, SC_NOT_FOUND, "Update id=" + updateID + " not found");
            return;
        }

        is = fileService.loadFile(update.getFileData());

        String range = request.getHeader("Range");
        long skip = 0;
        if (range != null) {
            logger.debug("Values of range header : " + range);
            range = range.substring("bytes=".length());
            skip = parseLong(range);

            is.skip(skip);
        }
        response.setContentType(update.getFileType());
        response.setContentLength((int) (update.getFileSize() - skip));

        logger.debug("Sending file on request: GET /api/download/" + updateID);
        copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (NumberFormatException | IOException e) {
        logger.error("Error sending file updateID=" + updateID + ": " + e);
        sendError(response, SC_INTERNAL_SERVER_ERROR, "Couldn't prepare file to send");
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                logger.debug(e);
            }
    }
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

public void handleGet(HttpServletRequest request, HttpServletResponse response, String pathInContext,
        Resource resource, boolean endsWithSlash) throws ServletException, IOException {
    if (resource == null || !resource.exists())
        response.sendError(HttpResponse.__404_Not_Found);
    else {//  w  w w .j  a va 2s.  c  o  m

        // check if directory
        if (resource.isDirectory()) {
            if (!endsWithSlash && !pathInContext.equals("/")) {
                String q = request.getQueryString();
                StringBuffer buf = request.getRequestURL();
                if (q != null && q.length() != 0) {
                    buf.append('?');
                    buf.append(q);
                }
                response.setContentLength(0);
                response.sendRedirect(response.encodeRedirectURL(URI.addPaths(buf.toString(), "/")));
                return;
            }

            // See if index file exists
            String welcome = _httpContext.getWelcomeFile(resource);
            if (welcome != null) {
                String ipath = URI.addPaths(pathInContext, welcome);
                if (_redirectWelcomeFiles) {
                    // Redirect to the index
                    response.setContentLength(0);
                    response.sendRedirect(URI.addPaths(_httpContext.getContextPath(), ipath));
                } else {
                    // Forward to the index
                    RequestDispatcher dispatcher = _servletHandler.getRequestDispatcher(ipath);
                    dispatcher.forward(request, response);
                }
                return;
            }

            // Check modified dates
            if (!passConditionalHeaders(request, response, resource))
                return;

            // If we got here, no forward to index took place
            sendDirectory(request, response, resource, pathInContext.length() > 1);
        } else {
            // Check modified dates
            if (!passConditionalHeaders(request, response, resource))
                return;

            // just send it
            sendData(request, response, pathInContext, resource);
        }
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;/*from w  ww.  jav  a  2s.c  o  m*/
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    String ref = null;
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    //       int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:mx.edu.um.mateo.rh.web.EstudiosEmpleadoController.java

private void generaReporte(String tipo, List<EstudiosEmpleado> estudiosEmpleados, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(estudiosEmpleados);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=EstudiosEmpleado.pdf");
        break;/*from   w ww  . j  a  v a2s.c  om*/
    case "CSV":
        archivo = generaCsv(estudiosEmpleados);
        response.setContentType("text/csv");
        response.addHeader("Content-Disposition", "attachment; filename=EstudiosEmpleado.csv");
        break;
    case "XLS":
        archivo = generaXls(estudiosEmpleados);
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment; filename=EstudiosEmpleado.xls");
    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}

From source file:com.stimulus.archiva.presentation.DownloadLogBean.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String fileName = ((ConfigBean) form).getLogFile();

    if (fileName == null) {
        logger.error("failed to download log file as the filename is null");
        return null;
    }//from  www  .j a v a2s.  co m
    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) {
        String codedfilename = URLEncoder.encode(fileName, "UTF8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        String codedfilename = MimeUtility.encodeText(fileName, "UTF8", "B");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else {
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    }
    File file = ConfigurationService.exportLog(fileName);
    String viewName = fileName.replace(' ', '_') + ".zip";
    logger.debug("download attachment {fileName='" + viewName + "'");
    String contentType = "application/download";
    response.setContentLength((int) file.length());
    Config.getFileSystem().getTempFiles().markForDeletion(file);
    return new FileStreamInfo(contentType, file);
}

From source file:annis.gui.servlets.BinaryServlet.java

private void responseStatus206(WebResource binaryRes, String mimeType, ServletOutputStream out,
        HttpServletResponse response, String range) throws RemoteException, IOException {
    List<AnnisBinaryMetaData> allMeta = binaryRes.path("meta").get(new AnnisBinaryMetaDataListType());

    if (allMeta.size() > 0) {
        AnnisBinaryMetaData bm = allMeta.get(0);
        for (AnnisBinaryMetaData m : allMeta) {
            if (mimeType.equals(m.getMimeType())) {
                bm = m;/*from w  ww  .j a  va  2s  . co  m*/
                break;
            }
        }

        // Range: byte=x-y | Range: byte=0-
        String[] rangeTupel = range.split("-");
        int offset = Integer.parseInt(rangeTupel[0].split("=")[1]);

        int slice;
        if (rangeTupel.length > 1) {
            slice = Integer.parseInt(rangeTupel[1]);
        } else {
            slice = bm.getLength();
        }

        int lengthToFetch = slice - offset;

        response.setHeader("Content-Range",
                "bytes " + offset + "-" + (bm.getLength() - 1) + "/" + bm.getLength());
        response.setContentType(bm.getMimeType());
        response.setStatus(206);
        response.setContentLength(lengthToFetch);

        writeStepByStep(offset, lengthToFetch, binaryRes, out);
    }
}

From source file:architecture.ee.web.community.spring.controller.DownloadController.java

@RequestMapping(value = "/profile/{username}", method = RequestMethod.GET)
@ResponseBody/*ww w. j av a 2  s  .c o  m*/
public void handleProfile(@PathVariable("username") String username,
        @RequestParam(value = "width", defaultValue = "0", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "0", required = false) Integer height,
        HttpServletResponse response) throws IOException {

    log.debug(" ------------------------------------------");
    log.debug("userName:" + username);
    log.debug("width:" + width);
    log.debug("height:" + height);
    log.debug("------------------------------------------");
    try {
        ProfileImage image = profileManager.getProfileImageByUsername(username);
        log.debug("using profile image : " + image.getFilename());
        InputStream input;
        String contentType;
        int contentLength;
        if (width > 0 && width > 0) {
            input = profileManager.getImageThumbnailInputStream(image, width, height);
            contentType = image.getThumbnailContentType();
            contentLength = image.getThumbnailSize();
        } else {
            input = profileManager.getImageInputStream(image);
            contentType = image.getImageContentType();
            contentLength = image.getImageSize();
        }

        response.setContentType(contentType);
        response.setContentLength(contentLength);
        IOUtils.copy(input, response.getOutputStream());
        response.flushBuffer();
    } catch (Exception e) {
        response.setStatus(301);
        String url = ApplicationHelper.getApplicationProperty("components.download.images.no-avatar-url",
                "/images/common/anonymous.png");
        response.addHeader("Location", url);
    }
}

From source file:com.stimulus.archiva.presentation.DownloadBean.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String fileName = request.getParameter("attachment");
    //String fileName = ((MessageBean)form).getAttachment();
    //File file = new File(((MessageBean)form).getAttachmentFilePath());
    String filePath = Config.getFileSystem().getViewPath() + File.separatorChar + fileName;
    File file = new File(filePath);
    logger.debug("download attachment {fileName='" + file.getPath() + "'");
    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) {
        String codedfilename = URLEncoder.encode(fileName, "UTF8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        String codedfilename = MimeUtility.encodeText(fileName, "UTF8", "B");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else {/*from  w ww. ja  v  a2 s .c o m*/
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    }
    String contentType = "application/download";
    response.setContentLength((int) file.length());
    Config.getFileSystem().getTempFiles().markForDeletion(file);
    return new FileStreamInfo(contentType, file);
}