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 void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this output stream.

Usage

From source file:org.commoncrawl.service.listcrawler.ProxyServlet.java

private static void sendCacheItemResponse(final HttpServletRequest req, final HttpServletResponse response,
        CacheItem responseItem, boolean isS3Response, String renderAs, AsyncResponse responseObject,
        long requestStartTime) throws IOException {

    // remove default headers ... 
    response.setHeader("Date", null);
    response.setHeader("Server", null);

    // parse response code in headers ... 
    CrawlURLMetadata metadata = new CrawlURLMetadata();

    HttpHeaderInfoExtractor.parseStatusLine(responseItem.getHeaderItems().get(0).getItemValue(), metadata);

    if (!metadata.isFieldDirty(CrawlURLMetadata.Field_HTTPRESULTCODE)) {
        metadata.setHttpResultCode(200);
    }/*from ww w  .  java  2 s  .c  o m*/
    // set the result code ... 
    response.setStatus(metadata.getHttpResultCode());

    if (renderAs.equals(PROXY_RENDER_TYPE_TEXT)) {

        response.setHeader("content-type", "text/plain");

        PrintWriter writer = response.getWriter();

        writer.write(responseItem.getHeaderItems().get(0).getItemValue() + "\n");

        if (isS3Response)
            writer.write(PROXY_HEADER_SOURCE + ":s3\n");
        else
            writer.write(PROXY_HEADER_SOURCE + ":cache\n");
        writer.write(PROXY_HEADER_TIMER + ":" + (System.currentTimeMillis() - requestStartTime) + "MS\n");
        writer.write(PROXY_HEADER_FINALURL + ":" + responseItem.getFinalURL() + "\n");

        writer.write("content-length:" + Integer.toString(responseItem.getContent().getCount()) + "\n");
        if ((responseItem.getFlags() & CacheItem.Flags.Flag_IsCompressed) != 0) {
            writer.write("content-encoding:gzip\n");
        }

        String truncationFlags = "";
        if ((responseItem.getFlags() & CacheItem.Flags.Flag_WasTruncatedDuringDownload) != 0) {
            truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInDownload);
        }
        if ((responseItem.getFlags() & CacheItem.Flags.Flag_WasTruncatedDuringInflate) != 0) {
            if (truncationFlags.length() != 0)
                truncationFlags += ",";
            truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInInflate);
        }

        if (truncationFlags.length() != 0) {
            writer.write(PROXY_HEADER_TRUNCATION + ":" + truncationFlags + "\n");
        }
        // iterate items 
        for (ArcFileHeaderItem headerItem : responseItem.getHeaderItems()) {
            // ignore unwanted items
            if (headerItem.getItemKey().length() != 0) {
                if (headerItem.getItemValue().length() != 0) {
                    if (!dontProxyHeaders.contains(headerItem.getItemKey().toLowerCase())) {
                        // and send other ones through 
                        writer.write(headerItem.getItemKey() + ":" + headerItem.getItemValue() + "\n");
                    } else {
                        if (headerItem.getItemKey().equalsIgnoreCase("content-length")) {
                            writer.write(
                                    PROXY_HEADER_ORIGINAL_CONTENT_LEN + ":" + headerItem.getItemValue() + "\n");
                        }
                    }
                }
            }
        }
        writer.write("\n");

        int contentLength = responseItem.getContent().getCount();
        byte contentData[] = responseItem.getContent().getReadOnlyBytes();

        if ((responseItem.getFlags() & CacheItem.Flags.Flag_IsCompressed) != 0) {

            UnzipResult result = GZIPUtils.unzipBestEffort(contentData, CrawlEnvironment.CONTENT_SIZE_LIMIT);
            if (result != null) {
                contentData = result.data.get();
                contentLength = result.data.getCount();
            }
        }

        NIOHttpHeaders headers = ArcFileItemUtils
                .buildHeaderFromArcFileItemHeaders(responseItem.getHeaderItems());

        BufferedReader bufferedReader = readerForCharset(headers, contentData, contentLength, writer);
        try {
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                writer.println(line);
            }
        } finally {
            bufferedReader.close();
        }
        writer.flush();
    } else {

        // set the content length ... 
        response.setHeader("content-length", Integer.toString(responseItem.getContent().getCount()));
        if ((responseItem.getFlags() & CacheItem.Flags.Flag_IsCompressed) != 0) {
            response.setHeader("content-encoding", "gzip");
        }
        if (isS3Response)
            response.setHeader(PROXY_HEADER_SOURCE, "s3");
        else
            response.setHeader(PROXY_HEADER_SOURCE, "cache");

        response.setHeader(PROXY_HEADER_TIMER, (System.currentTimeMillis() - requestStartTime) + "MS");
        response.setHeader(PROXY_HEADER_FINALURL, responseItem.getFinalURL());

        String truncationFlags = "";
        if ((responseItem.getFlags() & CacheItem.Flags.Flag_WasTruncatedDuringDownload) != 0) {
            truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInDownload);
        }
        if ((responseItem.getFlags() & CacheItem.Flags.Flag_WasTruncatedDuringInflate) != 0) {
            if (truncationFlags.length() != 0)
                truncationFlags += ",";
            truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInInflate);
        }
        if (truncationFlags.length() != 0) {
            response.setHeader(PROXY_HEADER_TRUNCATION, truncationFlags);
        }

        // iterate items 
        for (ArcFileHeaderItem headerItem : responseItem.getHeaderItems()) {
            // ignore unwanted items
            if (headerItem.getItemKey().length() != 0) {
                if (headerItem.getItemValue().length() != 0) {
                    if (!dontProxyHeaders.contains(headerItem.getItemKey().toLowerCase())) {
                        // and send other ones through 
                        response.setHeader(headerItem.getItemKey(), headerItem.getItemValue());
                    } else {
                        if (headerItem.getItemKey().equalsIgnoreCase("content-length")) {
                            response.setHeader(PROXY_HEADER_ORIGINAL_CONTENT_LEN, headerItem.getItemValue());
                        }
                    }
                }
            }
        }

        ServletOutputStream responseOutputStream = response.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(responseOutputStream, Charset.forName("ASCII")));

        // write out content bytes 
        responseOutputStream.write(responseItem.getContent().getReadOnlyBytes(), 0,
                responseItem.getContent().getCount());

    }
    ProxyServer.getSingleton().logProxySuccess(metadata.getHttpResultCode(), (isS3Response) ? "s3" : "cache",
            responseItem.getUrl(), responseItem.getFinalURL(), responseObject.getStartTime());
}

