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:PrintCGI.java

/**
     * Prints CGI Environment Variables in a table
     * //from   w  w w . ja va  2s.  com
     * @param request
     * @param response
     * @throws IOException
     */

    public void printCGIValues(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String headers = null;
        String htmlHeader = "<HTML><HEAD><TITLE> CGI Environment Variables </TITLE></HEAD><BODY>";
        String htmlFooter = "</BODY></HTML>";

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println(htmlHeader);
        out.println("<TABLE ALIGN=CENTER BORDER=1>");
        out.println("<tr><th> CGI Variable </th><th> Value </th>");

        out.println("<tr><td align=center>Authentication Type</td>");
        out.println("<td align=center>" + request.getAuthType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type</td>");
        out.println("<td align=center>" + request.getContentType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type Length</td>");
        out.println("<td align=center>" + request.getContentLength() + "</td></tr>");

        out.println("<tr><td align=center>Query String</td>");
        out.println("<td align=center>" + request.getMethod() + "</td></tr>");

        out.println("<tr><td align=center>IP Address</td>");
        out.println("<td align=center>" + request.getRemoteAddr() + "</td></tr>");

        out.println("<tr><td align=center>Host Name</td>");
        out.println("<td align=center>" + request.getRemoteHost() + "</td></tr>");

        out.println("<tr><td align=center>Request URL</td>");
        out.println("<td align=center>" + request.getRequestURI() + "</td></tr>");

        out.println("<tr><td align=center>Servlet Path</td>");
        out.println("<td align=center>" + request.getServletPath() + "</td></tr>");

        out.println("<tr><td align=center>Server's Name</td>");
        out.println("<td align=center>" + request.getServerName() + "</td></tr>");

        out.println("<tr><td align=center>Server's Port</td>");
        out.println("<td align=center>" + request.getServerPort() + "</td></tr>");

        out.println("</TABLE><BR>");
        out.println(htmlFooter);

    }

From source file:org.ow2.petals.binding.restproxy.in.AbstractRESTService.java

/**
 * @param path/*from   ww w.j  a v  a2  s . c o  m*/
 * @param request
 * @return
 */
private Map<String, Object> createProperties(final String path, final HttpServletRequest request) {
    Map<String, Object> result = new HashMap<String, Object>();

    result.put(org.ow2.petals.messaging.framework.message.Constants.HTTP_URL, path);

    Enumeration<?> headers = request.getHeaderNames();
    if (headers != null) {
        while (headers.hasMoreElements()) {
            Object object = headers.nextElement();
            String key = object.toString();
            result.put(org.ow2.petals.messaging.framework.message.Constants.HEADER + "." + key,
                    request.getHeader(key));
        }
    }

    result.put(org.ow2.petals.messaging.framework.message.Constants.CONTENT_LENGTH, request.getContentLength());
    String contentType = HTTPUtils.getContentType(request.getContentType());
    result.put(org.ow2.petals.messaging.framework.message.Constants.CONTENT_TYPE, contentType);
    final String charsetEncoding = request.getCharacterEncoding();
    result.put(org.ow2.petals.messaging.framework.message.Constants.CHARSET_ENCODING, charsetEncoding);
    result.put(org.ow2.petals.messaging.framework.message.Constants.HTTP_METHOD, request.getMethod());

    // get form data which is not XML!
    Enumeration<?> e = request.getParameterNames();
    while (e.hasMoreElements()) {
        String paramName = (String) e.nextElement();
        String[] values = request.getParameterValues(paramName.toString());
        int i = 0;
        for (String string : values) {
            result.put(org.ow2.petals.messaging.framework.message.Constants.PARAMETERS + "." + (i++) + "."
                    + paramName, string);
        }
    }

    for (String key : result.keySet()) {
        this.logger.debug("From HTTPRequest : Property '" + key + "' = '" + result.get(key) + "'");
    }
    return result;
}

From source file:org.fcrepo.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request/*from   ww  w .  j  a va  2s .co m*/
 */
public static RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers)
        throws Exception {
    RequestContent rContent = null;

    // See if the request is a multi-part file upload request
    if (ServletFileUpload.isMultipartContent(request)) {

        logger.debug("processing multipart content...");
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, use the first available File item
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                rContent = new RequestContent();
                rContent.contentStream = item.openStream();
                rContent.mimeType = item.getContentType();

                FileItemHeaders itemHeaders = item.getHeaders();
                if (itemHeaders != null) {
                    String contentLength = itemHeaders.getHeader("Content-Length");
                    if (contentLength != null) {
                        rContent.size = Long.parseLong(contentLength);
                    }
                }

                break;
            } else {
                logger.trace("ignoring form field \"{}\" \"{}\"", item.getFieldName(), item.getName());
            }
        }
    } else {
        // If the content stream was not been found as a multipart,
        // try to use the stream from the request directly
        if (rContent == null) {
            String contentLength = request.getHeader("Content-Length");
            long size = 0;
            if (contentLength != null) {
                size = Long.parseLong(contentLength);
            } else
                size = request.getContentLength();
            if (size > 0) {
                rContent = new RequestContent();
                rContent.contentStream = request.getInputStream();
                rContent.size = size;
            } else {
                String transferEncoding = request.getHeader("Transfer-Encoding");
                if (transferEncoding != null && transferEncoding.contains("chunked")) {
                    BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
                    bis.mark(2);
                    if (bis.read() > 0) {
                        bis.reset();
                        rContent = new RequestContent();
                        rContent.contentStream = bis;
                    }
                } else {
                    logger.warn(
                            "Expected chunked data not found- " + "Transfer-Encoding : {}, Content-Length: {}",
                            transferEncoding, size);
                }
            }
        }
    }

    // Attempt to set the mime type and size if not already set
    if (rContent != null) {
        if (rContent.mimeType == null) {
            MediaType mediaType = headers.getMediaType();
            if (mediaType != null) {
                rContent.mimeType = mediaType.toString();
            }
        }

        if (rContent.size == 0) {
            List<String> lengthHeaders = headers.getRequestHeader("Content-Length");
            if (lengthHeaders != null && lengthHeaders.size() > 0) {
                rContent.size = Long.parseLong(lengthHeaders.get(0));
            }
        }
    }

    return rContent;
}

