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:org.sprintapi.api.http.HttpServlet.java

protected void doService(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ErrorException, IOException {

    final RequestHolder<Object> request = new RequestHolder<Object>(getUri(httpRequest));
    request.setContext(httpRequest.getContextPath());

    // Resolve incoming URL and get resource descriptor
    final ResourceDescriptor resourceDsc = resolve(request.getUri());

    // Does the requested resource exist?
    if (resourceDsc == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_FOUND);
    }//  w w  w.ja  v  a2s. c  o m

    // Is requested method supported?
    if (httpRequest.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        request.setMethod(Method.valueOf(httpRequest.getMethod().toUpperCase(Locale.US)));

    } catch (IllegalArgumentException ex) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    if (request.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    // Get supported methods for requested resource
    Map<Method, MethodDescriptor<?, ?>> methods = resourceDsc.methods();

    // Get requested method descriptors for the resource
    MethodDescriptor<?, ?> methodDsc = (methods != null) ? methods.get(request.getMethod()) : null;

    // Is requested method supported?
    if ((methodDsc == null)) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    ContentAdapter<InputStream, ?> inputContentAdapter = null;

    // Is request body expected?
    if (request.getMethod().isRequestBody()) {
        String requestContentType = httpRequest.getContentType();

        inputContentAdapter = (methodDsc.consumes() != null) ? methodDsc.consumes().get(requestContentType)
                : null;
        if (inputContentAdapter == null) {
            throw new ErrorException(request.getUri(), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

    } else if (httpRequest.getContentLength() > 0) {
        // Unexpected request body
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    ContentAdapter<?, InputStream> outputContentAdapter = null;

    String responseContentType = null;

    // Is response body expected?
    if (request.getMethod().isResponseBody()) {
        // Check Accept header
        HttpAcceptHeader acceptHeader = HttpAcceptHeader
                .read(httpRequest.getHeader(ContentDescriptor.META_ACCEPT));
        if (acceptHeader != null) {

            Map<String, ?> produces = methodDsc.produces();

            // Response content negotiation 
            if (produces != null) {
                int weight = 0;

                for (String ct : produces.keySet()) {
                    int tw = acceptHeader.accept(ct);
                    if (tw > weight) {
                        weight = tw;
                        responseContentType = ct;
                        outputContentAdapter = (ContentAdapter<?, InputStream>) produces.get(ct);
                    }
                }
            }
            if (outputContentAdapter == null) {
                throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_ACCEPTABLE);
            }
        }
    }

    if (inputContentAdapter != null) {
        ContentHolder<Object> lc = new ContentHolder<Object>();
        lc.setBody(inputContentAdapter.transform(request.getUri(), httpRequest.getInputStream()));
        request.setContent(lc);
    }

    // Invoke resource method
    Response response = methodDsc.invoke((Request) request);

    if (response == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // Write response status
    int responseStatus = (response.getStatus() > 0) ? response.getStatus() : HttpServletResponse.SC_OK;
    httpResponse.setStatus(responseStatus);

    if (response.getContent() == null) {
        return;
    }

    // Write response headers
    if (response.getContent().getMetaNames() != null) {
        for (String metaName : response.getContent().getMetaNames()) {
            Object metaValue = response.getContent().getMeta(metaName);
            if (metaValue != null) {
                if (metaValue instanceof Date) {
                    httpResponse.setHeader(metaName, HttpDate.RFC1123_FORMAT.format(((Date) metaValue)));
                } else {
                    httpResponse.setHeader(metaName, metaValue.toString());
                }
            }
        }
    }

    if ((HttpServletResponse.SC_CREATED == responseStatus)) {
        httpResponse.setHeader(ContentDescriptor.META_LOCATION, response.getContext() + response.getUri());
    }

    if ((response.getContent().getBody() == null) || (HttpServletResponse.SC_NOT_MODIFIED == responseStatus)) {
        return;
    }

    // Write response body
    if (outputContentAdapter != null) {
        httpResponse.setHeader(ContentDescriptor.META_CONTENT_TYPE, responseContentType);
        InputStream is = ((ContentAdapter<Object, InputStream>) outputContentAdapter)
                .transform(request.getUri(), response.getContent().getBody());
        if (is != null) {
            CopyUtils.copy(is, httpResponse.getOutputStream());
        }
    }
}

From source file:petascope.PetascopeInterface.java

@Override
public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException {
    setServletURL(httpRequest);//ww  w.  j  a v  a 2  s.  c  om
    setCORSHeader(httpResponse);

    // NOTE: admin can change Service Prodiver, Identification then session *reloadPage* will exist and value is true
    HttpSession session = httpRequest.getSession();
    if (session.getAttribute("reloadMetadata") != null
            && Boolean.valueOf(session.getAttribute("reloadMetadata").toString()) == true) {
        try {
            meta = new DbMetadataSource(ConfigManager.METADATA_DRIVER, ConfigManager.METADATA_URL,
                    ConfigManager.METADATA_USER, ConfigManager.METADATA_PASS, false);

            // Then remove session as it does not need anymore
            session.removeAttribute("reloadMetadata");
        } catch (Exception e) {
            log.error("Stack trace: {}", e);
            throw new ServletException("Error initializing metadata database", e);
        }
    } else {
        // it is just normal query without updating metadata then session is null
        meta.clearCache();
    }

    String request = null;
    String requestBody = null;

    /* Process the request */
    try {
        try {
            //Check if this is a wms request and handled it accordingly
            if (wms13Adapter.handleGetRequests(httpRequest, httpResponse)) {
                //this is a wms13 request, and it was handled in the handleGetRequests
                //stop further execution
                return;
            }

            meta.ensureConnection();

            requestBody = IOUtils.toString(httpRequest.getReader());

            log.trace("POST Request length: {}", httpRequest.getContentLength());
            log.trace("POST request body  : \n------START REQUEST--------\n{}\n------END REQUEST------\n",
                    requestBody);
            log.trace("GET Query string   : {}", httpRequest.getQueryString());

            Map<String, String> params = buildParameterDictionary(requestBody);
            Map<String, String> paramMap = buildParameterMap(httpRequest);
            log.trace("Request parameters : {}", params);

            // GET interface processing
            String service = paramMap.get(KVPSymbols.KEY_SERVICE);

            // REST interface checks
            // get the uri contained after the context name i.e after petascope
            // in example.com/petascope/rest/wcs/... returns [rest,wcs]
            String pathInfo = httpRequest.getPathInfo();
            log.debug("Analyzing path info \"{}\" for REST interface checks.", pathInfo);
            // Java API: "This method returns null if there was no extra path information."
            String[] prsUrl = (null == pathInfo) ? new String[0] : pathInfo.substring(1).split("/");
            ArrayList<String> splitURI = new ArrayList<String>(Arrays.asList(prsUrl));
            if (service == null && splitURI.size() > 1
                    && (splitURI.get(0).equalsIgnoreCase(RESTProtocolExtension.REST_PROTOCOL_WCS_IDENTIFIER)
                            || splitURI.get(0).equals(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER))) {
                service = splitURI.get(0).toUpperCase();
            }

            if (service != null) {
                // Removed WPS support as it doesn't work. Using 52n instead -- DM 2012-may-24
                //                    if (service.equals("WPS")) {
                //                        WpsServer wpsServer = new WpsServer(httpResponse, httpRequest);
                //                        request = wpsServer.request;
                //                    } else
                if (service.equals(petascope.wcs2.parsers.BaseRequest.SERVICE)) {
                    // extract version
                    String version = null;
                    String operation = paramMap.get(WCPS_REQUEST_GET_PARAMETER);

                    //This might be a REST operation, try to get the operation from the uri
                    if (operation == null && splitURI.size() > 2) {
                        operation = RESTProtocolExtension
                                .mapRestResourcesToCoverageOperation(httpRequest.getRequestURI());
                    }

                    if (operation.equals(RequestHandler.GET_CAPABILITIES)) {
                        version = paramMap.get(KVPSymbols.KEY_ACCEPTVERSIONS);
                        if (version == null && splitURI.size() > 1) {
                            version = splitURI.get(1);
                        }
                        log.trace(KVPSymbols.KEY_ACCEPTVERSIONS + ": " + version);
                        if (version == null) {
                            version = ConfigManager.WCS_DEFAULT_VERSION;
                        } else {
                            String[] versions = version.split(KVPSymbols.VERSIONS_SEP);
                            version = "";
                            for (String v : versions) {
                                if (ConfigManager.WCS_VERSIONS.contains(v) && !v.startsWith("1")) { // the WCS 1.1 server doesn't support GET-KVP
                                    version = v;
                                    break;
                                }
                            }
                        }
                    } else if (operation.equals(RequestHandler.DESCRIBE_COVERAGE)
                            || operation.equals(RequestHandler.PROCESS_COVERAGE)
                            || operation.equals(RequestHandler.GET_COVERAGE)
                            || operation.equals(RequestHandler.INSERT_COVERAGE)
                            || operation.equals(RequestHandler.DELETE_COVERAGE)
                            || operation.equals(RequestHandler.UPDATE_COVERAGE)) {
                        version = paramMap.get(KVPSymbols.KEY_VERSION);
                        if (version == null && splitURI.size() > 1) {
                            version = splitURI.get(1);
                        }
                    }

                    // handle request
                    request = StringUtil.urldecode(httpRequest.getQueryString(), httpRequest.getContentType());
                    handleWcsRequest(version, paramMap.get(WCPS_REQUEST_GET_PARAMETER), request, httpResponse,
                            httpRequest);
                    return;
                }
            }

            // To preserve compatibility with previous client versions, we allow
            // GET requests with parameter "query"
            String request2 = null;
            request2 = paramMap.get(WCPS_QUERY_GET_PARAMETER);
            if (request2 == null) {
                request2 = StringUtil.urldecode(params.get(WCPS_QUERY_GET_PARAMETER),
                        httpRequest.getContentType());
            }

            // splitURI list can be of size 0 if there is not path info in the HTTP request.
            if (request2 == null && splitURI.size() > 0
                    && splitURI.get(0).equalsIgnoreCase(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER)) {
                if (splitURI.size() > 2
                        && splitURI.get(1).equals(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER)) {
                    String queryDecoded = StringUtil.urldecode(splitURI.get(2), httpRequest.getContentType());
                    request2 = RasUtil.abstractWCPSToRasql(queryDecoded, wcps);
                }
            } else if (request2 != null) {
                log.debug("Received Abstract Syntax Request via GET: \n\t\t{}", request2);
                request2 = RasUtil.abstractWCPStoXML(request2);
            }
            request = StringUtil.urldecode(params.get(WCPS_REQUEST_GET_PARAMETER),
                    httpRequest.getContentType());
            if (request == null && request2 != null) {
                request = request2;
            }

            // Empty request ?
            if (request == null && (requestBody == null || requestBody.length() == 0)) {
                if (paramMap.size() > 0) {
                    throw new WCSException(ExceptionCode.NoApplicableCode,
                            "Couldn't understand the recieved request, is the service attribute missing?");
                } else {
                    printUsage(httpResponse, request);
                    return;
                }
            }

            //   No parameters, just XML in the request body:
            if (request == null && requestBody != null && requestBody.length() > 0) {
                request = StringUtil.urldecode(requestBody, httpRequest.getContentType());
            }

            log.debug("Petascope Request: \n------START REQUEST--------\n{}" + "\n------END REQUEST------\n",
                    request);

            String root = XMLUtil.getRootElementName(request);
            log.debug("Root Element name: {}", root);
            if (root == null) {
                return;
            }
            if (root.equals(XMLSymbols.LABEL_ENVELOPE)) {
                handleWcs2Request(request, httpResponse, httpRequest);
            } else if (root.endsWith(XMLSymbols.LABEL_PROCESSCOVERAGE_REQUEST)) {
                /* ProcessCoverages is defined in the WCPS extension to WcsServer */
                handleProcessCoverages(request, httpResponse);
            } else if (root.equals(RequestHandler.GET_CAPABILITIES)) {
                // extract the version that the client prefers
                Document doc = XMLUtil.buildDocument(null, request);
                String version = "";
                List<Element> acceptVersions = XMLUtil.collectAll(doc.getRootElement(),
                        XMLSymbols.LABEL_ACCEPT_VERSIONS);
                if (!acceptVersions.isEmpty()) {
                    List<Element> versions = XMLUtil.collectAll(ListUtil.head(acceptVersions),
                            XMLSymbols.LABEL_VERSION);
                    for (Element v : versions) {
                        String val = XMLUtil.getText(v);
                        if (val != null && ConfigManager.WCS_VERSIONS.contains(val)) {
                            version = val;
                            break;
                        }
                    }
                } else {
                    version = ConfigManager.WCS_DEFAULT_VERSION; // by default the latest supported by petascope
                }
                handleWcsRequest(version, root, request, httpResponse, httpRequest);
            } else if (root.equals(RequestHandler.DESCRIBE_COVERAGE) || root.equals(RequestHandler.GET_COVERAGE)
                    || root.equals(RequestHandler.PROCESS_COVERAGE)
                    || root.equals(RequestHandler.INSERT_COVERAGE)
                    || root.equals(RequestHandler.DELETE_COVERAGE)
                    || root.equals(RequestHandler.UPDATE_COVERAGE)) {
                Document doc = XMLUtil.buildDocument(null, request);
                String version = doc.getRootElement().getAttributeValue(KVPSymbols.KEY_VERSION);
                handleWcsRequest(version, root, request, httpResponse, httpRequest);
            } else {
                // error
                handleUnknownRequest(request, httpResponse);
            }
        } catch (WCSException e) {
            throw e;
        } catch (SecoreException e) {
            throw new WCSException(ExceptionCode.SecoreError, e);
        } catch (Exception e) {
            // Finally, cast all other exceptions into a WCSException
            log.error("Runtime error : {}", e.getMessage());
            throw new WCSException(ExceptionCode.RuntimeError,
                    "Runtime error while processing request: " + e.getMessage(), e);
        }
    } // And catch all WCSExceptions, to display to the client
    catch (WCSException e) {
        printError(httpResponse, request, e);
    }
}

From source file:org.apache.hadoop.test.mock.MockRequestMatcher.java

public void match(HttpServletRequest request) throws IOException {
    if (methods != null) {
        assertThat(//from www. java  2  s.co m
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " is not using one of the expected HTTP methods",
                methods, hasItem(request.getMethod()));
    }
    if (pathInfo != null) {
        assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                + " does not have the expected pathInfo", request.getPathInfo(), is(pathInfo));
    }
    if (requestURL != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected requestURL",
                request.getRequestURL().toString(), is(requestURL));
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL()
                            + " does not have the expected value for header " + name,
                    request.getHeader(name), is(headers.get(name)));
        }
    }
    if (cookies != null) {
        List<Cookie> requestCookies = Arrays.asList(request.getCookies());
        for (Cookie cookie : cookies) {
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " does not have the expected cookie " + cookie, requestCookies, hasItem(cookie));
        }
    }
    if (contentType != null) {
        String[] requestContentType = request.getContentType().split(";", 2);
        assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                + " does not have the expected content type", requestContentType[0], is(contentType));
    }
    if (characterEncoding != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected character encoding",
                request.getCharacterEncoding(), equalToIgnoringCase(characterEncoding));
    }
    if (contentLength != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected content length",
                request.getContentLength(), is(contentLength));
    }
    if (attributes != null) {
        for (String name : attributes.keySet()) {
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " is missing attribute '" + name + "'", request.getAttribute(name), notNullValue());
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL()
                            + " has wrong value for attribute '" + name + "'",
                    request.getAttribute(name), is(request.getAttribute(name)));
        }
    }
    // Note: Cannot use any of the expect.getParameter*() methods because they will read the
    // body and we don't want that to happen.
    if (queryParams != null) {
        String queryString = request.getQueryString();
        Map<String, String[]> requestParams = parseQueryString(queryString == null ? "" : queryString);
        for (String name : queryParams.keySet()) {
            String[] values = requestParams.get(name);
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " query string "
                    + queryString + " is missing parameter '" + name + "'", values, notNullValue());
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL() + " query string "
                            + queryString + " is missing a value for parameter '" + name + "'",
                    Arrays.asList(values), hasItem(queryParams.get(name)));
        }
    }
    if (formParams != null) {
        String paramString = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        Map<String, String[]> requestParams = parseQueryString(paramString == null ? "" : paramString);
        for (String name : formParams.keySet()) {
            String[] actualValues = requestParams.get(name);
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL() + " form params "
                            + paramString + " is missing parameter '" + name + "'",
                    actualValues, notNullValue());
            String[] expectedValues = formParams.get(name);
            for (String expectedValue : expectedValues) {
                assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " form params "
                        + paramString + " is missing a value " + expectedValue + " for parameter '" + name
                        + "'", Arrays.asList(actualValues), hasItem(expectedValue));
            }
        }
    }
    if (entity != null) {
        if (contentType != null && contentType.endsWith("/xml")) {
            String expectEncoding = characterEncoding;
            String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding));
            String actualEncoding = request.getCharacterEncoding();
            String actual = IOUtils.toString(request.getInputStream(),
                    actualEncoding == null ? UTF8.name() : actualEncoding);
            assertThat(the(actual), isEquivalentTo(the(expect)));
        } else if (contentType != null && contentType.endsWith("/json")) {
            String expectEncoding = characterEncoding;
            String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding));
            String actualEncoding = request.getCharacterEncoding();
            String actual = IOUtils.toString(request.getInputStream(),
                    actualEncoding == null ? UTF8.name() : actualEncoding);
            //        System.out.println( "EXPECT=" + expect );
            //        System.out.println( "ACTUAL=" + actual );
            assertThat(actual, sameJSONAs(expect));
        } else if (characterEncoding == null || request.getCharacterEncoding() == null) {
            byte[] bytes = IOUtils.toByteArray(request.getInputStream());
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " content does not match the expected content", bytes, is(entity));
        } else {
            String expect = new String(entity, characterEncoding);
            String actual = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " content does not match the expected content", actual, is(expect));
        }
    }
}

