Example usage for javax.servlet.http HttpServletResponse getOutputStream

List of usage examples for javax.servlet.http HttpServletResponse getOutputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getOutputStream.

Prototype

public ServletOutputStream getOutputStream() throws IOException;

Source Link

Document

Returns a ServletOutputStream suitable for writing binary data in the response.

Usage

From source file:org.shareok.data.webserv.WebUtil.java

public static void setupFileDownload(HttpServletResponse response, String downloadPath) {
    try {/*from www .  j  av  a2 s . c om*/
        File file = new File(downloadPath);
        if (!file.exists()) {
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
        while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
        response.setHeader("Content-Disposition",
                String.format("attachment; filename=\"" + file.getName() + "\""));

        /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
        //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        //Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException ioex) {
        logger.error("Cannot set up a file download.", ioex);
    }
}

From source file:org.shareok.data.webserv.WebUtil.java

public static void downloadFileFromServer(HttpServletResponse response, String downloadPath) {

    try {/*from w w  w  . j  a  v  a 2 s  .co m*/
        File file = new File(downloadPath);
        if (!file.exists()) {
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
        while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
        response.setHeader("Content-Disposition",
                String.format("attachment; filename=\"" + file.getName() + "\""));

        /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
        //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        //Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException ioex) {
        logger.error("Cannot download file responding to downloading resquest!", ioex);
    }
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for exporting a single module
 * /* w w  w. j a va 2  s  .c  om*/
 * @param module -The module to export
 * @param response
 */
public static void exportSingleModule(Module module, HttpServletResponse response) {
    File file = module.getFile();
    response.setContentLength(new Long(file.length()).intValue());
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    try {
        FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.pactera.edg.am.metamanager.extractor.util.AntZip.java

public static void zipFile(String inputFileName, HttpServletResponse response) {
    try {// ww  w.ja v  a2  s.c  o m
        response.setContentType("text/plain;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=data.zip");
        response.setStatus(HttpServletResponse.SC_OK); //??
        OutputStream output = response.getOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(output);
        zip(zipOut, new File(inputFileName), "");
        if (zipOut != null)
            zipOut.close();
        if (output != null)
            output.close();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    } finally {

    }

}

From source file:com.aurel.track.exchange.docx.exporter.LaTeXExportBL.java

/**
 * Serializes the docx content into the response's output stream
 * @param response/*from ww  w.ja va 2 s .c  o m*/
 * @param wordMLPackage
 * @return
 */
static String prepareReportResponse(HttpServletResponse response, TWorkItemBean workItem,
        ReportBeans reportBeans, TPersonBean user, Locale locale, String templateDir, String templateFile) {
    ReportBeansToLaTeXConverter rl = new ReportBeansToLaTeXConverter();
    File pdf = rl.generatePdf(workItem, reportBeans.getItems(), true, locale, user, "", "", false,
            new File(templateFile), new File(templateDir));

    OutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        InputStream is = new FileInputStream(pdf);
        IOUtils.copy(is, outputStream);
        is.close();
    } catch (FileNotFoundException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.error("Getting the output stream failed with " + e.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }

    return null;
}

From source file:net.sf.appstatus.web.pages.Resources.java

public static void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

    String location = null;/* www.j av a2s .co  m*/
    String id = req.getParameter("resource");
    if (id == null) {
        id = req.getParameter("icon");
    }

    if (resources.containsKey(id)) {
        resp.setContentType(resources.get(id).getMimeType());
        location = resources.get(id).getLocation();
        InputStream is = Resources.class.getResourceAsStream(location);
        IOUtils.copy(is, resp.getOutputStream());
    } else {
        resp.sendError(404);
    }

}

From source file:com.googlecode.psiprobe.Utils.java

public static void sendFile(HttpServletRequest request, HttpServletResponse response, File file)
        throws IOException {
    OutputStream out = response.getOutputStream();
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    try {//from   w  w w  .j  a v a 2 s  .  c  o  m
        long fileSize = raf.length();
        long rangeStart = 0;
        long rangeFinish = fileSize - 1;

        // accept attempts to resume download (if any)
        String range = request.getHeader("Range");
        if (range != null && range.startsWith("bytes=")) {
            String pureRange = range.replaceAll("bytes=", "");
            int rangeSep = pureRange.indexOf("-");

            try {
                rangeStart = Long.parseLong(pureRange.substring(0, rangeSep));
                if (rangeStart > fileSize || rangeStart < 0) {
                    rangeStart = 0;
                }
            } catch (NumberFormatException e) {
                // ignore the exception, keep rangeStart unchanged
            }

            if (rangeSep < pureRange.length() - 1) {
                try {
                    rangeFinish = Long.parseLong(pureRange.substring(rangeSep + 1));
                    if (rangeFinish < 0 || rangeFinish >= fileSize) {
                        rangeFinish = fileSize - 1;
                    }
                } catch (NumberFormatException e) {
                    // ignore the exception
                }
            }
        }

        // set some headers
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Length", Long.toString(rangeFinish - rangeStart + 1));
        response.setHeader("Content-Range", "bytes " + rangeStart + "-" + rangeFinish + "/" + fileSize);

        // seek to the requested offset
        raf.seek(rangeStart);

        // send the file
        byte[] buffer = new byte[4096];

        long len;
        int totalRead = 0;
        boolean nomore = false;
        while (true) {
            len = raf.read(buffer);
            if (len > 0 && totalRead + len > rangeFinish - rangeStart + 1) {
                // read more then required?
                // adjust the length
                len = rangeFinish - rangeStart + 1 - totalRead;
                nomore = true;
            }

            if (len > 0) {
                out.write(buffer, 0, (int) len);
                totalRead += len;
                if (nomore) {
                    break;
                }
            } else {
                break;
            }
        }
    } finally {
        raf.close();
    }
}

From source file:com.liferay.util.servlet.ServletResponseUtil.java

public static void sendFile(HttpServletResponse res, String fileName, byte[] byteArray, String contentType)
        throws IOException {

    _log.debug("Sending file of type " + contentType);

    res.setContentType(contentType);//from www  .j a v  a  2  s  . c om

    res.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.PUBLIC);
    res.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PUBLIC);

    if (Validator.isNotNull(fileName)) {
        res.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
    }

    res.getOutputStream().write(byteArray);
    res.getOutputStream().flush();
}

From source file:com.google.gsa.valve.modules.utils.HTTPAuthZProcessor.java

/**
 * If the document is non HTML, this method processes its content in order to 
 * rewrite the URLs it includes/*from w w w.j a va2  s.c  o  m*/
 * 
 * @param response
 * @param method
 * @throws IOException
 */
public static void processNonHTML(HttpServletResponse response, HttpMethodBase method) throws IOException {

    logger.debug("Processing a non HTML document");

    InputStream is = new BufferedInputStream(method.getResponseBodyAsStream());

    //HTTP Output
    OutputStream os = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_BLOCK_SIZE];
    int read = is.read(buffer);
    while (read >= 0) {
        if (read > 0) {
            os.write(buffer, 0, read);
        }
        read = is.read(buffer);
    }

    //protection
    buffer = null;

    is.close();
    os.close();
}

From source file:jease.site.Streams.java

/**
 * Write given file to response./*from  w  w  w .java2 s  .  c  o m*/
 * 
 * If the given content type denotes a browser supported image, the image
 * will be automatically scaled if either "scale" is present as request
 * paramter or JEASE_IMAGE_LIMIT is set in Registry.
 */
public static void write(HttpServletRequest request, HttpServletResponse response, File file,
        String contentType) throws IOException {
    if (Images.isBrowserCompatible(contentType)) {
        int scale = NumberUtils.toInt(request.getParameter("scale"));
        if (scale > 0) {
            java.io.File scaledImage = Images.scale(file, scale);
            scaledImage.deleteOnExit();
            response.setContentType(contentType);
            response.setContentLength((int) scaledImage.length());
            Files.copy(scaledImage.toPath(), response.getOutputStream());
            return;
        }
        int limit = NumberUtils.toInt(Registry.getParameter(Names.JEASE_IMAGE_LIMIT));
        if (limit > 0) {
            java.io.File scaledImage = Images.limit(file, limit);
            scaledImage.deleteOnExit();
            response.setContentType(contentType);
            response.setContentLength((int) scaledImage.length());
            Files.copy(scaledImage.toPath(), response.getOutputStream());
            return;
        }

    }
    response.setContentType(contentType);
    response.setContentLength((int) file.length());
    Files.copy(file.toPath(), response.getOutputStream());
}