From source file:org.apache.myfaces.renderkit.html.util.MyFacesResourceLoader.java

/**
 * Copy the content of the specified input stream to the servlet response.
 *//*from   w ww . j  ava2 s.  co m*/
protected void writeResource(HttpServletRequest request, HttpServletResponse response, InputStream in)
        throws IOException {
    ServletOutputStream out = response.getOutputStream();
    try {
        byte[] buffer = new byte[1024];
        for (int size = in.read(buffer); size != -1; size = in.read(buffer)) {
            out.write(buffer, 0, size);
        }
        out.flush();
    } catch (IOException e) {
        // This happens sometimes with Microsft Internet Explorer. It would
        // appear (guess) that when javascript creates multiple dom nodes
        // referring to the same remote resource then IE stupidly opens 
        // multiple sockets and requests that resource multiple times. But
        // when the first request completes, it then realises its stupidity
        // and forcibly closes all the other sockets. But here we are trying
        // to service those requests, and so get a "broken pipe" failure 
        // on write. The only thing to do here is to silently ignore the issue,
        // ie suppress the exception. Note that it is also possible for the
        // above code to succeed (ie this exception clause is not run) but
        // for a later flush to get the "broken pipe"; this is either due
        // just to timing, or possibly IE is closing sockets after receiving
        // a complete file for some types (gif?) rather than waiting for the
        // server to close it. We throw a special exception here to inform
        // callers that they should NOT flush anything - though that is
        // dangerous no matter what IOException subclass is thrown.
        log.debug("Unable to send resource data to client", e);
        throw new ResourceLoader.ClosedSocketException();
    }
}