From source file:org.wings.session.MultipartRequest.java

/**
 * Parses passed request and stores contained parameters.
 *
 * @throws IOException On unrecoverable parsing bugs due to old Tomcat version.
 *///from www  . java 2  s .co m
protected void processRequest(HttpServletRequest req) throws IOException {
    String type = req.getContentType();
    if (type == null || !type.toLowerCase().startsWith("multipart/form-data")) {
        urlencodedRequest = true;
        return;
    }

    urlencodedRequest = false;
    parameters = new HashMap<String, List>();
    files = new HashMap<String, UploadedFile>();

    for (Iterator iterator = req.getParameterMap().entrySet().iterator(); iterator.hasNext(); /**/) {
        Map.Entry entry = (Map.Entry) iterator.next();
        parameters.put((String) entry.getKey(), new ArrayList(Arrays.asList((String[]) entry.getValue())));
    }

    String boundaryToken = extractBoundaryToken(type);
    if (boundaryToken == null) {
        /*
         * this could happen due to a bug in Tomcat 3.2.2 in combination
         * with Opera.
         * Opera sends the boundary on a separate line, which is perfectly
         * correct regarding the way header may be constructed 
         * (multiline headers). Alas, Tomcat fails to read the header in 
         * the content type line and thus we cannot read it.. haven't 
         * checked later versions of Tomcat, but upgrading is
         * definitly needed, since we cannot do anything about it here.
         * (JServ works fine, BTW.) (Henner)
         */
        throw new IOException("Separation boundary was not specified (BUG in Tomcat 3.* with Opera?)");
    }

    MultipartInputStream mimeStream = null;

    ByteArrayOutputStream headerByteArray;
    StringBuilder content = new StringBuilder();
    HashMap headers = null;
    int currentByte = 0;
    int currentPos = 0;
    int currentTransformByte = 0;
    String currentParam = null;
    File uploadFile = null;
    OutputStream fileStream = null;
    boolean done;
    int last = -1;

    try {
        mimeStream = new MultipartInputStream(req.getInputStream(), req.getContentLength(), maxSize);
        while (currentByte != -1) {
            // Read MIME part header line
            done = false;
            headerByteArray = new ByteArrayOutputStream();
            while ((currentByte = mimeStream.read()) != -1 && !done) {
                headerByteArray.write(currentByte);
                done = (last == '\n' && currentByte == '\r');
                last = currentByte;
            }
            if (currentByte == -1)
                break;

            headers = parseHeader(headerByteArray.toString(req.getCharacterEncoding()));
            headerByteArray.reset();
            currentParam = (String) headers.get("name");

            if (headers.size() == 1) { // .. it's not a file
                byte[] bytes = new byte[req.getContentLength()];
                currentPos = 0;
                while ((currentByte = mimeStream.read()) != -1) {
                    bytes[currentPos] = (byte) currentByte;
                    currentPos++;
                    if (currentPos >= boundaryToken.length()) {
                        int i;
                        for (i = 0; i < boundaryToken.length(); i++) {
                            if (boundaryToken
                                    .charAt(boundaryToken.length() - i - 1) != bytes[currentPos - i - 1]) {
                                i = 0;
                                break;
                            }
                        }
                        if (i == boundaryToken.length()) { // end of part ..
                            ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0,
                                    currentPos - boundaryToken.length() - 4);
                            InputStreamReader ir;
                            if (req.getCharacterEncoding() != null)
                                // It's common behaviour of browsers to encode their form input in the character
                                // encoding of the page, though they don't declare the used characterset explicetly
                                // for backward compatibility.
                                ir = new InputStreamReader(bais, req.getCharacterEncoding());
                            else
                                ir = new InputStreamReader(bais);
                            content.setLength(0);
                            while ((currentTransformByte = ir.read()) != -1) {
                                content.append((char) currentTransformByte);
                            }

                            putParameter(currentParam, content.toString());
                            break;
                        }
                    }
                }
            } else { // .. it's a file
                String filename = (String) headers.get("filename");
                if (filename != null && filename.length() != 0) {
                    // The filename may contain a full path.  Cut to just the filename.
                    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
                    if (slash > -1) {
                        filename = filename.substring(slash + 1);
                    }
                    String name = (String) headers.get("name");

                    String contentType = (String) headers.get("content-type");
                    try {
                        uploadFile = File.createTempFile("wings_uploaded", "tmp");
                    } catch (IOException e) {
                        log.error("couldn't create temp file in '" + System.getProperty("java.io.tmpdir")
                                + "' (CATALINA_TMPDIR set correctly?)", e);
                        throw e;
                    }

                    UploadedFile upload = new UploadedFile(filename, contentType, uploadFile);
                    fileStream = new FileOutputStream(uploadFile);

                    fileStream = UploadFilterManager.createFilterInstance(name, fileStream);

                    AccessibleByteArrayOutputStream byteArray = new AccessibleByteArrayOutputStream();
                    byte[] bytes = null;

                    int blength = boundaryToken.length();
                    int i;
                    while ((currentByte = mimeStream.read()) != -1) {
                        byteArray.write(currentByte);
                        for (i = 0; i < blength; i++) {
                            if (boundaryToken.charAt(blength - i - 1) != byteArray.charAt(-i - 1)) {
                                i = 0;
                                if (byteArray.size() > 512 + blength + 2)
                                    byteArray.writeTo(fileStream, 512);
                                break;
                            }
                        }
                        if (i == blength) // end of part ..
                            break;
                    }
                    bytes = byteArray.toByteArray();
                    fileStream.write(bytes, 0, bytes.length - blength - 4);
                    fileStream.close();

                    files.put(name, upload);
                    putParameter(name, upload.toString());
                } else { // workaround for some netscape bug
                    int i;
                    int blength = boundaryToken.length();
                    while ((currentByte = mimeStream.read()) != -1) {
                        content.append((char) currentByte);
                        if (content.length() >= blength) {
                            for (i = 0; i < blength; i++) {
                                if (boundaryToken.charAt(blength - i - 1) != content
                                        .charAt(content.length() - i - 1)) {
                                    i = 0;
                                    break;
                                }
                            }
                            if (i == blength)
                                break;
                        }
                    }
                }
            }

            currentByte = mimeStream.read();
            if (currentByte == '\r' && mimeStream.read() != '\n')
                log.error("No line return char? " + currentByte);
            if (currentByte == '-' && mimeStream.read() != '-')
                log.error("?? No clue " + currentByte);
        }
    } catch (IOException ex) {
        // cleanup and store the exception for notification of SFileChooser
        log.warn("upload", ex);
        if (uploadFile != null)
            uploadFile.delete();
        setException(currentParam, ex);
    } finally {
        try {
            fileStream.close();
        } catch (Exception ign) {
        }
        try {
            mimeStream.close();
        } catch (Exception ign) {
        }
    }
}

