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:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Get a response Writer depending on acceptable encodings
 * // ww  w .  jav a2  s.  c om
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
public static Writer getWriter(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    Writer out;
    String encodings = request.getHeader("Accept-Encoding");
    if (debug) {
        log.debug("encodings=" + encodings);
    }
    if (encodings != null && encodings.indexOf("gzip") != -1) {
        response.setHeader("Content-Encoding", "gzip");
        out = new OutputStreamWriter(new GZIPOutputStream(response.getOutputStream()), "UTF-8");
    } else if (encodings != null && encodings.indexOf("deflate") != -1) {
        response.setHeader("Content-Encoding", "deflate");
        out = new OutputStreamWriter(new DeflaterOutputStream(response.getOutputStream()), "UTF-8");
    } else {
        out = response.getWriter();
    }
    return out;
}

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

public static void sendFile(DataSource ds, HttpServletResponse response) {
    response.setContentType(ds.getContentType());

    if (ds.getName() != null && ds.getName().length() > 0) {
        response.addHeader("Content-Disposition", "attachment; filename=" + ds.getName());
    }// ww w . j av  a  2 s.  c om

    OutputStream outputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {
        outputStream = response.getOutputStream();

        bufferedInputStream = new BufferedInputStream(ds.getInputStream());
        int readBytes = 0;

        while ((readBytes = bufferedInputStream.read()) != -1) {
            outputStream.write(readBytes);
        }

        if (log.isDebugEnabled()) {
            log.debug("finished sending bytes");
        }

    } catch (IOException ex) {
        log.error("Error serving a file: " + ex.getMessage(), ex);
    } finally {
        if (outputStream != null)
            try {
                outputStream.close();
            } catch (Exception ex) {
            }
        if (bufferedInputStream != null)
            try {
                bufferedInputStream.close();
            } catch (Exception ex) {
            }
    }
}

From source file:de.micromata.genome.gwiki.plugin.vfolder_1_0.GWikiVFolderUtils.java

public static void writeContent(GWikiElement vfolderEl, String filePageId, HttpServletResponse resp)
        throws IOException {

    // resp.setContentType(getContentType());
    String localName = getLocalFromFilePageId(vfolderEl, filePageId);
    GWikiVFolderNode fvn = GWikiVFolderNode.getVFolderFromElement(vfolderEl);

    FsObject file = fvn.getFileSystem().getFileObject(localName);
    if (file.exists() == false) {
        return;//from   ww  w  . j  a v a2  s  .co m
    }
    resp.setContentLength(file.getLength());
    OutputStream os = resp.getOutputStream();
    fvn.getFileSystem().readBinaryFile(localName, os);
}

From source file:com.jaspersoft.jasperserver.war.OlapGetChart.java

/**
 * Binary streams the specified file to the HTTP response in 1KB chunks
 *
 * @param file The file to be streamed./*ww w . ja  v a2 s  .co m*/
 * @param response The HTTP response object.
 * @param mimeType The mime type of the file, null allowed.
 *
 * @throws IOException  if there is an I/O problem.
 * @throws FileNotFoundException  if the file is not found.
 */
public static void sendTempFile(File file, HttpServletResponse response, String mimeType)
        throws IOException, FileNotFoundException {

    if (file.exists()) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        //  Set HTTP headers
        if (mimeType != null) {
            response.setHeader("Content-Type", mimeType);
        }
        response.setHeader("Content-Length", String.valueOf(file.length()));
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        response.setHeader("Last-Modified", sdf.format(new Date(file.lastModified())));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] input = new byte[1024];
        boolean eof = false;
        while (!eof) {
            int length = bis.read(input);
            if (length == -1) {
                eof = true;
            } else {
                bos.write(input, 0, length);
            }
        }
        bos.flush();
        bis.close();
        bos.close();
    } else {
        throw new FileNotFoundException(file.getAbsolutePath());
    }
    return;
}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

/**
 * This method is used to download files from specified path
 * @param response/*from w  ww .  j  a  va 2s .  c  o  m*/
 * @param archiveFile
 */