From source file:org.polymap.rap.updownload.upload.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from w  w  w  . j  av  a2  s .co  m*/
        FileItemIterator it = fileUpload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            String name = item.getFieldName();
            InputStream in = item.openStream();
            try {
                if (item.isFormField()) {
                    log.info("Form field " + name + " with value " + Streams.asString(in) + " detected.");
                } else {
                    log.info("File field " + name + " with file name " + item.getName() + " detected.");

                    String key = req.getParameter("handler");
                    assert key != null;
                    IUploadHandler handler = handlers.get(key);
                    // for the upload field we always get just one item (which has the length of the request!?)
                    int length = req.getContentLength();
                    handler.uploadStarted(item.getName(), item.getContentType(), length, in);
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (Exception e) {
        log.warn("", e);
        throw new RuntimeException(e);
    }
}

From source file:net.naijatek.myalumni.util.fileupload.FileUpload.java

/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
 * compliant <code>multipart/form-data</code> stream. If files are stored
 * on disk, the path is given by <code>getRepositoryPath()</code>.
 * //from   w w w .j  a  v  a  2  s .  c o m
 * @param req The servlet request to_email be parsed.
 * @param sizeThreshold The max size in bytes to_email be stored in memory.
 * @param sizeMax The maximum allowed upload size, in bytes.
 * @param path The location where the files should be stored.
 * 
 * @return A list of <code>FileItem</code> instances parsed from_email the
 * request, in the order that they were transmitted.
 * 
 * @exception FileUploadException if there are problems reading/parsing
 * the request or storing files.
 */
public List /* FileItem */ parseRequest(final HttpServletRequest req, final int sizeThreshold,
        final int sizeMax, final String path) throws FileUploadException {
    ArrayList items = new ArrayList();
    String contentType = req.getHeader(CONTENT_TYPE);

    if (!contentType.startsWith(MULTIPART)) {
        throw new FileUploadException(
                "the request doesn't contain a " + MULTIPART_FORM_DATA + " or " + MULTIPART_MIXED + " stream");
    }
    int requestSize = req.getContentLength();

    if (requestSize == -1) {
        throw new FileUploadException("the request was rejected because " + "it's size is unknown");
    }

    if (sizeMax >= 0 && requestSize > sizeMax) {
        throw new FileUploadException("the request was rejected because " + "it's size exceeds allowed range");
    }

    try {
        byte[] boundary = contentType.substring(contentType.indexOf("boundary=") + 9).getBytes();

        InputStream input = req.getInputStream();

        MultipartStream multi = new MultipartStream(input, boundary);
        boolean nextPart = multi.skipPreamble();
        while (nextPart) {
            Map headers = parseHeaders(multi.readHeaders());
            String fieldName = getFieldName(headers);
            if (fieldName != null) {
                String subContentType = getHeader(headers, CONTENT_TYPE);
                if (subContentType != null && subContentType.startsWith(MULTIPART_MIXED)) {
                    // Multiple files.
                    byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9)
                            .getBytes();
                    multi.setBoundary(subBoundary);
                    boolean nextSubPart = multi.skipPreamble();
                    while (nextSubPart) {
                        headers = parseHeaders(multi.readHeaders());
                        if (getFileName(headers) != null) {
                            FileItem item = createItem(sizeThreshold, path, headers, requestSize);
                            OutputStream os = ((DefaultFileItem) item).getOutputStream();
                            try {
                                multi.readBodyData(os);
                            } finally {
                                os.close();
                            }
                            item.setFieldName(getFieldName(headers));
                            items.add(item);
                        } else {
                            // Ignore anything but files inside
                            // multipart/mixed.
                            multi.discardBodyData();
                        }
                        nextSubPart = multi.readBoundary();
                    }
                    multi.setBoundary(boundary);
                } else {
                    if (getFileName(headers) != null) {
                        // A single file.
                        FileItem item = createItem(sizeThreshold, path, headers, requestSize);
                        OutputStream os = ((DefaultFileItem) item).getOutputStream();
                        try {
                            multi.readBodyData(os);
                        } finally {
                            os.close();
                        }
                        item.setFieldName(getFieldName(headers));
                        items.add(item);
                    } else {
                        // A form field.
                        FileItem item = createItem(sizeThreshold, path, headers, requestSize);
                        OutputStream os = ((DefaultFileItem) item).getOutputStream();
                        try {
                            multi.readBodyData(os);
                        } finally {
                            os.close();
                        }
                        item.setFieldName(getFieldName(headers));
                        item.setIsFormField(true);
                        items.add(item);
                    }
                }
            } else {
                // Skip this part.
                multi.discardBodyData();
            }
            nextPart = multi.readBoundary();
        }
    } catch (IOException e) {
        throw new FileUploadException(
                "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage());
    }

    return items;
}

From source file:com.legstar.c2ws.servlet.C2wsProxy.java

/** {@inheritDoc} */
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    long startTime = System.currentTimeMillis();

    /* Use correlation id received in http header. This allows logs on
     * this side to be easily correlated with the mainframe logs. */
    String requestID = request.getHeader(CORRELATION_ID_HDR);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Start proxy request " + requestID + " from client " + request.getRemoteHost());
    }//from   ww  w . ja v  a  2 s .  c  om

    /* Make sure this is a Mainframe LegStar request. */
    if (!isSupportedContentType(request)) {
        throw new ServletException("Content type " + request.getContentType() + " is not supported");
    }

    try {
        /* Get all the bytes from the request in a byte array */
        int requestBytesLen = request.getContentLength();
        byte[] requestBytes = new byte[requestBytesLen];
        InputStream in = request.getInputStream();
        int offset = 0;
        int n;
        do {
            n = in.read(requestBytes, offset, requestBytesLen - offset);
        } while (n != -1);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Request data from host:");
            traceData(requestID, requestBytes, LOG);
        }

        /* Call the proxy getting a byte array back */
        byte[] replyBytes = getServiceProxy().invoke(requestID, requestBytes);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Reply data to host:");
            traceData(requestID, replyBytes, LOG);
        }

        /* Push the reply byte array into the http response */
        response.setContentType(request.getContentType());
        response.getOutputStream().write(replyBytes);

    } catch (IOException e) {
        throw (new ServletException(e));
    } catch (ProxyInvokerException e) {
        throw (new ServletException(e));
    }

    long endTime = System.currentTimeMillis();
    if (LOG.isDebugEnabled()) {
        LOG.debug("End proxy request " + requestID + " from client " + request.getRemoteHost() + " serviced in "
                + (endTime - startTime) + " msecs");
    }
}

