Example usage for org.apache.commons.httpclient HttpVersion parse

List of usage examples for org.apache.commons.httpclient HttpVersion parse

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpVersion parse.

Prototype

public static HttpVersion parse(String paramString) throws ProtocolException 

Source Link

Usage

From source file:net.sf.antcontrib.net.httpclient.ClientParams.java

public void setVersion(String version) {
    try {//from w ww. j  a  v  a 2s.c om
        setVersion(HttpVersion.parse(version));
    } catch (ProtocolException e) {
        throw new BuildException(e);
    }
}

From source file:com.zimbra.soap.SoapServlet.java

private void sendResponse(HttpServletRequest req, HttpServletResponse resp, Element envelope)
        throws IOException {
    SoapProtocol soapProto = SoapProtocol.determineProtocol(envelope);
    int statusCode = soapProto.hasFault(envelope) ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
            : HttpServletResponse.SC_OK;

    boolean chunkingEnabled = LC.soap_response_chunked_transfer_encoding_enabled.booleanValue();

    if (chunkingEnabled) {
        // disable chunking if proto < HTTP 1.1
        String proto = req.getProtocol();
        try {//  ww w .ja  v a 2  s .  c om
            HttpVersion httpVer = HttpVersion.parse(proto);
            chunkingEnabled = !httpVer.lessEquals(HttpVersion.HTTP_1_0);
        } catch (ProtocolException e) {
            ZimbraLog.soap.warn(
                    "cannot parse http version in request: %s, http chunked transfer encoding disabled", proto,
                    e);
            chunkingEnabled = false;
        }
    }

    // use jetty default if the LC key is not set
    int responseBufferSize = soapResponseBufferSize();
    if (responseBufferSize != -1)
        resp.setBufferSize(responseBufferSize);

    resp.setContentType(soapProto.getContentType());
    resp.setStatus(statusCode);
    resp.setHeader("Cache-Control", "no-store, no-cache");

    if (chunkingEnabled) {
        // Let jetty chunk the response if applicable.
        ZimbraServletOutputStream out = new ZimbraServletOutputStream(resp.getOutputStream());
        envelope.output(out);
        out.flush();
    } else {
        // serialize the envelope to a byte array and send the response with Content-Length header.
        byte[] soapBytes = envelope.toUTF8();
        resp.setContentLength(soapBytes.length);
        resp.getOutputStream().write(soapBytes);
        resp.getOutputStream().flush();
    }
    envelope.destroy();
}

From source file:com.zenkey.net.prowser.Tab.java

/**************************************************************************
 * Configures the HttpMethod object before use.
 * /*  w w  w . j av a  2 s  .c  om*/
 * @param httpMethod
 *        The HTTP method object.
 * @param request
 *        The request object.
 * @param ioTimeout
 *        The timeout value to use for I/O operations (like making
 *        connections and socket reads). This value should be 1 second
 *        longer than the actual timeout used for the request, in order to
 *        allow the request to timeout cleanly without having an I/O
 *        exception get in the way.
 * @param httpMethodRetryHandler
 *        The retry handler object.
 * @throws ProtocolException
 *         If the HTTP version in the request object is invalid.
 */
private static void prepareHttpMethod(HttpMethod httpMethod, Request request,
        HttpMethodRetryHandler httpMethodRetryHandler) throws ProtocolException {

    httpMethod.setFollowRedirects(false);

    httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpMethodRetryHandler);

    String httpVersion = null;
    if ((httpVersion = request.getHttpVersion()) != null)
        httpMethod.getParams().setVersion(HttpVersion.parse("HTTP/" + httpVersion));

    String userAgent = null;
    if ((userAgent = request.getUserAgent()) != null)
        httpMethod.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
}

From source file:com.zenkey.net.prowser.Tab.java

void setHttpClientHttpVersion(String httpVersion) {
    try {//from w ww  . jav  a 2  s  . c o  m
        httpClient.getParams().setVersion(HttpVersion.parse("HTTP/" + httpVersion));
    } catch (ProtocolException e) {
        throw new IllegalArgumentException("Invalid HTTP version argument");
    }
}

