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:com.google.gwtjsonrpc.server.JsonServlet.java

private static void textError(final ActiveCall call, final int status, final String message)
        throws IOException {
    final HttpServletResponse r = call.httpResponse;
    r.setStatus(status);// w ww .  j av  a2  s.c o m
    r.setContentType("text/plain; charset=" + ENC);

    final Writer w = new OutputStreamWriter(r.getOutputStream(), ENC);
    try {
        w.write(message);
    } finally {
        w.close();
    }
}

From source file:edu.harvard.med.screensaver.ui.arch.util.JSFUtils.java

/**
 * Performs the necessary steps to return server-side data, provided as an
 * InputStream, to an HTTP client. Must be called within a JSF-enabled servlet
 * environment.//from  w w w. j  av  a 2 s  . co  m
 *
 * @param facesContext the JSF FacesContext
 * @param dataInputStream an InputStream containing the data to send to the HTTP client
 * @param contentLocation set the "content-location" HTTP header to this value, allowing the downloaded file to be named
 * @param mimeType the MIME type of the file being sent
 * @throws IOException
 */
public static void handleUserDownloadRequest(FacesContext facesContext, InputStream dataInputStream,
        String contentLocation, String mimeType) throws IOException {
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    if (mimeType == null && contentLocation != null) {
        mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(contentLocation);
    }
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    // NOTE: the second line does the trick with the filename. leaving first line in for posterity
    response.setHeader("Content-Location", contentLocation);
    response.setHeader("Content-disposition", "attachment; filename=\"" + contentLocation + "\"");

    OutputStream out = response.getOutputStream();
    IOUtils.copy(dataInputStream, out);
    out.close();

    // skip Render-Response JSF lifecycle phase, since we're generating a
    // non-Faces response
    facesContext.responseComplete();
}

From source file:ispyb.client.common.util.FileUtil.java

/**
 * downloadFile// w  w  w. j  av a2  s  .c  om
 * 
 * @param fullFilePath
 * @param mimeType
 * @param response
 */