From source file:org.apache.stratos.theme.mgt.ui.servlets.ThemeResourceServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from w  ww .  j a  v a2s.  c o  m*/
        ThemeMgtServiceClient client = new ThemeMgtServiceClient(servletConfig, request.getSession());
        String path = request.getParameter("path");
        String viewImage = request.getParameter("viewImage");
        if (path == null) {
            String msg = "Could not get the resource content. Path is not specified.";
            log.error(msg);
            response.setStatus(400);
            return;
        }

        ContentDownloadBean bean = client.getContentDownloadBean(path);

        InputStream contentStream = null;
        if (bean.getContent() != null) {
            contentStream = bean.getContent().getInputStream();
        } else {
            String msg = "The resource content was empty.";
            log.error(msg);
            response.setStatus(204);
            return;
        }

        response.setDateHeader("Last-Modified", bean.getLastUpdatedTime().getTime().getTime());
        String ext = "jpg";
        if (path.lastIndexOf(".") < path.length() - 1 && path.lastIndexOf(".") > 0) {
            ext = path.substring(path.lastIndexOf(".") + 1);
        }

        if (viewImage != null && viewImage.equals("1")) {
            response.setContentType("img/" + ext);
        } else {
            if (bean.getMediatype() != null && bean.getMediatype().length() > 0) {
                response.setContentType(bean.getMediatype());
            } else {
                response.setContentType("application/download");
            }

            if (bean.getResourceName() != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + bean.getResourceName() + "\"");
            }
        }

        if (contentStream != null) {

            ServletOutputStream servletOutputStream = null;
            try {
                servletOutputStream = response.getOutputStream();

                byte[] contentChunk = new byte[1024];
                int byteCount;
                while ((byteCount = contentStream.read(contentChunk)) != -1) {
                    servletOutputStream.write(contentChunk, 0, byteCount);
                }

                response.flushBuffer();
                servletOutputStream.flush();

            } finally {
                contentStream.close();

                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
            }
        }
    } catch (Exception e) {

        String msg = "Failed to get resource content. " + e.getMessage();
        log.error(msg, e);
        response.setStatus(500);
    }
}

From source file:com.mkmeier.quickerbooks.ProcessSquare.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from  www  .  j  a  va2  s  . co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        showForm(request, response);
    } else {

        ServletFileUploader up = new ServletFileUploader();
        up.parseRequest(request);

        File file = up.getFileMap().get("squareTxn");

        int incomeAcctNum = Integer.parseInt(up.getFieldMap().get("incomeAcct"));
        int feeAcctNum = Integer.parseInt(up.getFieldMap().get("feeAcct"));
        int depositAcctNum = Integer.parseInt(up.getFieldMap().get("depositAcct"));

        QbAccount incomeAcct = getAccount(incomeAcctNum);
        QbAccount feeAcct = getAccount(feeAcctNum);
        QbAccount depositAcct = getAccount(depositAcctNum);

        SquareParser sp = new SquareParser(file);
        List<SquareTxn> txns;

        try {
            txns = sp.parse();
        } catch (SquareException ex) {
            throw new ServletException(ex);
        }

        SquareToIif squareToIif = new SquareToIif(txns, incomeAcct, feeAcct, depositAcct);
        File iifFile = squareToIif.getIifFile();

        response.setHeader("Content-Disposition", "attachement; filename=\"iifFile.iif\"");
        ServletOutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(iifFile);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();

        //       PrintWriter out = response.getWriter();
        //       for (SquareTxn txn : txns) {
        //      out.println(txn.toString());
        //       }
    }
}

From source file:org.apache.cxf.fediz.spring.web.FederationSignOutCleanupFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String wa = request.getParameter(FederationConstants.PARAM_ACTION);
    if (FederationConstants.ACTION_SIGNOUT_CLEANUP.equals(wa)) {
        if (request instanceof HttpServletRequest) {
            ((HttpServletRequest) request).getSession().invalidate();
        }//from   w ww  .ja  v a 2s .  c  om

        final ServletOutputStream responseOutputStream = response.getOutputStream();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("logout.jpg");
        if (inputStream == null) {
            LOG.warn("Could not write logout.jpg");
            return;
        }
        int read = 0;
        byte[] buf = new byte[1024];
        while ((read = inputStream.read(buf)) != -1) {
            responseOutputStream.write(buf, 0, read);
        }
        inputStream.close();
        responseOutputStream.flush();
    } else {
        chain.doFilter(request, response);
    }
}

From source file:com.denimgroup.threadfix.webapp.controller.VulnerabilitySearchController.java

private boolean sendFileContentToClient(String content, HttpServletResponse response) throws IOException {
    if (content == null) {
        return false;
    }/*from   w w w  . j av a 2s  . c o m*/
    InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"));

    if (in != null) {
        ServletOutputStream out = response.getOutputStream();

        byte[] outputByteBuffer = new byte[65535];

        int remainingSize = in.read(outputByteBuffer, 0, 65535);

        // copy binary content to output stream
        while (remainingSize != -1) {
            out.write(outputByteBuffer, 0, remainingSize);
            remainingSize = in.read(outputByteBuffer, 0, 65535);
        }
        in.close();
        out.flush();
        out.close();
        return true;
    } else {
        return false;
    }
}

From source file:com.kwoksys.biz.files.FileService.java

