Example usage for javax.servlet.http HttpServletResponse getBufferSize

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

Introduction

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

Prototype

public int getBufferSize();

Source Link

Document

Returns the actual buffer size used for the response.

Usage

From source file:Buffering.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setBufferSize(8 * 1024); // 8K 
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    int size = res.getBufferSize(); // returns 8096 or greater

    log("The default buffer size is " + size);

    out.println("The client won't see this");
    res.reset();//from  w  w  w .j  a  v a 2  s. co m
    out.println("Nor will the client see this!");
    res.reset();
    out.println("And this won't be seen if sendError() is called");
    if (req.getParameter("param") == null) {
        res.sendError(res.SC_BAD_REQUEST, "param needed");
    }
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setBufferSize(8 * 1024); // 8K buffer
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    int size = res.getBufferSize(); // returns 8096 or greater

    // Record the default size, in the log
    log("The default buffer size is " + size);

    out.println("The client won't see this");
    res.reset();//from   www .  j  av  a2  s .  com
    out.println("And this won't be seen if sendError() is called");
    if (req.getParameter("important_parameter") == null) {
        res.sendError(res.SC_BAD_REQUEST, "important_parameter needed");
    }
}

From source file:net.paoding.spdy.server.tomcat.impl.supports.SpdyOutputBuffer.java

@Override
public int doWrite(ByteChunk chunk, Response coyoteResponse) throws IOException {
    int chunkLength = chunk.getLength();
    if (chunkLength <= 0) {
        return 0;
    }/*  w  ww.ja  v  a2s .  co m*/
    // @see org.apache.catalina.connector.CoyoteAdapter#service
    HttpServletResponse response = (HttpServletResponse) coyoteResponse.getNote(CoyoteAdapter.ADAPTER_NOTES);
    // chunk.getBuffer()byte?write
    if (response != null && chunk.getStart() + chunkLength == response.getBufferSize()) {
        byte[] copied = new byte[chunkLength];
        System.arraycopy(chunk.getBuffer(), chunk.getStart(), copied, 0, chunkLength);
        delay = ChannelBuffers.wrappedBuffer(copied);
        if (debugEnabled) {
            logger.debug("writing copied buffer: offset=" + chunk.getStart() + " len=" + chunkLength
                    + "  outputBufferSize=" + response.getBufferSize());
        }
        flush(coyoteResponse);
    }
    // ????write??chunk.bufferbyte
    else {
        if (fin) {
            throw new Error("spdy buffer error: buffer closed");
        }
        if (debugEnabled) {
            logger.debug("writing writing buffer: offset=" + chunk.getStart() + " len=" + chunkLength);
        }
        delay = ChannelBuffers.wrappedBuffer(chunk.getBuffer(), chunk.getStart(), chunkLength);
        flushAndClose(coyoteResponse);
    }
    return chunk.getLength();
}

From source file:arena.web.view.DownloadView.java

@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    response.setStatus(HttpServletResponse.SC_OK);
    String mt = (mimeTypeParam != null ? (String) model.get(mimeTypeParam) : this.mimeType);
    if (mt != null) {
        response.setContentType(this.mimeType);
    }//from   ww w. ja v  a  2 s.  c  o  m

    Object contentObj = model.get(this.contentParam);
    String fileName = ServletUtils.replaceWildcards(this.filenamePattern, this.allowRequestArgs, model,
            request);
    if (!fileName.equals("")) {
        String rfc2047Name = javax.mail.internet.MimeUtility.encodeText(fileName, "UTF-8", null);
        String fullHeader = "attachment;filename=" + rfc2047Name;
        response.setHeader("Content-Disposition", fullHeader);
    }

    ServletOutputStream out = response.getOutputStream();
    if (contentObj instanceof byte[]) {
        byte[] content = (byte[]) model.get(this.contentParam);
        response.setContentLength(content == null ? 0 : content.length);
        if (content != null && content.length > 0) {
            out.write(content);
        }
    } else if (contentObj instanceof InputStream) {
        InputStream content = (InputStream) contentObj;
        byte[] buffer = new byte[response.getBufferSize()];
        int read = 0;
        while ((read = content.read(buffer)) >= 0) {
            out.write(buffer, 0, read);
        }
        if (this.closeStream) {
            content.close();
        }
    }
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void get(HttpServletRequest req, HttpServletResponse resp)
        throws RemoteException, IndelibleWebAccessException {
    String path = req.getPathInfo();
    FilePath reqPath = FilePath.getFilePath(path);
    if (reqPath == null || reqPath.getNumComponents() < 2)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

    // Should be an absolute path
    reqPath = reqPath.removeLeadingComponent();
    String fsIDStr = reqPath.getComponent(0);
    IndelibleFSVolumeIF volume = getVolume(fsIDStr);
    FilePath listPath = reqPath.removeLeadingComponent();

    try {//  w w  w.  j  a  v  a  2s. co m
        IndelibleFileNodeIF getFile = volume.getObjectByPath(listPath.makeAbsolute());
        if (getFile.isDirectory())
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null);
        resp.setContentType("application/x-download");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + listPath.getName() + "\"");
        IndelibleFSForkIF dataFork = getFile.getFork("data", false);
        if (dataFork != null) {
            IndelibleFSForkRemoteInputStream forkStream = new IndelibleFSForkRemoteInputStream(dataFork);
            OutputStream outStream = resp.getOutputStream();
            byte[] outBuffer = new byte[resp.getBufferSize()];
            int bytesRead;
            while ((bytesRead = forkStream.read(outBuffer)) > 0)
                outStream.write(outBuffer, 0, bytesRead);
        }
    } catch (ObjectNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
    } catch (PermissionDeniedException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
    } catch (IOException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
    } catch (ForkNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e);
    }
    return;
}

