Example usage for org.apache.commons.httpclient HttpParser parseHeaders

List of usage examples for org.apache.commons.httpclient HttpParser parseHeaders

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpParser parseHeaders.

Prototype

public static Header[] parseHeaders(InputStream paramInputStream) throws IOException, HttpException 

Source Link

Usage

From source file:de.kapsi.net.daap.bio.DaapConnectionBIO.java

private DaapRequest readRequest() throws IOException {

    String line = null;/*from  w w w .  j a  v a2  s . c  o  m*/

    do {
        line = HttpParser.readLine(in);
    } while (line != null && line.length() == 0);

    if (line == null) {
        throw new IOException("Request is null: " + this);
    }

    DaapRequest request = new DaapRequest(this, line);
    Header[] headers = HttpParser.parseHeaders(in);
    request.addHeaders(headers);

    return request;
}

From source file:org.jboss.remoting.transport.http.HTTPServerInvoker.java

private boolean processRequest(FilterInputStream dataInput, FilterOutputStream dataOutput) {
    boolean keepAlive = true;
    try {//  w w  w.  j  ava 2s .  c  o  m
        Object response = null;
        boolean isError = false;
        String requestContentType = null;
        String methodType = null;
        String path = null;
        String httpVersion = null;

        InvocationRequest request = null;

        try {

            // Need to parse the header to find Content-Type

            /**
             * Read the first line, as this will be the POST or GET, path, and HTTP version.
             * Then next comes the headers.  (key value seperated by a ': '
             * Then followed by an empty \r\n, which will be followed by the payload
             */
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int ch;
            while ((ch = dataInput.read()) >= 0) {
                buffer.write(ch);
                if (ch == '\n') {
                    break;
                }
            }

            byte[] firstLineRaw = buffer.toByteArray();
            buffer.close();
            // now need to backup and make sure the character before the \n was a \r
            if (firstLineRaw[firstLineRaw.length - 2] == '\r') {
                //Got our first line, now to set the variables
                String firstLine = new String(firstLineRaw).trim();
                int startIndex = 0;
                int endIndex = firstLine.indexOf(' ');
                methodType = firstLine.substring(startIndex, endIndex);
                startIndex = endIndex + 1;
                endIndex = firstLine.indexOf(' ', startIndex);
                path = firstLine.substring(startIndex, endIndex);
                startIndex = endIndex + 1;
                httpVersion = firstLine.substring(startIndex);
            } else {
                log.error("Error processing first line.  Should have ended in \r\n, but did not");
                throw new RuntimeException(
                        "Error processing HTTP request type.  First line of request is invalid.");
            }

            Map metadata = new HashMap();
            Header[] headers = HttpParser.parseHeaders(dataInput);
            for (int x = 0; x < headers.length; x++) {
                String headerName = headers[x].getName();
                String headerValue = headers[x].getValue();
                metadata.put(headerName, headerValue);
                // doing this instead of getting from map since ignores case
                if ("Content-Type".equalsIgnoreCase(headerName)) {
                    requestContentType = headers[x].getValue();
                }
            }

            metadata.put(HTTPMetadataConstants.METHODTYPE, methodType);
            metadata.put(HTTPMetadataConstants.PATH, path);
            metadata.put(HTTPMetadataConstants.HTTPVERSION, httpVersion);

            // checks to see if is Connection: close, which will deactivate keep alive.
            keepAlive = checkForConnecctionClose(headers);

            if (methodType.equals("OPTIONS")) {
                request = createNewInvocationRequest(metadata, null);
                response = invoke(request);

                Map responseMap = request.getReturnPayload();

                dataOutput.write("HTTP/1.1 ".getBytes());
                String status = "200 OK";
                dataOutput.write(status.getBytes());
                String server = "\r\n" + "Server: JBoss Remoting HTTP Server/" + Version.VERSION;
                dataOutput.write(server.getBytes());
                String date = "\r\n" + "Date: " + new Date();
                dataOutput.write(date.getBytes());
                String contentLength = "\r\n" + "Content-Length: 0";
                dataOutput.write(contentLength.getBytes());

                if (responseMap != null) {
                    Set entries = responseMap.entrySet();
                    Iterator itr = entries.iterator();
                    while (itr.hasNext()) {
                        Map.Entry entry = (Map.Entry) itr.next();
                        String entryString = "\r\n" + entry.getKey() + ": " + entry.getValue();
                        dataOutput.write(entryString.getBytes());
                    }
                }

                String close = "\r\n" + "Connection: close";
                dataOutput.write(close.getBytes());

                // content seperator
                dataOutput.write(("\r\n" + "\r\n").getBytes());

                dataOutput.flush();

                //nothing more to do since do not need to call handler for this one
                return keepAlive;

            } else if (methodType.equals("GET") || methodType.equals("HEAD")) {
                request = createNewInvocationRequest(metadata, null);
            } else // must be POST or PUT
            {
                UnMarshaller unmarshaller = getUnMarshaller();
                Object obj = unmarshaller.read(dataInput, metadata);

                if (obj instanceof InvocationRequest) {
                    request = (InvocationRequest) obj;
                } else {
                    if (WebUtil.isBinary(requestContentType)) {
                        request = getInvocationRequest(metadata, obj);
                    } else {
                        request = createNewInvocationRequest(metadata, obj);
                    }
                }
            }

            try {
                // call transport on the subclass, get the result to handback
                response = invoke(request);
            } catch (Throwable ex) {
                log.debug("Error thrown calling invoke on server invoker.", ex);
                response = ex;
                isError = true;
            }
        } catch (Throwable thr) {
            log.debug("Error thrown processing request.  Probably error with processing headers.", thr);
            if (thr instanceof SocketException) {
                log.error("Error processing on socket.", thr);
                keepAlive = false;
                return keepAlive;
            } else if (thr instanceof Exception) {
                response = (Exception) thr;
            } else {
                response = new Exception(thr);
            }
            isError = true;
        }

        if (dataOutput != null) {

            Map responseMap = null;

            if (request != null) {
                responseMap = request.getReturnPayload();
            }

            if (response == null) {
                dataOutput.write("HTTP/1.1 ".getBytes());
                String status = "204 No Content";
                if (responseMap != null) {
                    String handlerStatus = (String) responseMap.get(HTTPMetadataConstants.RESPONSE_CODE);
                    if (handlerStatus != null) {
                        status = handlerStatus;
                    }
                }
                dataOutput.write(status.getBytes());
                String contentType = "\r\n" + "Content-Type" + ": " + "text/html";
                dataOutput.write(contentType.getBytes());
                String contentLength = "\r\n" + "Content-Length" + ": " + 0;
                dataOutput.write(contentLength.getBytes());
                if (responseMap != null) {
                    Set entries = responseMap.entrySet();
                    Iterator itr = entries.iterator();
                    while (itr.hasNext()) {
                        Map.Entry entry = (Map.Entry) itr.next();
                        String entryString = "\r\n" + entry.getKey() + ": " + entry.getValue();
                        dataOutput.write(entryString.getBytes());
                    }
                }

                dataOutput.write(("\r\n" + "\r\n").getBytes());
                //dataOutput.write("NULL return".getBytes());
                dataOutput.flush();
            } else {
                dataOutput.write("HTTP/1.1 ".getBytes());
                String status = null;
                if (isError) {
                    status = "500 JBoss Remoting: Error occurred within target application.";
                } else {
                    status = "200 OK";
                    if (responseMap != null) {
                        String handlerStatus = (String) responseMap.get(HTTPMetadataConstants.RESPONSE_CODE);
                        if (handlerStatus != null) {
                            status = handlerStatus;
                        }
                    }
                }

                dataOutput.write(status.getBytes());

                // write return headers
                String contentType = "\r\n" + "Content-Type" + ": " + requestContentType;
                dataOutput.write(contentType.getBytes());
                int iContentLength = getContentLength(response);
                String contentLength = "\r\n" + "Content-Length" + ": " + iContentLength;
                dataOutput.write(contentLength.getBytes());

                if (responseMap != null) {
                    Set entries = responseMap.entrySet();
                    Iterator itr = entries.iterator();
                    while (itr.hasNext()) {
                        Map.Entry entry = (Map.Entry) itr.next();
                        String entryString = "\r\n" + entry.getKey() + ": " + entry.getValue();
                        dataOutput.write(entryString.getBytes());
                    }
                }

                // content seperator
                dataOutput.write(("\r\n" + "\r\n").getBytes());

                if (methodType != null && !methodType.equals("HEAD")) {
                    // write response
                    Marshaller marshaller = getMarshaller();
                    marshaller.write(response, dataOutput);
                }
            }
        } else {
            if (isError) {
                log.warn(
                        "Can not send error response due to output stream being null (due to previous error).");
            } else {
                log.error(
                        "Can not send response due to output stream being null (even though there was not a previous error encountered).");
            }
        }
    } catch (Exception e) {
        log.error("Error processing client request.", e);
        keepAlive = false;
    }

    return keepAlive;
}