From source file:org.apache.camel.component.http.HttpProducer.java

public void process(Exchange exchange) throws Exception {
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;

    if (getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString);
        }//  ww  w  .  j  ava 2  s .  c  o  m
        // Need to remove the Host key as it should be not used 
        exchange.getIn().getHeaders().remove("host");
    }
    HttpMethod method = createMethod(exchange);
    Message in = exchange.getIn();
    String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
    if (httpProtocolVersion != null) {
        // set the HTTP protocol version
        HttpMethodParams params = method.getParams();
        params.setVersion(HttpVersion.parse(httpProtocolVersion));
    }

    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();

    // propagate headers as HTTP headers
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object headerValue = in.getHeader(key);

        if (headerValue != null) {
            // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
            final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);

            // the value to add as request header
            final List<String> values = new ArrayList<String>();

            // if its a multi value then check each value if we can add it and for multi values they
            // should be combined into a single value
            while (it.hasNext()) {
                String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());

                // we should not add headers for the parameters in the uri if we bridge the endpoint
                // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                    continue;
                }
                if (value != null && strategy != null
                        && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    values.add(value);
                }
            }

            // add the value(s) as a http request header
            if (values.size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = values.size() > 1 ? values.toString() : values.get(0);
                method.addRequestHeader(key, s);
            }
        }
    }

    // lets store the result in the output message.
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString());
        }
        int responseCode = executeMethod(method);
        LOG.debug("Http responseCode: {}", responseCode);

        if (!throwException) {
            // if we do not use failed exception then populate response for all response codes
            populateResponse(exchange, method, in, strategy, responseCode);
        } else {
            if (responseCode >= 100 && responseCode < 300) {
                // only populate response for OK response
                populateResponse(exchange, method, in, strategy, responseCode);
            } else {
                // operation failed so populate exception to throw
                throw populateHttpOperationFailedException(exchange, method, responseCode);
            }
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.mule.transport.as2.As2MuleMessageFactory.java

@Override
protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception {
    String method;/* w  w  w .ja v a 2  s  . c  o  m*/
    HttpVersion httpVersion;
    String uri;
    String statusCode = null;
    Map<String, Object> headers;
    Map<String, Object> httpHeaders = new HashMap<String, Object>();
    Map<String, Object> queryParameters = new HashMap<String, Object>();

    if (transportMessage instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) transportMessage;
        method = httpRequest.getRequestLine().getMethod();
        httpVersion = httpRequest.getRequestLine().getHttpVersion();
        uri = httpRequest.getRequestLine().getUri();
        headers = convertHeadersToMap(httpRequest.getHeaders(), uri);
        convertMultiPartHeaders(headers);
    } else if (transportMessage instanceof HttpMethod) {
        HttpMethod httpMethod = (HttpMethod) transportMessage;
        method = httpMethod.getName();
        httpVersion = HttpVersion.parse(httpMethod.getStatusLine().getHttpVersion());
        uri = httpMethod.getURI().toString();
        statusCode = String.valueOf(httpMethod.getStatusCode());
        headers = convertHeadersToMap(httpMethod.getResponseHeaders(), uri);
    } else {
        // This should never happen because of the supported type checking in our superclass
        throw new MessageTypeNotSupportedException(transportMessage, getClass());
    }

    rewriteConnectionAndKeepAliveHeaders(headers);

    headers = processIncomingHeaders(headers);

    httpHeaders.put(HttpConnector.HTTP_HEADERS, new HashMap<String, Object>(headers));

    String encoding = getEncoding(headers);

    queryParameters.put(HttpConnector.HTTP_QUERY_PARAMS, processQueryParams(uri, encoding));

    //Make any URI params available ans inbound message headers
    addUriParamsAsHeaders(headers, uri);

    headers.put(HttpConnector.HTTP_METHOD_PROPERTY, method);
    headers.put(HttpConnector.HTTP_REQUEST_PROPERTY, uri);
    headers.put(HttpConnector.HTTP_VERSION_PROPERTY, httpVersion.toString());
    if (enableCookies) {
        headers.put(HttpConnector.HTTP_COOKIE_SPEC_PROPERTY, cookieSpec);
    }

    if (statusCode != null) {
        headers.put(HttpConnector.HTTP_STATUS_PROPERTY, statusCode);
    }

    message.addInboundProperties(headers);
    message.addInboundProperties(httpHeaders);
    message.addInboundProperties(queryParameters);

    // The encoding is stored as message property. To avoid overriding it from the message
    // properties, it must be initialized last
    initEncoding(message, encoding);
}

