Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream write.

Prototype

public abstract void write(int b) throws IOException;

Source Link

Document

Writes the specified byte to this output stream.

Usage

From source file:org.ejbca.ui.web.RequestHelper.java

/**
 * Sends back certificate as binary file (application/octet-stream)
 *
 * @param b64cert base64 encoded certificate to be returned
 * @param out output stream to send to/*from   w  w  w . j  av  a2  s  .  com*/
 * @param filename filename sent as 'Content-disposition' header 
 * @param beginKey String containing key information, i.e. BEGIN_CERTIFICATE_WITH_NL or BEGIN_PKCS7_WITH_NL
 * @param endKey String containing key information, i.e. END_CERTIFICATE_WITH_NL or END_PKCS7_WITH_NL
 * @throws IOException 
 * @throws Exception on error
 */
public static void sendNewB64File(byte[] b64cert, HttpServletResponse out, String filename, String beginKey,
        String endKey) throws IOException {
    if (b64cert.length == 0) {
        log.error("0 length certificate can not be sent to client!");
        return;
    }

    // We must remove cache headers for IE
    ServletUtils.removeCacheHeaders(out);

    // Set content-type to general file
    out.setContentType("application/octet-stream");
    out.setHeader("Content-disposition", "filename=\"" + StringTools.stripFilename(filename) + "\"");

    out.setContentLength(b64cert.length + beginKey.length() + endKey.length());

    // Write the certificate
    ServletOutputStream os = out.getOutputStream();
    os.write(beginKey.getBytes());
    os.write(b64cert);
    os.write(endKey.getBytes());
    out.flushBuffer();
    if (log.isDebugEnabled()) {
        log.debug("Sent reply to client");
        log.debug(new String(b64cert));
    }
}

From source file:org.ejbca.ui.web.RequestHelper.java

/**
 * Sends back a number of bytes/*from   ww w.j a  v a  2s. com*/
 *
 * @param bytes DER encoded certificate to be returned
 * @param out output stream to send to
 * @param contentType mime type to send back bytes as
 * @param fileName to call the file in a Content-disposition, can be null to leave out this header
 *
 * @throws Exception on error
 */
public static void sendBinaryBytes(final byte[] bytes, final HttpServletResponse out, final String contentType,
        final String filename) throws Exception {
    if ((bytes == null) || (bytes.length == 0)) {
        log.error("0 length can not be sent to client!");
        return;
    }

    if (filename != null) {
        // We must remove cache headers for IE
        ServletUtils.removeCacheHeaders(out);
        out.setHeader("Content-disposition", "filename=\"" + StringTools.stripFilename(filename) + "\"");
    }

    // Set content-type to general file
    out.setContentType(contentType);
    out.setContentLength(bytes.length);

    // Write the certificate
    final ServletOutputStream os = out.getOutputStream();
    os.write(bytes);
    out.flushBuffer();
    if (log.isDebugEnabled()) {
        log.debug("Sent " + bytes.length + " bytes to client");
    }
}

From source file:org.xsystem.sql2.http.impl.HttpHelper.java

public static void writeFile(FileTransfer fileTransfer, boolean isDownload, int thumb,
        HttpServletRequest request, HttpServletResponse response, ServletOutputStream out) throws Exception {
    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache");
    response.setCharacterEncoding("UTF-8");

    if (!isDownload) {

        FileTransfer ft = ImgHelper.previewFile(fileTransfer, thumb);
        String contentType = ft.getContentType();
        response.setContentType(contentType);
        byte b[] = ft.getData();
        out.write(b);
    } else {//from  w w w .j av a  2 s  .  c  o m
        String userAgent = request.getHeader("USER-AGENT").toLowerCase();
        response.setHeader("Content-Type", "application/force-download; charset=utf-8");
        String fname = fileTransfer.getFileName();
        String URLEncodedFileName = URLEncoder.encode(fname, "UTF-8");
        String ResultFileName = URLEncodedFileName.replace('+', ' ');
        if (userAgent != null && (userAgent.contains("chrome") || userAgent.contains("msie")
                || userAgent.contains("trident"))) {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + ResultFileName + "\"");

        } else {
            response.setHeader("Content-Disposition",
                    "attachment; filename*=\"utf8'ru-ru'" + ResultFileName + "\"");
        }
        out.write(fileTransfer.getData());
    }
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static void sendBytes(byte[] bytes, String filename, String contentType) {
    if (bytes != null) {
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();

        response.setContentType(contentType);
        response.addHeader("Content-disposition", "attachment; filename=" + filename);
        response.addHeader("Content-Length", String.valueOf(bytes.length));
        ServletOutputStream os = null;
        try {/*from   w  w w  .  ja va 2  s .  c o m*/
            os = response.getOutputStream();
            os.write(bytes);
            os.flush();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException e) {
            LOGGER.error("Sending content failed {0}", filename, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close stream after sending", e);
                }
            }
        }
    }
}

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