From source file:com.groupon.odo.Proxy.java

/**
 * @param httpServletResponse/*  www  . j ava  2 s  .  co  m*/
 * @param outStream
 * @param jsonpCallback
 * @throws IOException
 */
private void writeResponseOutput(HttpServletResponse httpServletResponse, OutputStream outStream,
        String jsonpCallback) throws IOException {
    RequestInformation requestInfo = requestInformation.get();

    // check to see if this is chunked
    boolean chunked = false;
    if (httpServletResponse.containsHeader(HttpUtilities.STRING_TRANSFER_ENCODING) && httpServletResponse
            .getHeader(HttpUtilities.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
        httpServletResponse.setHeader(HttpUtilities.STRING_CONNECTION, HttpUtilities.STRING_CHUNKED);
        chunked = true;
    }

    // reattach JSONP if needed
    if (requestInfo.outputString != null && jsonpCallback != null) {
        requestInfo.outputString = jsonpCallback + "(" + requestInfo.outputString + ");";
    }

    // don't do this if we got a HTTP 304 since there is no data to send back
    if (httpServletResponse.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
        logger.info("Chunked: {}, {}", chunked, httpServletResponse.getBufferSize());
        if (!chunked) {
            // change the content length header to the new length
            if (requestInfo.outputString != null) {
                httpServletResponse.setContentLength(requestInfo.outputString.getBytes().length);
            } else {
                httpServletResponse.setContentLength(((ByteArrayOutputStream) outStream).toByteArray().length);
            }
        }

        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();

        if (requestInfo.outputString != null) {
            outputStreamClientResponse.write(requestInfo.outputString.getBytes());
        } else {
            outputStreamClientResponse.write(((ByteArrayOutputStream) outStream).toByteArray());
        }
        httpServletResponse.flushBuffer();

        logger.info("Done writing");
    }

    // outstr might still be null.. let's try to set it from outStream
    if (requestInfo.outputString == null) {
        try {
            requestInfo.outputString = outStream.toString();
        } catch (Exception e) {
            // can ignore any issues.. worst case outstr is still null
        }
    }
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;/*from  ww  w .  j  a  v  a 2 s.  co m*/
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:org.apache.roller.weblogger.ui.core.filters.DebugFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    log.info("ENTERING " + request.getRequestURL());

    // some info about the request and response
    log.info("Response Object:");
    log.info("   isCommited = " + response.isCommitted());
    log.info("   bufferSize = " + response.getBufferSize());
    log.info("");

    chain.doFilter(request, response);/*from  w ww  .j  av  a 2 s . c  om*/

    log.info("EXITING " + request.getRequestURL());

    // some info about the request and response
    log.info("Response Object:");
    log.info("   isCommited = " + response.isCommitted());
    log.info("   bufferSize = " + response.getBufferSize());
    log.info("");
}

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/download")
public String download(Model model, @RequestHeader("User-Agent") String userAgent,
        @RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception {
    FileDTO fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    BufferedInputStream bufferdInputStream = null;
    ServletOutputStream servletOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    StringBuilder sb = new StringBuilder();

    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();

    try {//from ww w.  ja  v a2s .c o m

        if (StringUtils.isNotEmpty(repositoryPath)) {
            // FILE_SYSTEM
            sb.append(repositoryPath);
            if (!repositoryPath.endsWith(File.separator)) {
                sb.append(File.separator);
            }
            sb.append(uniqueFilename);
            File file = new File(sb.toString());
            inputStream = new FileInputStream(file);
        } else {
            // DATABASE
            byte[] bytes = new byte[] {};
            if (fileDTO.getFileSize() > 0) {
                bytes = fileDTO.getBytes();
            }
            inputStream = new ByteArrayInputStream(bytes);

        }
        // set response contenttype, header
        String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
        logger.debug("realFilename: {}", realFilename);
        logger.debug("encodedRealFilename: {}", encodedRealFilename);

        response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
        sb.setLength(0);
        if (userAgent.indexOf("MSIE5.5") > -1) {
            sb.append("filename=");
        } else {
            sb.append("attachment; filename=");
        }
        sb.append(encodedRealFilename);
        response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());
        logger.debug("header: {}", sb.toString());
        logger.debug("character encoding: {}", response.getCharacterEncoding());
        logger.debug("content type: {}", response.getContentType());
        logger.debug("bufferSize: {}", response.getBufferSize());
        logger.debug("locale: {}", response.getLocale());

        bufferdInputStream = new BufferedInputStream(inputStream);
        servletOutputStream = response.getOutputStream();
        bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
        int bytesRead;
        byte buffer[] = new byte[2048];
        while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        // flush stream
        bufferedOutputStream.flush();

        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    } finally {
        // close stream
        inputStream.close();
        bufferdInputStream.close();
        servletOutputStream.close();
        bufferedOutputStream.close();
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}