public static void DownloadFile(String fullFilePath, String mimeType, String attachmentFilename,
        HttpServletResponse response) {
    try {
        byte[] imageBytes = FileUtil.readBytes(fullFilePath);
        response.setContentLength(imageBytes.length);
        ServletOutputStream out = response.getOutputStream();
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

        out.write(imageBytes);
        out.flush();
        out.close();

    } catch (FileNotFoundException fnf) {
        LOG.debug("[DownloadFile] File not found: " + fullFilePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sunchenbin.store.feilong.servlet.http.ResponseUtil.java

/**
 * Down load data./*w  w w. j  a  v a  2s.c o  m*/
 *
 * @param saveFileName
 *            the save file name
 * @param inputStream
 *            the input stream
 * @param contentLength
 *            the content length
 * @param request
 *            the request
 * @param response
 *            the response
 */
private static void downLoadData(String saveFileName, InputStream inputStream, Number contentLength,
        HttpServletRequest request, HttpServletResponse response) {
    Date beginDate = new Date();

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("begin download~~,saveFileName:[{}],contentLength:[{}]", saveFileName,
                FileUtil.formatSize(contentLength.longValue()));
    }
    try {
        OutputStream outputStream = response.getOutputStream();

        //? 
        //inputStream.read(buffer);
        //outputStream = new BufferedOutputStream(response.getOutputStream());
        //outputStream.write(buffer);

        IOWriteUtil.write(inputStream, outputStream);
        if (LOGGER.isInfoEnabled()) {
            Date endDate = new Date();
            LOGGER.info("end download,saveFileName:[{}],contentLength:[{}],time use:[{}]", saveFileName,
                    FileUtil.formatSize(contentLength.longValue()),
                    DateExtensionUtil.getIntervalForView(beginDate, endDate));
        }
    } catch (IOException e) {
        /*
         * ?  ClientAbortException  ????? 
         * ?? ??
         * ???????
         * ? KILL? ?? ClientAbortException
         */
        //ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error
        final String exceptionName = e.getClass().getName();

        if (StringUtil.contains(exceptionName, "ClientAbortException")
                || StringUtil.contains(e.getMessage(), "ClientAbortException")) {
            LOGGER.warn(
                    "[ClientAbortException],maybe user use Thunder soft or abort client soft download,exceptionName:[{}],exception message:[{}] ,request User-Agent:[{}]",
                    exceptionName, e.getMessage(), RequestUtil.getHeaderUserAgent(request));
        } else {
            LOGGER.error("[download exception],exception name: " + exceptionName, e);
            throw new UncheckedIOException(e);
        }
    }
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportExecuteBL.java

/**
 * Serializes the data source into the response's output stream using a DOM
 * to XML converter/*from w ww  .ja  va  2  s  .com*/
 *
 * @param pluggableDatasouce
 * @param datasource
 * @return
 */
static String prepareDatasourceResponse(HttpServletResponse response, Integer templateID,
        IPluggableDatasource pluggableDatasouce, Map<String, Object> description, Object datasource) {
    // otherwise prepare an XML result
    DownloadUtil.prepareResponse(ServletActionContext.getRequest(), response, "TrackReport.xml", "text/xml");
    try {
        final OutputStream outputStream = response.getOutputStream();
        final String xslt = (String) description.get("xslt");
        if ((datasource != null) && (xslt != null) && (templateID != null)) {
            final File template = ReportBL.getDirTemplate(templateID);
            URL baseURL = null;
            try {
                baseURL = template.toURL();
            } catch (final MalformedURLException e) {
                LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
            if (baseURL != null) {
                final String absolutePathXslt = baseURL.getFile() + xslt;
                try {
                    datasource = XsltTransformer.getInstance().transform((Document) datasource,
                            absolutePathXslt);
                } catch (final Exception e) {
                    LOGGER.warn("Tranforming the datasource with " + absolutePathXslt + " failed with "
                            + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        if (pluggableDatasouce == null) {
            // the default datasource (ReportBeans from last executed query)
            // serialize the DOM object into an XML stream
            ReportBeansToXML.convertToXml(outputStream, (Document) datasource);
        } else {
            // datasource specific serialization
            pluggableDatasouce.serializeDatasource(outputStream, datasource);
        }
    } catch (final Exception e) {
        LOGGER.error("Serializing the datasource to output stream failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));

    }
    return null;
}

From source file:io.druid.server.AsyncQueryForwardingServlet.java

private static void handleException(HttpServletResponse response, ObjectMapper objectMapper,
        Exception exception) throws IOException {
    if (!response.isCommitted()) {
        final String errorMessage = exception.getMessage() == null ? "null exception" : exception.getMessage();

        response.resetBuffer();//from   ww  w. java 2  s.  co  m
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
    }
    response.flushBuffer();
}

From source file:com.aurel.track.admin.customize.lists.BlobBL.java

/**
 * Download the icon content/*from   ww w .j  a  va2s .  co  m*/
 * 
 * @param iconBytes
 * @param request
 * @param reponse
 * @param fileName
 * @param inline
 */
public static void download(byte[] iconBytes, HttpServletRequest request, HttpServletResponse reponse,
        String fileName, boolean inline) {
    prepareResponse(request, reponse, fileName, Long.toString(iconBytes.length), inline);
    // open the file
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        // retrieve the file data
        inputStream = new BufferedInputStream(new ByteArrayInputStream(iconBytes));
        outputStream = reponse.getOutputStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    } catch (FileNotFoundException fnfe) {
        LOGGER.error("FileNotFoundException thrown " + fnfe.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(fnfe));
        return;
    } catch (Exception ioe) {
        LOGGER.error("Creating the input stream failed with  " + ioe.getMessage(), ioe);
        LOGGER.debug(ExceptionUtils.getStackTrace(ioe));
        return;
    } finally {
        // flush and close the streams
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
        if (outputStream != null) {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.iorga.iraj.security.AbstractSecurityFilter.java

protected static void sendError(final int sc, final String message, final HttpServletResponse resp,
        final String debugMessage, final Throwable debugThrowableCause) throws IOException {
    if (log.isDebugEnabled()) {
        final String logMessage = "[" + sc + ":" + message + "]"
                + (debugMessage != null ? " " + debugMessage : "");
        if (debugThrowableCause != null) {
            log.debug(logMessage, debugThrowableCause);
        } else {/*from   ww  w.  j a  v  a 2  s  .  c  o  m*/
            log.debug(logMessage);
        }
    }

    resp.setStatus(sc);
    new MessagesBuilder().appendError(message).build().writeToOutputStream(resp.getOutputStream());
}

From source file:com.ikon.util.WebUtils.java

/**
 * Send file to client browser.//from w w  w  .  j  a  va  2s.  c  o  m
 * 
 * @throws IOException If there is a communication error.
 */
public static void sendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline, InputStream is) throws IOException {
    log.debug("sendFile({}, {}, {}, {}, {}, {})",
            new Object[] { request, response, fileName, mimeType, inline, is });
    prepareSendFile(request, response, fileName, mimeType, inline);

    // Set length
    response.setContentLength(is.available());
    log.debug("File: {}, Length: {}", fileName, is.available());

    ServletOutputStream sos = response.getOutputStream();
    IOUtils.copy(is, sos);
    sos.flush();
    sos.close();
}

From source file:com.ikon.util.WebUtils.java

/**
 * Send file to client browser.//from  w ww  . ja v  a 2 s.  c om
 * 
 * @throws IOException If there is a communication error.
 */
public static void sendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline, File input) throws IOException {
    log.debug("sendFile({}, {}, {}, {}, {}, {})",
            new Object[] { request, response, fileName, mimeType, inline, input });
    prepareSendFile(request, response, fileName, mimeType, inline);

    // Set length
    response.setContentLength((int) input.length());
    log.debug("File: {}, Length: {}", fileName, input.length());

    ServletOutputStream sos = response.getOutputStream();
    FileUtils.copy(input, sos);
    sos.flush();
    sos.close();
}