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:com.web.server.ProxyServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);/*from w w  w. ja v  a 2s.c o  m*/
    uri.append(req.getRequestURI());

    // Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    //       if (contentLength == -1)
    //          throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //             System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:org.ngrinder.script.controller.DavSvnController.java

private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());/*w w w .  ja  v  a2  s. co  m*/
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();//  w  w w.j  ava  2  s  .  c om
    addRemoteIpToLoggingContext(req);

    log.info("Handling autodiscover request...");

    byte[] reqBytes = null;
    reqBytes = ByteUtil.getContent(req.getInputStream(), req.getContentLength());
    if (reqBytes == null) {
        log.warn("No content found in the request");
        sendError(resp, 600, "No content found in the request");
        return;
    }
    String content = new String(reqBytes, "UTF-8");
    log.debug("Request before auth: %s", content);

    if (log.isDebugEnabled()) {
        Enumeration<String> enm = req.getHeaderNames();
        while (enm.hasMoreElements()) {
            String header = enm.nextElement();
            log.info("POST header: %s", header + ":" + req.getHeader(header));
        }
    }

    String email = null;
    String responseSchema = null;

    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(content)));
        NodeList nList = doc.getElementsByTagName("Request");

        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                email = getTagValue("EMailAddress", element);
                responseSchema = getTagValue("AcceptableResponseSchema", element);

                if (email != null)
                    break;
            }
        }
    } catch (Exception e) {
        log.warn("cannot parse body: %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Body cannot be parsed");
        return;
    }

    //Return an error if there's no email address specified!
    if (email == null || email.length() == 0) {
        log.warn("No Email address is specified in the Request, %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "No Email address is specified in the Request");
        return;
    }

    //Return an error if the response schema doesn't match ours!
    if (responseSchema != null && responseSchema.length() > 0) {

        if (!(responseSchema.equals(NS_MOBILE) || responseSchema.equals(NS_OUTLOOK))) {
            log.warn("Requested response schema not available " + responseSchema);
            sendError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "Requested response schema not available " + responseSchema);
            return;
        }
    }

    log.debug("Authenticating user");
    Account acct = authenticate(req, resp, responseSchema);
    if (acct == null) {
        return;
    }
    log.debug("Authentication finished successfully");

    log.debug("content length: %d, content type: %s", req.getContentLength(), req.getContentType());
    if (req.getContentLength() == 0 || req.getContentType() == null) {
        log.warn("No suitable content found in the request");
        sendError(resp, 600, "No suitable content found in the request");
        return;
    }

    try {
        if (!(AccountUtil.addressMatchesAccount(acct, email) || acct.isAvailabilityServiceProvider())) { //Exchange server sends dummy email address from service account.
            log.warn(email + " doesn't match account addresses for user " + acct.getName());
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    email + " doesn't match account addresses");
            return;
        }
    } catch (ServiceException e) {
        log.warn("Account access error; user=" + acct.getName(), e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Account access error; user=" + acct.getName());
        return;
    }

    String respDoc = null;
    try {
        String serviceUrl = getServiceUrl(acct, responseSchema);
        String displayName = acct.getDisplayName() == null ? email : acct.getDisplayName();
        if (displayName.contains("@")) {
            displayName = displayName.substring(0, displayName.indexOf("@"));
        }
        log.debug("displayName: %s, email: %s, serviceUrl: %s", displayName, email, serviceUrl);
        if (isEwsClient(responseSchema)) {
            respDoc = createResponseDocForEws(displayName, email, serviceUrl, acct);
        } else {
            respDoc = createResponseDoc(displayName, email, serviceUrl);
        }
    } catch (Exception e) {
        log.warn(e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.info("Response: %s", respDoc);
    log.debug("response length: %d", respDoc.length());

    try {
        ByteUtil.copy(new ByteArrayInputStream(respDoc.getBytes("UTF-8")), true, resp.getOutputStream(), false);
    } catch (IOException e) {
        log.error("copy response error", e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.debug("setting content type to text/xml");
    resp.setContentType("text/xml");
    log.info("sending autodiscover response...");
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Override this method if you want to check the request before it is passed 
 * to commons-fileupload parser./*from  w w w.jav  a2  s . co  m*/
 * 
 * @param request
 * @throws RuntimeException
 */
public void checkRequest(HttpServletRequest request) {
    logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") procesing a request with size: "
            + request.getContentLength() + " bytes.");
    if (request.getContentLength() > maxSize) {
        throw new UploadSizeLimitException(maxSize, request.getContentLength());
    }
}

From source file:com.centurylink.mdw.hub.servlet.RestServlet.java

protected String handleRequest(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> metaInfo) throws ServiceException, IOException {

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug(/*w w  w  .java2  s  .c  om*/
                getClass().getSimpleName() + " " + request.getMethod() + ":\n   " + request.getRequestURI()
                        + (request.getQueryString() == null ? "" : ("?" + request.getQueryString())));
    }

    String requestString = null;
    // DELETE can have a body in some containers
    if (!"GET".equalsIgnoreCase(request.getMethod())) {
        BufferedReader reader = request.getReader();
        StringBuffer requestBuffer = new StringBuffer(
                request.getContentLength() < 0 ? 0 : request.getContentLength());
        String line;
        while ((line = reader.readLine()) != null)
            requestBuffer.append(line).append('\n');

        // log request
        requestString = requestBuffer.toString();
        if (logger.isMdwDebugEnabled()) {
            logger.mdwDebug(
                    getClass().getSimpleName() + " " + request.getMethod() + " Request:\n" + requestString);
        }
    }

    authenticate(request, metaInfo, requestString);
    if (metaInfo.containsKey(Listener.METAINFO_REQUEST_PAYLOAD)) {
        requestString = metaInfo.get(Listener.METAINFO_REQUEST_PAYLOAD);
        metaInfo.remove(Listener.METAINFO_REQUEST_PAYLOAD);
    }

    Set<String> reqHeaderKeys = new HashSet<String>(metaInfo.keySet());
    String responseString = new ListenerHelper().processEvent(requestString, metaInfo);
    populateResponseHeaders(reqHeaderKeys, metaInfo, response);
    if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) == null)
        response.setContentType("application/json");
    else
        response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE));

    if (metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE) != null
            && !metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE).equals("0"))
        response.setStatus(Integer.parseInt(metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE)));

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug(
                getClass().getSimpleName() + " " + request.getMethod() + " Response:\n" + responseString);
    }

    return responseString;
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