From source file:org.mule.transport.http.components.HttpResponseBuilder.java

private void setStatus(HttpResponse response, MuleMessage message) throws MuleException {
    if (status != null) {
        try {//from w ww. j  av a2  s .c  om
            response.setStatusLine(HttpVersion.parse(version), Integer.valueOf(parse(status, message)));
        } catch (ProtocolException e) {
            throw new DefaultMuleException(e);
        }
    }
}

From source file:org.mule.transport.http.HttpResponse.java

public HttpResponse(final StatusLine statusline, final Header[] headers, final InputStream content)
        throws IOException {
    super();/*  w  ww .  ja  va2 s. co m*/
    if (statusline == null) {
        throw new IllegalArgumentException("Status line may not be null");
    }
    setStatusLine(HttpVersion.parse(statusline.getHttpVersion()), statusline.getStatusCode(),
            statusline.getReasonPhrase());
    setHeaders(headers);
    if (content != null) {
        InputStream in = content;
        Header contentLength = this.headers.getFirstHeader(HttpConstants.HEADER_CONTENT_LENGTH);
        Header transferEncoding = this.headers.getFirstHeader(HttpConstants.HEADER_TRANSFER_ENCODING);

        if (transferEncoding != null) {
            if (transferEncoding.getValue().indexOf(HttpConstants.TRANSFER_ENCODING_CHUNKED) != -1) {
                in = new ChunkedInputStream(in);
            }
        } else if (contentLength != null) {
            long len = getContentLength();
            if (len >= 0) {
                in = new ContentLengthInputStream(in, len);
            }
        }
    }
}

From source file:org.mule.transport.http.RequestLine.java

public RequestLine(final String method, final String uri, final String httpversion) throws ProtocolException {
    this(method, uri, HttpVersion.parse(httpversion));
}

From source file:org.mule.transport.http.transformers.MuleMessageToHttpResponse.java

