Example usage for javax.servlet ServletRequest getContentLength

List of usage examples for javax.servlet ServletRequest getContentLength

Introduction

In this page you can find the example usage for javax.servlet ServletRequest 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.jaspersoft.jasperserver.war.MultipartRequestWrapperFilter.java

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

    // unwrap multipart request
    try {//w w w  .  j a va 2 s . c o m
        if (multipartResolver.isMultipart((HttpServletRequest) request) && request.getContentLength() > 0) {
            MultipartHttpServletRequest multipartHttpServletRequest = multipartResolver
                    .resolveMultipart((HttpServletRequest) request);
            request = new MultipartHttpServletRequestWrapper(multipartHttpServletRequest);

            // support for file resource and olap schema wizards
            {
                MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
                Iterator iterator = mreq.getFileNames();
                String fieldName = null;
                while (iterator.hasNext()) {
                    fieldName = (String) iterator.next();
                    // Assuming only 1 file is uploaded per page
                    // can be modified to handle multiple uploads per request
                }
                MultipartFile file = mreq.getFile(fieldName);
                if (file != null) {
                    String fullName = file.getOriginalFilename();
                    if (fullName != null && fullName.trim().length() != 0) {
                        int lastIndex = fullName.lastIndexOf(".");
                        if (lastIndex != -1) {
                            String fileName = fullName.substring(0, lastIndex);
                            String extension = fullName.substring(lastIndex + 1);
                            mreq.setAttribute(JasperServerConst.UPLOADED_FILE_NAME, fileName);
                            mreq.setAttribute(JasperServerConst.UPLOADED_FILE_EXT, extension);
                        } else {
                            mreq.setAttribute(JasperServerConst.UPLOADED_FILE_NAME, fullName);
                        }
                    }
                }
            }

        }
    } catch (MultipartException e) {
        log.error("Cannot resolve multipart data", e);
    }

    chain.doFilter(request, response);

}

From source file:com.loadtesting.showcase.springmvc.filter.PatternFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *//*ww w  . ja va 2 s  . co  m*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ExampleKpiCapturers caps = new ExampleKpiCapturers(request, PatternLayer.list());
    WebProfilingFormat webFormat;
    try {
        caps.startDefaultCapturer();

        CountingOutputStream cos = new CountingOutputStream(response.getOutputStream());
        chain.doFilter(request, response);
        webFormat = new WebProfilingFormat(request.getContentLength(), cos.getByteCount());
    } finally {
        caps.endDefaultCapturer();
    }

    sendReports(webFormat, caps);
}

From source file:com.loadtesting.showcase.springmvc.filter.LoadTestFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *//*  w  w  w  . j ava 2 s . co  m*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ExampleKpiCapturers caps = new ExampleKpiCapturers(request, LoadTestLayer.list());
    WebProfilingFormat webFormat;
    try {
        caps.startDefaultCapturer();

        CountingOutputStream cos = new CountingOutputStream(response.getOutputStream());
        chain.doFilter(request, response);
        webFormat = new WebProfilingFormat(request.getContentLength(), cos.getByteCount());
    } finally {
        caps.endDefaultCapturer();
    }

    sendReports(webFormat, caps);
}

From source file:com.curl.orb.servlet.DefaultInstanceManagementFilter.java

@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // accept just HTTP.
    if (!((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)))
        throw new ServletException("The request is not HTTP protocol.");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    InstanceManagementRequest instanceManagementRequest = null;
    // serialize the request object and set to the attribute
    try {//w  w w .ja  va2 s.c o  m
        if (request.getContentLength() == -1) {
            // forward to requested page.
            request.getRequestDispatcher(httpRequest.getServletPath()).forward(request, response);
            return;
        }
        instanceManagementRequest = (InstanceManagementRequest) serializer
                .deserialize(httpRequest.getInputStream());
        // debug request object (instanceManagementRequest.toString())
        log.debug("Curl ORB Request object [" + instanceManagementRequest + "]");
        httpRequest.setAttribute(InstanceManagementServlet.REQUEST_OBJECT, instanceManagementRequest);
    } catch (SerializerException e) {
        // NOTE: 
        //  Cannot handle the exception when "stream response" mode. 
        //  Clients cannot receive the error.
        setResponse((HttpServletResponse) response,
                new InstanceManagementException("Could not deserialize the object from Curl.", e), null);
        return;
    }

    try {
        // do filters and servlets
        chain.doFilter(httpRequest, response);
        // deserialize the object and return the response
        setResponse((HttpServletResponse) response,
                httpRequest.getAttribute(InstanceManagementServlet.RESPONSE_OBJECT),
                (Map<String, Object>) httpRequest
                        .getAttribute(InstanceManagementServlet.RESPONSE_SUBORDINATE_OBJECT));
    } catch (Exception e) {
        setResponse((HttpServletResponse) response, e, null);
    }
}