From source file:com.concursive.connect.web.modules.documents.utils.HttpMultiPartParser.java

/**
 * Description of the Method//from  w w  w .j  a v  a 2  s  .  c  o  m
 *
 * @param saveInDir Description of Parameter
 * @param request   Description of the Parameter
 * @return Description of the Returned Value
 * @throws IllegalArgumentException Description of Exception
 * @throws IOException              Description of Exception
 */
private HashMap processData(HttpServletRequest request, String saveInDir)
        throws IllegalArgumentException, IOException {
    String contentType = request.getHeader("Content-type");
    //TODO: use the contentLength for a progress bar
    int contentLength = request.getContentLength();
    LOG.debug("HttpMultiPartParser Length: " + contentLength);
    if ((contentType == null) || (!contentType.startsWith("multipart/"))) {
        throw new IllegalArgumentException("Not a multipart message");
    }
    int boundaryIndex = contentType.indexOf("boundary=");
    String boundary = contentType.substring(boundaryIndex + 9);
    LOG.debug("Request boundary: " + boundary);
    ServletInputStream is = request.getInputStream();
    if (is == null) {
        throw new IllegalArgumentException("InputStream");
    }
    if (boundary == null || boundary.trim().length() < 1) {
        throw new IllegalArgumentException("boundary");
    }
    //Each content will begin with two dashes "--" plus the actual boundary string
    boundary = "--" + boundary;
    //Prepare to read in from request
    StringTokenizer stLine = null;
    StringTokenizer stFields = null;
    FileInfo fileInfo = null;
    HashMap dataTable = new HashMap(5);
    String line = null;
    String field = null;
    String paramName = null;
    boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
    boolean isFile = false;
    boolean validFile = false;
    int fileCount = 0;
    //First line should be the boundary
    line = getLine(is);
    if (line == null || !line.startsWith(boundary)) {
        throw new IOException("Boundary not found;" + " boundary = " + boundary + ", line = " + line);
    }
    //Continue with the rest of the lines
    while (line != null) {
        LOG.trace(line);
        // Process boundary line  ----------------------------------------
        if (line == null || !line.startsWith(boundary)) {
            return dataTable;
        }
        // Process "Content-Disposition: " line --------------------------
        line = getLine(is);
        if (line == null) {
            return dataTable;
        }
        // Split line into the following 3 tokens (or 2 if not a file):
        // 1. Content-Disposition: form-data
        // 2. name="LocalFile1"
        // 3. filename="C:\autoexec.bat"  (only present if this is part of a HTML file INPUT tag) */
        stLine = new StringTokenizer(line, ";\r\n");
        if (stLine.countTokens() < 2) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Confirm that this is "form-data"
        line = stLine.nextToken().toLowerCase();
        if (line.indexOf("form-data") < 0) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Now split token 2 from above into field "name" and it's "value"
        // e.g. name="LocalFile1"
        stFields = new StringTokenizer(stLine.nextToken(), "=\"");
        if (stFields.countTokens() < 2) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Get field name
        fileInfo = new FileInfo();
        fileInfo.setVersion(version);
        fileInfo.setExtensionId(extensionId);
        stFields.nextToken();
        paramName = stFields.nextToken();
        // Now split token 3 from above into file "name" and it's "value"
        // e.g. filename="C:\autoexec.bat"
        isFile = false;
        if (stLine.hasMoreTokens()) {
            field = stLine.nextToken();
            stFields = new StringTokenizer(field, "=\"");
            if (stFields.countTokens() > 1) {
                if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
                    fileInfo.setName(paramName);
                    String value = stFields.nextToken();
                    if (value != null && value.trim().length() > 0) {
                        fileInfo.setClientFileName(value);
                        isFile = true;
                        ++fileCount;
                    } else {
                        // An error condition occurred, skip to next boundary
                        line = getLine(is);
                        // Skip "Content-Type:" line
                        line = getLine(is);
                        // Skip blank line
                        line = getLine(is);
                        // Skip blank line
                        line = getLine(is);
                        // Position to boundary line
                        continue;
                    }
                }
            } else if (field.toLowerCase().indexOf("filename") >= 0) {
                // An error condition occurred, skip to next boundary
                line = getLine(is);
                // Skip "Content-Type:" line
                line = getLine(is);
                // Skip blank line
                line = getLine(is);
                // Skip blank line
                line = getLine(is);
                // Position to boundary line
                continue;
            }
        }
        // Process "Content-Type: " line ----------------------------------
        // e.g. Content-Type: text/plain
        boolean skipBlankLine = true;
        if (isFile) {
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
            // "Content-type" line not guaranteed to be sent by the browser
            if (line.trim().length() < 1) {
                skipBlankLine = false;
            } else {
                // Prevent re-skipping below
                stLine = new StringTokenizer(line, ": ");
                if (stLine.countTokens() < 2) {
                    throw new IllegalArgumentException("Bad data in third line");
                }
                stLine.nextToken();
                // Content-Type
                fileInfo.setFileContentType(stLine.nextToken());
            }
        }
        // Skip blank line  -----------------------------------------------
        if (skipBlankLine) {
            // Blank line already skipped above?
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
        }
        // Process data: If not a file, add to hashmap and continue
        if (!isFile) {
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
            StringBuffer sb = new StringBuffer();
            sb.append(line);
            while (line != null && !line.startsWith(boundary)) {
                line = getLine(is);
                if (line != null && !line.startsWith(boundary)) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(line);
                }
            }
            LOG.debug(" HttpMultiPartParser ->Adding param: " + paramName);
            dataTable.put(paramName, sb.toString());
            continue;
        }
        // Either save contents in memory or to a local file
        OutputStream os = null;
        String path = null;
        try {
            String tmpPath = null;
            String filenameToUse = null;
            if (saveFiles) {
                if (usePathParam) {
                    tmpPath = saveInDir + fileInfo.getName() + fs;
                } else {
                    tmpPath = saveInDir;
                }
                if (useDateForFolder) {
                    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy");
                    String datePathToUse1 = formatter1.format(new java.util.Date());
                    SimpleDateFormat formatter2 = new SimpleDateFormat("MMdd");
                    String datePathToUse2 = formatter2.format(new java.util.Date());
                    tmpPath += datePathToUse1 + fs + datePathToUse2 + fs;
                }
                // Create output directory in case it doesn't exist
                File f = new File(tmpPath);
                f.mkdirs();
                //If specified, store files using a unique name, based on date
                if (useUniqueName) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                    filenameToUse = formatter.format(new java.util.Date());
                    if (fileCount > 1) {
                        filenameToUse += String.valueOf(fileCount);
                    }
                } else {
                    filenameToUse = fileInfo.getClientFileName();
                }
                fileInfo.setClientFileName(getFileName(fileInfo.getClientFileName()));
                //Append a version id for record keeping and uniqueness, prevents
                //multiple uploads from overwriting each other
                filenameToUse += (version == -1 ? "" : "^" + version)
                        + (extensionId == -1 ? "" : "-" + extensionId);
                //Create the file to a file
                os = new FileOutputStream(path = getFileName(tmpPath, filenameToUse));
            } else {
                //Store the file in memory
                os = new ByteArrayOutputStream(ONE_MB);
            }
            //Begin reading in the request
            boolean readingContent = true;
            byte previousLine[] = new byte[2 * ONE_MB];
            byte temp[] = null;
            byte currentLine[] = new byte[2 * ONE_MB];
            int read;
            int read3;
            //read in the first line, break out if eof
            if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
                line = null;
                break;
            }
            //read until next boundary and write the contents to OutputStream
            while (readingContent) {
                if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
                    line = null;
                    break;
                }
                //check if current line is a boundary
                if (compareBoundary(boundary, currentLine)) {
                    if (read - 2 > 0) {
                        validFile = true;
                    }
                    os.write(previousLine, 0, read - 2);
                    os.flush();
                    line = new String(currentLine, 0, read3);
                    break;
                } else {
                    //current line is not a boundary, write previous line
                    os.write(previousLine, 0, read);
                    validFile = true;
                    os.flush();
                    //reposition previousLine to be currentLine
                    temp = currentLine;
                    currentLine = previousLine;
                    previousLine = temp;
                    read = read3;
                }
            }
            os.close();
            temp = null;
            previousLine = null;
            currentLine = null;
            //Store the completed file somewhere
            if (!saveFiles) {
                ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
                fileInfo.setFileContents(baos.toByteArray());
            } else {
                File thisFile = new File(path);
                if (validFile) {
                    fileInfo.setLocalFile(thisFile);
                    fileInfo.setSize((int) thisFile.length());
                    os = null;
                } else {
                    thisFile.delete();
                }
            }
            if (validFile) {
                LOG.debug("Adding file param: " + fileInfo.getName());
                dataTable.put(paramName, fileInfo);
            }
        } catch (Exception e) {
            LOG.error("HttpMultiPartParser-> error: " + e.getMessage(), e);
            if (os != null) {
                os.close();
            }
            if (saveFiles && path != null) {
                File thisFile = new File(path);
                if (thisFile.exists()) {
                    thisFile.delete();
                    LOG.warn("HttpMultiPartParser-> Temporary file deleted");
                }
            }
        }
    }
    return dataTable;
}

