Example usage for javax.servlet.http HttpServletRequest getContentLength

List of usage examples for javax.servlet.http HttpServletRequest getContentLength

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContentLength.

Prototype

public int getContentLength();

Source Link

Document

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.MAX_VALUE.

Usage

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }//  w ww. j ava  2 s . c o  m
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:com.ibm.btt.sample.SampleFileHandler.java

@Override
protected int doRequestValidation(HttpServletRequest request) {
    int size = request.getContentLength();
    // notifiy the browser the file size is exceeded. 
    if (size > maxSize) {
        return FILE_SIZE_EXCEED;
    }//  w w  w . ja v a 2  s .  c  om
    return REQ_VALID;
}

From source file:com.google.nigori.server.NigoriServlet.java

private String getJsonAsString(HttpServletRequest req, int maxLength) throws ServletException {

    if (maxLength != 0 && req.getContentLength() > maxLength) {
        return null;
    }// w  w  w .  j a  v a2  s .  c o m

    String charsetName = req.getCharacterEncoding();
    if (charsetName == null) {
        charsetName = MessageLibrary.CHARSET;
    }

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream(), charsetName));
        StringBuilder json = new StringBuilder();
        char[] buffer = new char[64 * 1024];
        int charsRemaining = maxJsonQueryLength;
        int charsRead;
        while ((charsRead = in.read(buffer)) != -1) {
            charsRemaining -= charsRead;
            if (charsRemaining < 0) {
                throw new ServletException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                        "Json request exceeds server maximum length of " + maxLength);
            }
            json.append(buffer, 0, charsRead);
        }
        return json.toString();
    } catch (IOException ioe) {
        throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Internal error receiving data from client.");
    }
}

From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
    out.println();/*from ww w  .j a  v a2  s.  c  o m*/
    int fileSize = request.getContentLength();
    byte[] buf = new byte[fileSize];
    try {
        ServletInputStream is = request.getInputStream();
        is.read(buf);
        File file = new File(destinationDir, "LogisticNetwork.mxe");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(buf);
        fos.close();
        out.close();
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

}

From source file:com.globalsight.everest.webapp.pagehandler.tm.management.FileUploadHelper.java

public void uploadWithValidation(HttpServletRequest p_request) {
    ResourceBundle bundle = PageHandler.getBundle(p_request.getSession());

    if (status == null) {
        return;/* w w w .jav  a 2 s  . co  m*/
    }

    status.setBundle(bundle);
    status.setTotalSize(p_request.getContentLength());

    try {
        status.beginUpload();
        upload(p_request);

        status.beginValidation();
        validate();

    } catch (Exception e) {
        CATEGORY.error(e.getMessage(), e);
    }
}

From source file:upload.UploadAction.java

private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {

        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }/*from   w w  w  .j  a va  2  s  . c  o m*/

        public String getContentType() {
            return req.getContentType();
        }

        public int getContentLength() {
            return req.getContentLength();
        }

        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:org.red5.server.net.servlet.RequestDumpServlet.java

/** {@inheritDoc} */
@Override//from   w  ww .  j  a v  a  2s .c  om
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Enumeration en = req.getHeaderNames();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        log.info(name + " => " + req.getHeader(name));
    }

    ByteBuffer reqBuffer = null;

    try {

        //req.getSession().getAttribute(REMOTING_CONNECTOR);

        reqBuffer = ByteBuffer.allocate(req.getContentLength());
        ServletUtils.copy(req.getInputStream(), reqBuffer.asOutputStream());
        //reqBuffer.flip();

        log.info(HexDump.formatHexDump(reqBuffer.getHexDump()));

    } catch (IOException e) {
        log.error(e);
    }
    log.info("End");
}

From source file:org.webguitoolkit.ui.controls.form.fileupload.FileUploadServlet.java

public UploadListener(HttpServletRequest request, String cssId, long debugDelay) {
    this.cssId = cssId;
    this.request = request;
    this.delay = debugDelay;
    totalToRead = request.getContentLength();
    this.startTime = System.currentTimeMillis();
}

From source file:com.geocent.owf.openlayers.DataRequestProxy.java

/**
 * Gets the data from the provided remote URL.
 * Note that the data will be returned from the method and not automatically
 * populated into the response object./*from   w ww  .  j av a  2 s .  co m*/
 * 
 * @param request       ServletRequest object containing the request data.
 * @param response      ServletResponse object for the response information.
 * @param url           URL from which the data will be retrieved.
 * @return              Data from the provided remote URL.
 * @throws IOException 
 */
public String getData(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {

    if (!allowUrl(url)) {
        throw new UnknownHostException("Request to invalid host not allowed.");
    }

    HttpURLConnection connection = (HttpURLConnection) (new URL(url).openConnection());
    connection.setRequestMethod(request.getMethod());

    // Detects a request with a payload inside the message body
    if (request.getContentLength() > 0) {
        connection.setRequestProperty("Content-Type", request.getContentType());
        connection.setDoOutput(true);
        connection.setDoInput(true);
        byte[] requestPayload = IOUtils.toByteArray(request.getInputStream());
        connection.getOutputStream().write(requestPayload);
        connection.getOutputStream().flush();
    }

    // Create handler for the given content type and proxy the extracted information
    Handler contentHandler = HandlerFactory.getHandler(connection.getContentType());
    return contentHandler.handleContent(response, connection.getInputStream());
}

From source file:org.apache.wookie.proxy.ProxyServlet.java

/**
 * Gets the content of the request//from   w ww.  j  a  va2  s.  c o  m
 * @param request
 * @return
 * @throws IOException
 */
private String getXmlData(HttpServletRequest request) throws IOException {
    // Note that we cannot use a Reader for this as we already
    // call getParameter() which works on an InputStream - and you
    // can only use an InputStream OR a Reader, not both.
    byte[] b = new byte[request.getContentLength()];
    request.getInputStream().read(b, 0, request.getContentLength());
    String xml = new String(b);
    return xml;
}