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:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

    if (user != null && queryId != null && !queryId.isEmpty()) {

        try {//  w ww  .j av  a  2s . c o  m

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

            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();
        } catch (Exception ex) {
            logger.error(ex);
        }

    }
}

From source file:com.npower.dl.SoftwareDownloadServlet.java

public void doDownloadJAD(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestUri = request.getRequestURI();
    log.info("Download Service: Download Content: uri: " + requestUri);
    String requestUrl = request.getRequestURL().toString();

    String packageID = parserPackageID(requestUri);
    ManagementBeanFactory factory = null;
    try {//w  w  w  .jav  a2 s .  c  o  m
        factory = ManagementBeanFactory.newInstance(EngineConfig.getProperties());
        SoftwareBean bean = factory.createSoftwareBean();
        SoftwarePackage pkg = bean.getPackageByID(Long.parseLong(packageID));
        if (pkg == null) {
            throw new DMException("Could not found download package by package ID: " + packageID);
        }
        if (pkg.getMimeType().equalsIgnoreCase("text/vnd.sun.j2me.app-descriptor")) {
            // Content is JAD
            InputStream ins = pkg.getBinary().getBinaryBlob().getBinaryStream();
            if (pkg.getSize() > 0) {
                response.setContentType(pkg.getMimeType());
                response.setContentLength(pkg.getSize());
                OutputStream out = response.getOutputStream();
                byte[] buf = new byte[1024];
                int len = ins.read(buf);
                while (len > 0) {
                    out.write(buf, 0, len);
                    len = ins.read(buf);
                }
                out.flush();
                //out.close();
                return;
            }
        } else if (pkg.getMimeType().equalsIgnoreCase("application/java-archive")
                || pkg.getMimeType().equalsIgnoreCase("application/java")
                || pkg.getMimeType().equalsIgnoreCase("application/x-java-archive")) {
            // JAR Format, generate a JAD
            File jarFile = File.createTempFile("software_tmp", "jar");
            InputStream ins = pkg.getBinary().getBinaryBlob().getBinaryStream();
            if (pkg.getSize() > 0) {
                OutputStream out = new FileOutputStream(jarFile);
                byte[] buf = new byte[1024];
                int len = ins.read(buf);
                while (len > 0) {
                    out.write(buf, 0, len);
                    len = ins.read(buf);
                }
                out.flush();
                out.close();

                String url4Jar = StringUtils.replace(requestUrl, ".jad", ".jar");
                JADCreator creator = new JADCreator();
                Manifest manifest = creator.getJADManufest(jarFile, url4Jar);
                response.setContentType(pkg.getMimeType());
                manifest.write(response.getOutputStream());

                // Clean temp file
                jarFile.delete();
                return;
            }
        }
        // Return Not Found Code.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        if (factory != null) {
            factory.release();
        }
    }
}

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

@RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET)
@ResponseBody/*from  w  w w .java2 s .c  o m*/
public void handleImageByLink(@PathVariable("fileName") String fileName,
        @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("fileName:" + fileName);
    log.debug("width:" + width);
    log.debug("height:" + height);
    log.debug("------------------------------------------");

    try {
        Image image = imageManager.getImageByImageLink(fileName);

        InputStream input;
        String contentType;
        int contentLength;

        if (width > 0 && width > 0) {
            input = imageManager.getImageThumbnailInputStream(image, width, height);
            contentType = image.getThumbnailContentType();
            contentLength = image.getThumbnailSize();
        } else {
            input = imageManager.getImageInputStream(image);
            contentType = image.getContentType();
            contentLength = image.getSize();

        }

        response.setContentType(contentType);
        response.setContentLength(contentLength);
        IOUtils.copy(input, response.getOutputStream());
        response.flushBuffer();

    } catch (NotFoundException e) {
        response.sendError(404);
    }
}

From source file:jp.terasoluna.fw.web.struts.actions.FileDownloadUtil.java