From source file:ORG.oclc.os.SRW.SRWServlet.java

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request/*from  w ww  .j a v a2s .  c  o  m*/
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;
    if (isDebug)
        servletLog.debug("Enter: doPost()");
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    Message responseMsg = null;
    String contentType = req.getContentType().toLowerCase();
    if (log.isDebugEnabled())
        log.debug("in SRWServlet.doPost: contentType=" + contentType);
    if (contentType.indexOf("atom+xml") > 0) {
        msgContext = createMessageContext(getEngine(), req, res);
        if (!srwInfo.setSRWStuff(req, res, msgContext)) {
            servletLog.error("srwInfo.setSRWStuff failed!");
            return;
        }
        SRWDatabase db = (SRWDatabase) msgContext.getProperty("db");
        if (log.isDebugEnabled())
            log.debug("adding to database " + db);
        if (log.isDebugEnabled())
            log.debug("adding to database " + db.dbname);
        InputStream is = req.getInputStream();
        int len, offset = 0, totlen = req.getContentLength();
        byte[] b = new byte[totlen];
        while (totlen > 0) {
            len = is.read(b, offset, totlen);
            totlen -= len;
            offset += len;
        }
        db.add(b);
        if (db.httpHeaderSetter != null)
            db.httpHeaderSetter.setPostResponseHeaders(new String(b, "UTF-8"), req, res);
        res.setStatus(201);
        return;
    }

    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            servletLog.debug("No Engine!", se);
            throw se;
        }

        res.setBufferSize(1024 * 8); // provide performance boost.

        /** get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res);

        // ? OK to move this to 'getMessageContext',
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug)
                servletLog.debug("securityProvider:" + securityProvider);
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }

        /* Get request message
         */
        Message requestMsg = new Message(req.getInputStream(), false,
                req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));

        if (isDebug)
            servletLog.debug("Request Message:" + requestMsg);

        /* Set the request(incoming) message field in the context */
        /**********************************************************/
        msgContext.setRequestMessage(requestMsg);
        //String url = HttpUtils.getRequestURL(req).toString();
        String url = req.getRequestURL().toString();
        msgContext.setProperty(MessageContext.TRANS_URL, url);

        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /********************************************************/
            soapAction = getSoapAction(req);

            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            } else { // not a SOAP request
                String content = new String(((SOAPPart) (requestMsg.getSOAPPart())).getAsBytes());
                if (content.startsWith("<")) { // must be an ATOM request
                    return;
                }
                if (content.indexOf("query=") >= 0 || content.indexOf("scanClause=") >= 0) {
                    processMethodRequest(msgContext,
                            new LateContentParsingHttpServletRequestWrapper(req, content), res);
                    return;
                }

                // nothing I recognize
                AxisFault af = new AxisFault("Client.NoSOAPAction",
                        Messages.getMessage("noHeader00", "SOAPAction"), null, null);

                exceptionLog.error(Messages.getMessage("genFault00"), af);

                throw af;
            }

            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }

            srwInfo.setSRWStuff(req, res, msgContext);

            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug)
                servletLog.debug("Invoking Axis Engine.");
            //here we run the message by the engine
            engine.invoke(msgContext);
            if (isDebug)
                servletLog.debug("Return from Axis Engine.");
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                //tell everyone that something is wrong
                throw new Exception(Messages.getMessage("noResponse01"));
            }
        } catch (AxisFault fault) {
            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(fault);
            }
        } catch (Exception e) {
            //other exceptions are internal trouble
            responseMsg = msgContext.getResponseMessage();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            responseMsg = convertExceptionToAxisFault(e, responseMsg);
        }
    } catch (AxisFault fault) {
        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        responseMsg = msgContext.getResponseMessage();
        if (responseMsg == null) {
            responseMsg = new Message(fault);
        }
    }
    //determine content type from message response
    contentType = responseMsg.getContentType(msgContext.getSOAPConstants());
    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    /* Send response back along the wire...  */
    /***********************************/
    if (responseMsg != null) {
        sendResponse(getProtocolVersion(req), contentType, res, responseMsg);
    }

    if (isDebug) {
        servletLog.debug("Response sent.");
        servletLog.debug("Exit: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post="
                + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "."
                + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }

}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information.//w  w  w .  j a v  a  2  s . com
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Set all the values from a request on this request object and set this request
 * as the one which the values were copied from
 * @param req any request//from  w w  w .  jav  a  2 s .com
 */