/**
 * downloadFile//from w w  w  . j  a  va 2s  .  c  o m
 * 
 * @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:ch.rasc.extclassgenerator.ModelGenerator.java

public static void writeModel(HttpServletRequest request, HttpServletResponse response, ModelBean model,
        OutputConfig outputConfig) throws IOException {

    byte[] data = generateJavascript(model, outputConfig).getBytes(UTF8_CHARSET);
    String ifNoneMatch = request.getHeader("If-None-Match");
    String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\"";

    if (etag.equals(ifNoneMatch)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;//from   w  w w. j  av a  2s.  co  m
    }

    response.setContentType("application/javascript");
    response.setCharacterEncoding(UTF8_CHARSET.name());
    response.setContentLength(data.length);

    response.setHeader("ETag", etag);

    @SuppressWarnings("resource")
    ServletOutputStream out = response.getOutputStream();
    out.write(data);
    out.flush();

}

From source file:org.opentaps.common.event.PaginationEvents.java

/**
 * Download an existing Excel file from the ${opentaps_home}/runtime/output
 * directory. The Excel file is deleted after the download.
 *
 * @param filename the file name String object
 * @param request a <code>HttpServletRequest</code> value
 * @param response a <code>HttpServletResponse</code> value
 * @return a <code>String</code> value
 *///from w w  w . ja v  a  2  s .c  o m
private static String downloadExcel(String filename, HttpServletRequest request, HttpServletResponse response) {
    File file = null;
    ServletOutputStream out = null;
    FileInputStream fileToDownload = null;

    try {
        out = response.getOutputStream();

        file = new File(UtilCommon.getAbsoluteFilePath(request, filename));
        fileToDownload = new FileInputStream(file);

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentLength(fileToDownload.available());

        int c;
        while ((c = fileToDownload.read()) != -1) {
            out.write(c);
        }

        out.flush();
    } catch (FileNotFoundException e) {
        Debug.logError("Failed to open the file: " + filename, MODULE);
        return "error";
    } catch (IOException ioe) {
        Debug.logError("IOException is thrown while trying to download the Excel file: " + ioe.getMessage(),
                MODULE);
        return "error";
    } finally {
        try {
            out.close();
            if (fileToDownload != null) {
                fileToDownload.close();
                // Delete the file under /runtime/output/ this is optional
                file.delete();
            }
        } catch (IOException ioe) {
            Debug.logError("IOException is thrown while trying to download the Excel file: " + ioe.getMessage(),
                    MODULE);
            return "error";
        }
    }

    return "success";
}

From source file:CounterServer.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    int count = 1;
    Integer i = (Integer) session.getAttribute(COUNTER_KEY);
    if (i != null) {
        count = i.intValue() + 5;//from   w  ww. j  a va  2s . c o  m
    }
    session.setAttribute(COUNTER_KEY, new Integer(count));
    DataInputStream in = new DataInputStream(req.getInputStream());
    resp.setContentType("application/octet-stream");
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.writeInt(count);
    out.flush();
    byte[] buf = byteOut.toByteArray();
    resp.setContentLength(buf.length);
    ServletOutputStream servletOut = resp.getOutputStream();
    servletOut.write(buf);
    servletOut.close();
}

From source file:werecloud.api.view.StringView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (model.containsKey("string")) {
        String data = model.get("string").toString();
        byte[] _data = data.getBytes();
        response.setContentType(getContentType());
        response.setContentLength(_data.length);
        ServletOutputStream out = response.getOutputStream();
        out.write(_data);
        out.flush();/*from w  w w .j  a v  a2s. c o m*/
        out.close();
        return;
    }
    throw new Exception("Could not find model.");
}

From source file:test.be.fedict.eid.applet.XmlSignatureServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    HttpSession httpSession = request.getSession();
    String documentStr = (String) httpSession.getAttribute("xmlDocument");
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    out.write(documentStr.getBytes());
    out.close();//from   w  ww .j a v a  2 s .  com
}