private HttpRequest newProxyRequest(final HttpServletRequest servletRequest, final String proxyRequestUri)
        throws IOException {
    final String method = servletRequest.getMethod();
    if (null != servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH)
            || null != servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING)) {
        //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
        final HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        r.setEntity(new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        return r;
    } else {/*from w  w w .j a v a  2 s  .  c o  m*/
        return new BasicHttpRequest(method, proxyRequestUri);
    }
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data./*from  w  ww.  java  2  s  .co m*/
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

From source file:com.couchbase.capi.servlet.CAPIServlet.java

protected void handleBulkDocs(HttpServletRequest req, HttpServletResponse resp, String database)
        throws ServletException, IOException {

    if (!req.getMethod().equals("POST")) {
        throw new UnsupportedOperationException("_bulk_docs must be POST");
    }/*from w w w.j  a v a 2 s  .c om*/

    logger.trace("Got bulk docs request for " + database);

    resp.setStatus(HttpServletResponse.SC_CREATED);
    resp.setContentType("application/json");

    OutputStream os = resp.getOutputStream();
    InputStream is = req.getInputStream();

    int requestLength = req.getContentLength();
    byte[] buffer = new byte[requestLength];
    IOUtils.readFully(is, buffer, 0, requestLength);

    @SuppressWarnings("unchecked")
    Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class);

    logger.trace("parsed value is " + parsedValue);

    try {
        List<Object> responseList = capiBehavior.bulkDocs(database,
                (ArrayList<Map<String, Object>>) parsedValue.get("docs"));
        if (responseList == null) {
            sendNotFoundResponse(resp, "missing");
            return;
        }
        mapper.writeValue(os, responseList);
    } catch (UnavailableException e) {
        sendServiceUnavailableResponse(resp, "too many concurrent requests");
    }
}

From source file:org.iita.struts.interceptor.GearsFileUploadInterceptor.java

/**
 * @param request//  w  w  w  .ja v  a2s . c  o  m
 * @param validation
 * @param ac
 * 
 */
@SuppressWarnings("unchecked")
private File doGearsUpload(HttpServletRequest request, ValidationAware validation, ActionContext ac) {
    // this is our extension for Gears uploads
    String fileName = request.getHeader("gears-filename");
    if (fileName != null) {
        String contentType = request.getHeader("gears-contentType");
        if (contentType == null)
            contentType = "application/x-binary";
        String inputName = request.getHeader("gears-inputName");
        if (inputName == null)
            inputName = "uploads";

        log.info("Gears filename: " + fileName);
        log.info("Gears contentType: " + contentType);
        log.info("Content-length: " + request.getContentLength());
        try {
            ServletInputStream uploadStream = request.getInputStream();
            File tempFile = File.createTempFile("gears.", ".upload");
            tempFile.deleteOnExit();
            FileOutputStream tempStream = new FileOutputStream(tempFile);
            byte[] b = new byte[2048];
            int len = 0, total = 0;
            do {
                len = uploadStream.read(b);
                if (len > 0) {
                    tempStream.write(b, 0, len);
                    total += len;
                }
            } while (len > 0);
            uploadStream.close();
            tempStream.flush();
            tempStream.close();
            log.debug("File uploaded from stream.");

            if (request.getContentLength() != total) {
                log.warn("Upload not complete? " + total + " received of " + request.getContentLength());
                tempFile.delete();
                tempFile = null;
                return null;
            }
            if (acceptFile(tempFile, contentType, inputName, validation, ac.getLocale())) {
                Map parameters = ac.getParameters();

                parameters.put(inputName, new File[] { tempFile });
                parameters.put(inputName + "ContentType", contentType);
                parameters.put(inputName + "FileName", fileName);
                return tempFile;

            }
        } catch (IOException e) {
            log.error(e);
        }
    }
    return null;
}

From source file:org.red5.server.net.rtmpt.RTMPTServlet.java

/**
 * Poll RTMPT session for updates./*from   w  w w.j a v a  2  s .c  om*/
 * 
 * @param req
 *            Servlet request
 * @param resp
 *            Servlet response
 * @throws IOException
 *             I/O exception
 */
protected void handleIdle(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    log.debug("handleIdle");
    // skip sent data
    skipData(req);
    // get associated connection
    RTMPTConnection conn = getConnection();
    if (conn != null) {
        conn.dataReceived();
        conn.updateReadBytes(req.getContentLength());
        // return pending
        returnPendingMessages(conn, resp);
    } else {
        handleBadRequest(String.format("Idle: unknown client session: %s", requestInfo.get().getSessionId()),
                resp);
    }
}