protected HttpResponse createResponse(Object src, String encoding, MuleMessage msg)
        throws IOException, TransformerException {
    HttpResponse response = new HttpResponse();

    Object tmp = msg.getOutboundProperty(HttpConnector.HTTP_STATUS_PROPERTY);
    int status = HttpConstants.SC_OK;

    if (tmp != null) {
        status = Integer.valueOf(tmp.toString());
    } else if (msg.getExceptionPayload() != null) {
        status = HttpConstants.SC_INTERNAL_SERVER_ERROR;
    }/*from   www .j a v a  2s .  c  o m*/

    String version = msg.getInboundProperty(HttpConnector.HTTP_VERSION_PROPERTY);
    if (version == null) {
        version = HttpConstants.HTTP11;
    }

    String contentType = msg.getInboundProperty(HttpConstants.HEADER_CONTENT_TYPE);
    if (contentType == null) {
        contentType = msg.getInvocationProperty(HttpConstants.HEADER_CONTENT_TYPE);
    }

    // MULE-4047 Don't explicitly set the content-type to a default value here,
    // otherwise any settings on the servlet/transport will be happily ignored.
    //if (contentType == null)
    //{
    //    contentType = HttpConstants.DEFAULT_CONTENT_TYPE;
    //
    //    if (encoding != null)
    //    {
    //        contentType += "; charset=" + encoding;
    //    }
    //    logger.warn("Content-Type was not set, defaulting to: " + contentType);
    //}

    response.setStatusLine(HttpVersion.parse(version), status);
    if (contentType != null) {
        response.setHeader(new Header(HttpConstants.HEADER_CONTENT_TYPE, contentType));
    }
    String date = formatDate(System.currentTimeMillis());
    response.setHeader(new Header(HttpConstants.HEADER_DATE, date));
    response.setHeader(new Header(HttpConstants.HEADER_SERVER, server));

    String etag = msg.getOutboundProperty(HttpConstants.HEADER_ETAG);
    if (etag != null) {
        response.setHeader(new Header(HttpConstants.HEADER_ETAG, etag));
    }
    response.setFallbackCharset(encoding);

    Collection<String> headerNames = new LinkedList<String>();
    headerNames.addAll(HttpConstants.RESPONSE_HEADER_NAMES.values());
    headerNames.addAll(HttpConstants.GENERAL_AND_ENTITY_HEADER_NAMES.values());

    for (String headerName : headerNames) {
        if (HttpConstants.HEADER_COOKIE_SET.equals(headerName)) {
            // TODO This have to be improved. We shouldn't have to look in all
            // scopes
            Object cookiesObject = msg.getInvocationProperty(headerName);
            if (cookiesObject == null) {
                cookiesObject = msg.getOutboundProperty(headerName);
            }
            if (cookiesObject == null) {
                cookiesObject = msg.getInboundProperty(headerName);
            }
            if (cookiesObject == null) {
                continue;
            }

            if (!(cookiesObject instanceof Cookie[])) {
                response.addHeader(new Header(headerName, cookiesObject.toString()));
            } else {
                Cookie[] arrayOfCookies = CookieHelper.asArrayOfCookies(cookiesObject);
                for (Cookie cookie : arrayOfCookies) {
                    response.addHeader(
                            new Header(headerName, CookieHelper.formatCookieForASetCookieHeader(cookie)));
                }
            }
        } else {
            Object value = msg.getInvocationProperty(headerName);
            if (value == null) {
                value = msg.getOutboundProperty(headerName);
            }
            if (value != null) {
                response.setHeader(new Header(headerName, value.toString()));
            }
        }
    }

    Map customHeaders = msg.getOutboundProperty(HttpConnector.HTTP_CUSTOM_HEADERS_MAP_PROPERTY);
    if (customHeaders != null) {
        throw new TransformerException(HttpMessages.customHeaderMapDeprecated(), this);
    }

    //attach the outbound properties to the message
    for (String headerName : msg.getOutboundPropertyNames()) {
        if (response.getFirstHeader(headerName) != null) {
            //keep headers already set
            continue;
        }
        Object v = msg.getOutboundProperty(headerName);
        if (v != null) {
            if (headerName.startsWith(MuleProperties.PROPERTY_PREFIX)) {
                headerName = HttpConstants.CUSTOM_HEADER_PREFIX + headerName;
            }
            response.setHeader(new Header(headerName, v.toString()));
        }
    }

    if (msg.getCorrelationId() != null) {
        response.setHeader(
                new Header(HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_CORRELATION_ID_PROPERTY,
                        msg.getCorrelationId()));
        response.setHeader(new Header(
                HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_CORRELATION_GROUP_SIZE_PROPERTY,
                String.valueOf(msg.getCorrelationGroupSize())));
        response.setHeader(new Header(
                HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_CORRELATION_SEQUENCE_PROPERTY,
                String.valueOf(msg.getCorrelationSequence())));
    }
    if (msg.getReplyTo() != null) {
        response.setHeader(
                new Header(HttpConstants.CUSTOM_HEADER_PREFIX + MuleProperties.MULE_REPLY_TO_PROPERTY,
                        msg.getReplyTo().toString()));
    }

    try {
        response.setBody(msg);
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }

    return response;
}