From source file:eu.freme.broker.tools.ratelimiter.RateLimitingFilter.java

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

    if (rateLimiterEnabled) {

        HttpServletRequest request = (HttpServletRequest) req;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        username = auth.getName();//from w  w w . j a v a2s . c om
        if (username.equals("anonymousUser")) {
            username = req.getRemoteAddr();
        } else {
            User user = ((User) auth.getPrincipal());
            username = user.getName();
        }

        userRole = ((SimpleGrantedAuthority) auth.getAuthorities().toArray()[0]).getAuthority();

        long size = req.getContentLength();
        if (size == 0) {
            try {
                size = request.getHeader("input").length();
            } catch (NullPointerException e) {
                //Then the size is truly 0
            }
        }
        try {
            rateLimiterInMemory.addToStoredRequests(username, new Date().getTime(), size,
                    request.getRequestURI(), userRole);
        } catch (TooManyRequestsException e) {
            HttpServletResponse response = (HttpServletResponse) res;
            exceptionHandlerService.writeExceptionToResponse(request, response, e);
            return;
        }
    }

    chain.doFilter(req, res);

}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;//from ww  w  .j  a va  2  s  .  c om
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/*from w w w .j a v a2  s.c o m*/

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        method = new ExtendedGetMethod();
    else
        method = new ExtendedPostMethod();

    method.setDecompress(false);

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
        connectionHeader = connectionHeader.toLowerCase();
        if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0)
            connectionHeader = null;
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    long contentLength = -1;
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if (dontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr))
            contentLength = request.getContentLength();

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                method.setRequestHeader(lhdr, val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
            }
        }
    }

    // Proxy headers
    method.setRequestHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor)
        method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr());

    if (method instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) method)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80)
        url.append(":" + httpRequest.getServerPort());
    if (httpRequest.getServletPath() != null) {
        url.append(httpRequest.getServletPath());
        method.setPath(httpRequest.getServletPath());
        if (httpRequest.getQueryString() != null) {
            url.append("?" + httpRequest.getQueryString());
            method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString());
        }
    }
    hostConfiguration.setHost(new URI(url.toString(), true));

    // SoapUI.log("PROXY to:" + url);

    monitor.fireBeforeProxy(request, response, method, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody()));
    capturedData.setResponseContent(new String(method.getDecompressedResponseBody()));

    monitor.fireAfterProxy(request, response, method, capturedData);

    if (!response.isCommitted()) {
        StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
        // capturedData = null;

        // copy headers to response
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        for (String name : responseHeaders.keySet()) {
            for (String header : responseHeaders.get(name))
                httpResponse.addHeader(name, header);
        }

        IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());
    }

    synchronized (this) {
        if (checkContentType(method)) {
            monitor.addMessageExchange(capturedData);
        }
    }
}

From source file:org.ajax4jsf.webapp.BaseFilter.java

private boolean isFileSizeRestricted(ServletRequest request, int maxSize) {
    if (maxSize != 0 && request.getContentLength() > maxSize) {
        return true;
    }/*from  w ww  .ja v  a 2 s  . com*/
    return false;
}

From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */// w  w w  . j  ava 2  s .  c  o m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null)
        return;

    // Render the generic servlet request properties
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis())));
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");
    Enumeration locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        if (first)
            first = false;
        else
            writer.print(", ");
        writer.print(locale.toString());
    }
    writer.println();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        writer.print("         parameter=" + name + "=");
        String values[] = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0)
                writer.print(", ");
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        writer.println("---------------------------------------------");
        HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());
        Cookie cookies[] = hrequest.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }
        names = hrequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());
    }
    writer.println("=============================================");

    // Log the resulting string
    writer.flush();
    filterConfig.getServletContext().log(sw.getBuffer().toString());
    log.info(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(request, response);

}

From source file:org.webdavaccess.servlet.WebdavServlet.java

/**
 * overwrites propNode and type, parsed from xml input stream
 * //from   w  w  w  .j a  va  2 s  .c  o m
 * @param propNode
 * @param type
 * @param req
 *            HttpServletRequest
 * @throws ServletException
 */
private PropertyNodeType getPropertyNodeAndType(ServletRequest req) throws ServletException {
    PropertyNodeType nodeType = new PropertyNodeType(FIND_ALL_PROP);
    if (req.getContentLength() != 0) {
        DocumentBuilder documentBuilder = getDocumentBuilder();
        try {
            Document document = documentBuilder.parse(new InputSource(req.getInputStream()));
            // Get the root element of the document
            Element rootElement = document.getDocumentElement();
            NodeList childList = rootElement.getChildNodes();

            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    if (currentNode.getNodeName().endsWith("prop")) {
                        nodeType.setType(FIND_BY_PROPERTY);
                        nodeType.setNode(currentNode);
                    }
                    if (currentNode.getNodeName().endsWith("propname")) {
                        nodeType.setType(FIND_PROPERTY_NAMES);
                    }
                    if (currentNode.getNodeName().endsWith("allprop")) {
                        nodeType.setType(FIND_ALL_PROP);
                    }
                    break;
                }
            }
        } catch (Exception e) {

        }
    } else {
        // no content, which means it is a allprop request
        nodeType.setType(FIND_ALL_PROP);
    }
    return nodeType;
}