/**
 * uEU_E??[h?B/*from   www  .  ja v a2s .  c om*/
 * @param downloadObject _E??[h??B
 * @param request NGXg?B
 * @param response X|X?B
 *
 * @throws IOException _E??[h?oO????B
 */
public static void download(AbstractDownloadObject downloadObject, HttpServletRequest request,
        HttpServletResponse response, boolean forceDownload) throws IOException {

    // downloadObjectnull???A??
    if (downloadObject == null) {
        if (log.isWarnEnabled()) {
            log.warn("No download object.");
        }
        return;
    }

    // wb_??B
    Map<String, List<String>> additionalHeaders = downloadObject.getAdditionalHeaders();

    // wb_?null???A??
    if (additionalHeaders == null) {
        if (log.isWarnEnabled()) {
            log.warn("Header must not be null.");
        }
        return;
    }

    // wb_??B
    Set<Entry<String, List<String>>> entrySet = additionalHeaders.entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        String headerName = entry.getKey();
        List<String> headerValues = entry.getValue();

        // wb_?L?[lXgnull???A??
        if (headerValues == null || headerName == null) {
            if (log.isWarnEnabled()) {
                log.warn("Header name and value must not be null.");
            }
            return;
        }
        for (String headerValue : headerValues) {
            // wb_?lnull
            if (headerValue == null) {
                headerValue = "";
            }
            response.addHeader(headerName, headerValue);
        }
    }

    // GR?[fBO?
    String charSet = downloadObject.getCharset();
    if (StringUtils.isNotEmpty(charSet)) {
        response.setCharacterEncoding(downloadObject.getCharset());
    }

    // Reg^Cv?
    String contentType = downloadObject.getContentType();
    if (StringUtils.isNotEmpty(contentType)) {
        response.setContentType(downloadObject.getContentType());
    }

    // f?[^TCY?
    int contentLength = downloadObject.getLengthOfData();
    if (contentLength > 0) {
        response.setContentLength(downloadObject.getLengthOfData());
    }

    // t@C????A??B
    // ?????B
    String name = downloadObject.getName();
    if (name != null) {
        name = encoder.encode(name, request, response);
    } else {
        name = encoder.encode("", request, response);
    }
    setFileName(response, name, forceDownload);

    InputStream inputStream = downloadObject.getStream();
    OutputStream outputStream = null;

    try {
        // _E??[h???s
        outputStream = response.getOutputStream();
        Streams.copy(inputStream, outputStream, false);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }

}

From source file:com.opencredo.servlet.BookDisplayCoverController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IllegalStateException, IOException {

    // set the content type
    response.setContentType(CONTENT_TYPE);

    // get the ID of the book -- set "bad request" if its not a valid integer
    Integer id;/*from ww w  . ja  v a 2 s  .c  om*/
    try {
        id = ServletRequestUtils.getIntParameter(request, "book");
        if (id == null)
            throw new IllegalStateException("must specify the book id");
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid book");
        return null;
    }

    // get the book from the service
    Book book = bookService.getBook(id);

    // if the book doesn't exist then set "not found"
    if (book == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "no such book");
        return null;
    }

    // if the book doesn't have a picture, set "not found"
    if (book.getCoverPng() == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "book has no image");
        return null;
    }

    if (logger.isDebugEnabled())
        logger.debug("returning cover for book " + book.getKey() + " '" + book.getTitle() + "'" + " size: "
                + book.getCoverPng().length + " bytes");

    // send the image
    response.setContentLength(book.getCoverPng().length);
    response.getOutputStream().write(book.getCoverPng());
    response.getOutputStream().flush();

    // we already handled the response
    return null;
}

From source file:com.qcadoo.report.internal.controller.ReportDevelopmentController.java

@RequestMapping(value = "developReport/generate", method = RequestMethod.POST)
public ModelAndView generateReport(@RequestParam(value = L_TEMPLATE) final String template,
        @RequestParam(value = "type") final String type, @RequestParam(value = L_LOCALE) final String locale,
        final HttpServletRequest request, final HttpServletResponse response) {
    if (!showReportDevelopment) {
        return new ModelAndView(new RedirectView("/"));
    }/* w  ww .  j  ava2 s .  c om*/

    List<ReportParameter> params = null;

    try {
        params = getReportParameters(template);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return showException(L_QCADOO_REPORT_REPORT, e).addObject(L_TEMPLATE, template)
                .addObject("isParameter", true).addObject(L_LOCALE, locale);
    }

    try {
        ReportType reportType = ReportType.valueOf(type.toUpperCase(Locale.ENGLISH));
        Locale reportLocale = new Locale(locale);

        Map<String, Object> parameters = new HashMap<String, Object>();

        for (ReportParameter param : params) {
            param.setValue(request.getParameter("params[" + param.getName() + "]"));
            parameters.put(param.getName(), param.getRawValue());
        }

        byte[] report = reportService.generateReport(template, reportType, parameters, reportLocale);

        response.setContentLength(report.length);
        response.setContentType(reportType.getMimeType());
        response.setHeader("Content-disposition", "attachment; filename=report." + type);
        response.addHeader("Expires", "Tue, 03 Jul 2001 06:00:00 GMT");
        response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.addHeader("Pragma", "no-cache");

        OutputStream out = response.getOutputStream();

        try {
            IOUtils.copy(new ByteArrayInputStream(report), out);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new ReportException(ReportException.Type.ERROR_WHILE_COPYING_REPORT_TO_RESPONSE, e);
        }

        out.flush();

        return null;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return showException(L_QCADOO_REPORT_REPORT, e).addObject(L_TEMPLATE, template)
                .addObject("isParameter", true).addObject(L_PARAMS, params).addObject(L_LOCALE, locale);
    }

}

From source file:de.unirostock.sems.cbarchive.web.servlet.DownloadServlet.java