From source file:org.gnode.wda.server.ProxyServlet.java

License:asdf

@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  ww w  . ja va  2 s  . com
    // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method.
    // Turns "/proxy/asdf" into "/asdf"
    uri.append(req.getRequestURI().substring(6));

    //    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();

    if (entity == null)
        return;

    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.osaf.cosmo.log.HttpLoggingFilter.java

private String formatRequest(HttpServletRequest request, String format) {

    StringBuffer sb = new StringBuffer();
    char[] formatArray = format.toCharArray();
    for (int i = 0; i < formatArray.length; i++) {
        if (formatArray[i] != '%') {
            sb.append(formatArray[i]);/*w  ww .  ja v  a  2 s . c  o  m*/

        } else {
            i++;

            switch (formatArray[i]) {

            case 'M':
                sb.append(request.getMethod());
                break;
            case 'C':
                sb.append(request.getScheme());
                break;
            case 'S':
                sb.append(request.getServerName());
                break;
            case 'P':
                sb.append(request.getServerPort());
                break;
            case 'U':
                sb.append(request.getRequestURI());
                break;
            case 'L':
                sb.append(request.getContentLength());
                break;
            case 'Q':
                sb.append(request.getQueryString());
                break;
            case 'I':
                HttpSession s = request.getSession(false);
                sb.append(s == null ? "No session" : s.getId());
                break;
            case 'A':
                if (securityManager == null) {
                    sb.append("\"No security manager\"");
                    break;
                }
                try {
                    CosmoSecurityContext securityContext = securityManager.getSecurityContext();
                    Ticket ticket = securityContext.getTicket();

                    User user = securityContext.getUser();
                    if (ticket != null) {
                        sb.append(ticket);
                    } else if (user != null) {
                        sb.append(user.getUsername());
                    } else {
                        sb.append("\"No auth token\"");
                    }

                } catch (CosmoSecurityException e) {
                    sb.append("\"No security context\"");
                }

                break;
            case '%':
                sb.append('%');
                break;
            default:
                sb.append('%' + formatArray[i]);
                break;
            }
        }
    }
    return new String(sb);

}

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

/**
 * Handle special operations at the root level /_...
 * @param req//w  w  w  . j a v  a 2  s  . c om
 * @param resp
 * @param special
 * @throws ServletException
 * @throws IOException
 */
protected void handleRootSpecial(HttpServletRequest req, HttpServletResponse resp, String special)
        throws ServletException, IOException {

    if (special.equals("_pre_replicate")) {
        logger.debug("got _pre_replicate: {}", req.getRequestURI());
        handlePreReplicate(req, resp);
        return;
    } else if (special.equals("_commit_for_checkpoint")) {
        logger.debug("got _commit_for_checkpoint: {}", req.getRequestURI());
        handleCommitForCheckpoint(req, resp);
        return;
    } else {
        logger.debug("got unknown special: {}", req.getRequestURI());
    }

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

    logger.trace("root special request body was: '{}'", new String(buffer));

    sendNotFoundResponse(resp, "missing");
}