public static void downloadArchiveFile(HttpServletResponse response, File archiveFile) {
    if (archiveFile.isFile()) {
        response.reset();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + archiveFile.getName() + "\"");
        FileInputStream is = null;
        ServletOutputStream op = null;
        try {
            op = response.getOutputStream();
            double dLength = archiveFile.length();
            int iLength = 0;
            int num_read = 0;

            if (dLength >= Integer.MIN_VALUE && dLength <= Integer.MAX_VALUE) {
                iLength = (int) dLength;
            }
            byte[] arBytes = new byte[iLength];
            is = new FileInputStream(archiveFile);

            while (num_read < iLength) {
                int count = is.read(arBytes, num_read, iLength - num_read);
                if (count < 0) {
                    throw new IOException("end of stream reached");
                }
                num_read += count;
            }
            op.write(arBytes);
            op.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (null != op) {
                try {
                    op.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * Writer/*from   w w w  . ja v a  2 s  .co m*/
 * 
 * @param response
 * @return 
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
public static Writer getResponseWriter(HttpServletResponse response)
        throws UnsupportedEncodingException, IOException {
    Writer writer = null;
    try {
        writer = response.getWriter();
    } catch (IllegalStateException e) {
        String encoding = response.getCharacterEncoding();
        if (encoding == null) {
            encoding = DEFAULT_OUTPUT_ENCODING;
        }
        writer = new OutputStreamWriter(response.getOutputStream(), encoding);
    }
    return writer;
}

From source file:com.lushapp.common.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String displayName,
        byte[] bytes) throws IOException {

    if (ArrayUtils.isEmpty(bytes)) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("??");
        return;//w  w w  .  java2  s.com
    }

    response.reset();
    WebUtils.setNoCacheHeader(response);

    response.setContentType("application/x-download");
    response.setContentLength((int) bytes.length);

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    WebUtils.setDownloadableHeader(request, response, displayFilename);
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new ByteArrayInputStream(bytes));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:fiftyone.mobile.detection.webapp.JavascriptProvider.java

static void sendJavaScript(HttpServletRequest request, HttpServletResponse response, Dataset dataSet,
        StringBuilder javascript) throws IOException {

    response.reset();//ww w  .j  a v a  2 s.co  m
    response.setContentType("application/x-javascript");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Vary", "User-Agent");
    response.setHeader("Cache-Control", "public");
    response.setHeader("Expires", dataSet.nextUpdate.toString());
    response.setHeader("Last-Modified", dataSet.published.toString());
    try {
        response.setHeader("ETag", eTagHash(dataSet, request));
    } catch (Exception ex) {
        // The response doesn't support eTags. Nothing we can do.
    }
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Length", Integer.toString(javascript.length()));

    response.getOutputStream().println(javascript.toString());
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:br.eb.ime.pfc.domain.GeoServerCommunication.java

private static void redirectStream(String urlName, HttpServletRequest request, HttpServletResponse response) {
    URL url = null;/* ww w  .ja  v  a  2 s  .co m*/
    try {
        url = new URL(urlName);
    } catch (MalformedURLException e) {
        //Internal error, the user will receive no data.
        sendError(HTTP_STATUS.BAD_REQUEST, response);
        return;
    }
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Authorization", "Basic " + BASE64_AUTHORIZATION);
        //conn.setRequestMethod("GET");
        //conn.setDoOutput(true);
        conn.connect();
    } catch (IOException e) {
        sendError(HTTP_STATUS.INTERNAL_ERROR, response);
        return;
    }

    try (InputStream is = conn.getInputStream(); OutputStream os = response.getOutputStream()) {
        response.setContentType(conn.getContentType());
        IOUtils.copy(is, os);
    } catch (IOException e) {
        request.getServletContext().log("IO");
        sendError(HTTP_STATUS.INTERNAL_ERROR, response);
        return;
    } finally { //Close connection to save resources
        conn.disconnect();
    }
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ?/*from w  ww .j a v  a  2s .  c  o  m*/
 * 
 * @param files 
 * @param out ?
 * @throws java.io.IOException
 * @throws Exception
 */
public static void zipDownLoad(File file, HttpServletResponse response) throws IOException {

    ServletOutputStream out = response.getOutputStream();
    ZipOutputStream zipout = new ZipOutputStream(out);

    zipout.setLevel(1);
    // zipout.setEncoding("GBK");
    for (File f : file.listFiles()) {
        if (f.isFile()) {
            compressFile(f, f.getName(), zipout, "");
        } else {
            compressFolder(f, f.getName(), zipout, "");
        }
    }

    zipout.finish();
    zipout.flush();
}