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.qcadoo.mes.basic.controllers.WorkstationMultiUploadController.java

@RequestMapping(value = "/getAttachment.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER,
            BasicConstants.MODEL_WORKSTATION_ATTACHMENT);
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService/* w  w  w  .j ava2 s. com*/
            .getInputStream(attachment.getStringField(WorkstationAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(WorkstationAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(WorkstationAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

From source file:com.qcadoo.mes.basic.controllers.SubassemblyMultiUploadController.java

@RequestMapping(value = "/getAttachmentForSubassembly.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER,
            BasicConstants.MODEL_SUBASSEMBLY_ATTACHMENT);
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService/*from   w w w.jav  a2s  .  com*/
            .getInputStream(attachment.getStringField(SubassemblyAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(SubassemblyAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(SubassemblyAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

From source file:com.yahoo.dba.perf.myperf.springmvc.ReportController.java

private ModelAndView download(Map<String, String> pathParams, HttpServletRequest req, HttpServletResponse resp)
        throws Exception {
    File rootPath = this.frameworkContext.getAlertRootPath();
    String ts = pathParams.get(Constants.URL_PATH_START_TS);
    String dt = this.getDateFromTS(ts);
    File dir = new File(rootPath, dt);
    do {//from ww w.  ja v  a 2  s.  c o m
        if (!dir.exists())
            break;
        String origTS = getOriginalTS(ts);
        File f = new File(dir,
                pathParams.get(Constants.URL_PATH_ALERT_TYPE) + "_" + pathParams.get(Constants.URL_PATH_DBGROUP)
                        + "_" + pathParams.get(Constants.URL_PATH_DBHOST) + "_" + origTS + ".txt");
        if (!f.exists())
            break;
        resp.setContentType("text/plain");
        resp.setContentLength((int) f.length());
        //resp.setHeader("Content-Disposition","attachment; filename=\""+f.getName()+"\"");        
        byte[] buf = new byte[8192];
        int len = 0;
        OutputStream out = resp.getOutputStream();
        InputStream in = null;
        try {
            in = new FileInputStream(f);
            while ((len = in.read(buf)) > 0)
                out.write(buf, 0, len);
        } catch (Exception ex) {

        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (Exception iex) {
            }
            out.flush();
        }
        return null;
    } while (false);

    //if we reach here, something wrong
    ModelAndView mv = new ModelAndView(this.jsonView);
    mv.addObject("json_result", ResultListUtil.toJSONString(null, null, Constants.STATUS_BAD,
            "Cannot find your alert report, try another one."));
    return mv;
}

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

protected void writeHeaders(HttpServletResponse response, Resource resource, long count) throws IOException {
    ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);

    response.setContentType(metaData.getMimeType());
    if (count != -1) {
        if (count == resource.length() && response instanceof ServletHttpResponse)
            response.setHeader(HttpFields.__ContentLength, metaData.getLength());
        else//from   w  w  w.j a va  2  s .c  o  m
            response.setContentLength((int) count);
    }

    response.setHeader(HttpFields.__LastModified, metaData.getLastModified());

    if (_acceptRanges)
        response.setHeader(HttpFields.__AcceptRanges, "bytes");
}

From source file:com.qcadoo.mes.technologies.controller.TechnologyMultiUploadController.java

@RequestMapping(value = "/getAttachment.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER,
            TechnologiesConstants.MODEL_TECHNOLOGY_ATTACHMENT);
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService/*ww w  .ja va  2  s .  c om*/
            .getInputStream(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(TechnologyAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

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

private void export(String ontologyName, boolean includeNonPublicXrefs, String mediaType,
        HttpServletResponse response) {
    OntologyFormat format = mediaTypes.get(mediaType);
    if (format != null) {
        try {/*from   ww w .  ja v a2s  .c  o m*/
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType(mediaType + ";charset=utf-8");
            response.setHeader("Cache-Control", "public, max-age=0");

            exportService.exportOntology(ontologyName, response.getOutputStream(), format,
                    includeNonPublicXrefs);
        } catch (OntologyNotFoundException e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentLength(0);
        } catch (Exception e) {
            log("Failed to export ontology", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    }
}

From source file:com.wxxr.nirvana.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }//from ww w.j  ava2s .  com

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    response.setContentType(
            serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:org.kuali.mobility.sakai.controllers.SakaiController.java

@RequestMapping(value = "/{siteId}/attachment", method = RequestMethod.GET)
public String getAnnouncementAttachment(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("siteId") String siteId, @RequestParam(value = "attachmentId") String attachmentId,
        @RequestParam(value = "type") String type, Model uiModel) {
    User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);

    byte[] fileData = sakaiSiteService.findAnnouncementAttachment(siteId, attachmentId, user.getUserId());

    try {//www  .  jav  a 2 s .c o  m
        if (type.equals(Constants.URL_MIME_TYPE)) {
            String url = new String(fileData);
            response.sendRedirect(response.encodeRedirectURL(url));
        } else {
            response.setContentType(type);
            response.setContentLength(fileData.length);
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + getFileName(attachmentId) + "\"");
            response.getOutputStream().write(fileData, 0, fileData.length);
            return null;
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.Uploader.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   www  .  j  av a 2 s .  c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //  processRequest(request, response);
    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    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");
}