public void setRequestValues(HttpServletRequest req) {
    if (req == null) {
        throw new IllegalArgumentException("request cannot be null");
    }
    // get the collections of values out
    Enumeration<String> attribNames = req.getAttributeNames();
    while (attribNames.hasMoreElements()) {
        String name = (String) attribNames.nextElement();
        Object obj = req.getAttribute(name);
        if (obj != null) {
            attributes.put(name, obj);
        }
    }
    Cookie[] ck = req.getCookies();
    if (ck != null) {
        for (int i = 0; i < ck.length; i++) {
            cookies.add(ck[i]);
        }
    }
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> henum = req.getHeaders(name);
        Vector<String> v = new Vector<String>(1);
        while (henum.hasMoreElements()) {
            String h = henum.nextElement();
            v.add(h);
        }
    }
    for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    // get the basic values out
    this.locale = req.getLocale();
    this.method = req.getMethod();
    this.contentType = req.getContentType();
    this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding();
    this.contentLength = req.getContentLength();

    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.queryString = req.getQueryString();
    this.requestURI = req.getRequestURI();
    this.servletPath = req.getServletPath();

    this.scheme = req.getScheme();
    this.protocol = req.getProtocol();
    this.serverName = req.getServerName();
    this.serverPort = req.getServerPort();
    this.remoteAddr = req.getRemoteAddr();
    this.remoteHost = req.getRemoteHost();

    this.realDispatcher = true;
}