public void download(ResponseContext responseContext, File file) throws FileNotFoundException {
    HttpServletResponse response = responseContext.getResponse();

    response.setContentType(file.getMimeType());
    response.setContentLength(file.getSize());

    // To work around file download problems on IE
    response.setHeader("Pragma", "public"); // For HTTP/1.0 backward compatibility.
    response.setHeader("Cache-Control", "public"); // For HTTP/1.1.

    response.setHeader("Content-Disposition", "filename=\"" + file.getLogicalName() + "\"");

    // Get the file in file input stream.
    java.io.File downloadFile = new java.io.File(file.getConfigRepositoryPath(), file.getPhysicalName());

    FileInputStream input = null;
    ServletOutputStream output = null;

    try {/*from   w ww  .j  a  va  2  s  .  c om*/
        input = new FileInputStream(downloadFile);
        output = response.getOutputStream();

        byte[] buffer = new byte[10240];
        int read;
        while ((read = input.read(buffer)) > 0) {
            output.write(buffer, 0, read);
        }
    } catch (Exception e) {
        logger.warning("Problem downloading a file: " + e.getMessage());
        throw new FileNotFoundException();

    } finally {
        close(input);
        close(output);
    }
}

From source file:org.apache.accumulo.monitor.servlets.DefaultServlet.java

private void getResource(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {/*from w  ww.j ava2 s.  co m*/
        String path = req.getRequestURI();

        if (path.endsWith(".jpg"))
            resp.setContentType("image/jpeg");

        if (path.endsWith(".html"))
            resp.setContentType("text/html");

        path = path.substring(1);
        InputStream data = BasicServlet.class.getClassLoader().getResourceAsStream(path);
        ServletOutputStream out = resp.getOutputStream();
        try {
            if (data != null) {
                byte[] buffer = new byte[1024];
                int n;
                while ((n = data.read(buffer)) > 0)
                    out.write(buffer, 0, n);
            } else {
                out.write(("could not get resource " + path + "").getBytes(UTF_8));
            }
        } finally {
            if (data != null)
                data.close();
        }
    } catch (Throwable t) {
        log.error(t, t);
        throw new IOException(t);
    }
}

From source file:Utils.UpDownFiles.java

/**
 *
 * @param pw/*from www .  j  av  a  2s. c  o  m*/
 * @param xml
 * @return
 */
public boolean prepareToDownBinary(File file, ServletOutputStream out) {
    try {

        // Open the file stream
        FileInputStream in = new FileInputStream(file);

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        return true;

    } catch (Exception e) {
        //Utils.StaticClass.webAppSystemOutPrintln("ERROR occured in UpDownFiles.prepareToDown");
        Utils.StaticClass.handleException(e);
        return false;
    }
}

From source file:org.exist.webstart.JnlpWriter.java

/**
 * Send JAR or JAR.PACK.GZ file to end user.
 *
 * @param filename Name of JAR file//from w w w .j a v  a  2  s . c  o  m
 * @param response Object for writing to end user.
 * @throws java.io.IOException
 */
void sendJar(JnlpJarFiles jnlpFiles, String filename, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    logger.debug("Send jar file " + filename);

    final File localFile = jnlpFiles.getJarFile(filename);
    if (localFile == null || !localFile.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Jar file '" + filename + "' not found.");
        return;
    }

    logger.debug("Actual file " + localFile.getAbsolutePath());

    if (localFile.getName().endsWith(".jar")) {
        //response.setHeader(CONTENT_ENCODING, JAR_MIME_TYPE);
        response.setContentType(JAR_MIME_TYPE);

    } else if (localFile.getName().endsWith(".jar.pack.gz")) {
        response.setHeader(CONTENT_ENCODING, PACK200_GZIP_ENCODING);
        response.setContentType(PACK_MIME_TYPE);
    }

    // It is very improbable that a 64 bit jar is needed, but
    // it is better to be ready
    // response.setContentLength(Integer.parseInt(Long.toString(localFile.length())));
    response.setHeader("Content-Length", Long.toString(localFile.length()));
    response.setDateHeader("Last-Modified", localFile.lastModified());

    final FileInputStream fis = new FileInputStream(localFile);
    final ServletOutputStream os = response.getOutputStream();

    try {
        // Transfer bytes from in to out
        final byte[] buf = new byte[4096];
        int len;
        while ((len = fis.read(buf)) > 0) {
            os.write(buf, 0, len);
        }

    } catch (final IllegalStateException ex) {
        logger.debug(ex.getMessage());

    } catch (final IOException ex) {
        logger.debug("Ignore IOException for '" + filename + "'");
    }

    os.flush();
    os.close();
    fis.close();
}