private void downloadArchive(HttpServletRequest request, HttpServletResponse response, UserManager user,
        String archive) throws IOException {

    // filters for omex extension
    //      ( is just there for the browser to name the downloaded file correctly)
    if (archive.endsWith("." + COMBINEARCHIVE_FILE_EXT))
        // just removes the file extension -> we get the archiveId
        archive = archive.substring(0, archive.length() - (COMBINEARCHIVE_FILE_EXT.length() + 1));

    File archiveFile = null;/*from ww w  . j  a v  a  2s .c o  m*/
    String archiveName = null;
    try {
        archiveFile = user.getArchiveFile(archive);
        archiveName = user.getArchive(archive, false).getName();
    } catch (FileNotFoundException | CombineArchiveWebException e) {
        LOGGER.warn(e, MessageFormat.format(
                "FileNotFound Exception, while handling donwload request for Archive {1} in Workspace {0}",
                user.getWorkingDir(), archive));
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    }

    // set MIME-Type to something downloadable
    response.setContentType("application/octet-stream");

    // set Content-Length
    response.setContentLength((int) archiveFile.length());

    // set the filename of the downloaded file
    response.addHeader("Content-Disposition",
            MessageFormat.format("inline; filename=\"{0}.{1}\"", archiveName, COMBINEARCHIVE_FILE_EXT));

    // print the file to the output stream
    try {
        OutputStream output = response.getOutputStream();
        InputStream input = new FileInputStream(archiveFile);

        // copy the streams
        IOUtils.copy(input, output);

        // flush'n'close
        output.flush();
        output.close();
        input.close();

        response.flushBuffer();
    } catch (IOException e) {
        LOGGER.error(e, MessageFormat.format(
                "IOException, while copying streams by handling donwload request for Archive {1} in Workspace {0}",
                user.getWorkingDir(), archive));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IOException while sending the file.");
    }
}

From source file:siddur.solidtrust.image.ImageController.java

@RequestMapping(value = "/images/{filename:.+}")
public void serveImage(HttpServletRequest req, HttpServletResponse resp,
        @PathVariable("filename") String filename, @RequestParam(value = "s", required = false) String scope)
        throws IOException {
    String filepath = filename;/*from w  ww . ja  va2  s  .c o  m*/
    if (scope != null) {
        filepath = scope + "/" + filepath;
    }
    //404
    File f = new File(FileSystemUtil.getImageDir(), filepath);
    if (!f.exists()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    //304
    long lastModifiedTimestamp = f.lastModified();
    long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    boolean notModified = (ifModifiedSince >= (lastModifiedTimestamp / 1000 * 1000));
    if (notModified) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    } else {
        resp.setDateHeader("Last-Modified", lastModifiedTimestamp);
    }

    //length
    resp.setContentLength((int) f.length());

    //content type
    resp.setContentType("image/jpg");

    //response
    FileCopyUtils.copy(new FileInputStream(f), resp.getOutputStream());
}

From source file:com.krawler.spring.importFunctionality.ImportController.java

public void downloadFileData(HttpServletRequest request, HttpServletResponse response) {
    try {//ww w  .  j  a  v  a 2  s .  c  o  m
        String filename = request.getParameter("filename");
        String storagename = request.getParameter("storagename");
        String filetype = request.getParameter("type");
        String destinationDirectory = storageHandlerImpl.GetDocStorePath();
        destinationDirectory += filetype.equalsIgnoreCase("csv") ? "importplans" : "xlsfiles";
        File intgfile = new File(destinationDirectory + "/" + storagename);
        byte[] buff = new byte[(int) intgfile.length()];

        try {
            FileInputStream fis = new FileInputStream(intgfile);
            int read = fis.read(buff);
        } catch (IOException ex) {
            filename = "file_not_found.txt";
        }

        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setContentType("application/octet-stream");
        response.setContentLength(buff.length);
        response.getOutputStream().write(buff);
        response.getOutputStream().flush();
    } catch (IOException ex) {
        KrawlerLog.op.warn("Unable To Download File :" + ex.toString());
    } catch (Exception ex) {
        KrawlerLog.op.warn("Unable To Download File :" + ex.toString());
    }

}

From source file:cn.lhfei.fu.web.controller.AdminController.java

@RequestMapping(value = "downloadArchive", method = RequestMethod.GET)
public void downloadArchive(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("id") int id) throws IOException {
    try {//  w w w  . jav  a  2s.co m
        ThesisArchive thesisAtchive = thesisArchiveService.read(id);

        if (null != thesisAtchive) {
            String archivePath = thesisAtchive.getArchivePath();
            String[] separatorPaths = archivePath.split("\\" + File.separator);
            String archiveName = separatorPaths[separatorPaths.length - 1];

            File file = new File(archivePath);
            //String fileName = thesisAtchive.getArchiveName();

            // get your file as InputStream
            InputStream is = new FileInputStream(file);
            response.setContentType("application/image;charset=UTF-8");
            response.setContentLength(new Long(file.length()).intValue());
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + archiveName + "; charset=UTF-8");

            // copy it to response's OutputStream
            org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        }
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException("IOError writing file to output stream", ex);
    }
}