Search in sources :

Example 41 with HeaderElement

use of org.apache.http.HeaderElement in project robovm by robovm.

the class CookieSpecBase method parse.

protected List<Cookie> parse(final HeaderElement[] elems, final CookieOrigin origin) throws MalformedCookieException {
    List<Cookie> cookies = new ArrayList<Cookie>(elems.length);
    for (HeaderElement headerelement : elems) {
        String name = headerelement.getName();
        String value = headerelement.getValue();
        if (name == null || name.length() == 0) {
            throw new MalformedCookieException("Cookie name may not be empty");
        }
        BasicClientCookie cookie = new BasicClientCookie(name, value);
        cookie.setPath(getDefaultPath(origin));
        cookie.setDomain(getDefaultDomain(origin));
        // cycle through the parameters
        NameValuePair[] attribs = headerelement.getParameters();
        for (int j = attribs.length - 1; j >= 0; j--) {
            NameValuePair attrib = attribs[j];
            String s = attrib.getName().toLowerCase(Locale.ENGLISH);
            cookie.setAttribute(s, attrib.getValue());
            CookieAttributeHandler handler = findAttribHandler(s);
            if (handler != null) {
                handler.parse(cookie, attrib.getValue());
            }
        }
        cookies.add(cookie);
    }
    return cookies;
}
Also used : Cookie(org.apache.http.cookie.Cookie) NameValuePair(org.apache.http.NameValuePair) HeaderElement(org.apache.http.HeaderElement) CookieAttributeHandler(org.apache.http.cookie.CookieAttributeHandler) MalformedCookieException(org.apache.http.cookie.MalformedCookieException) ArrayList(java.util.ArrayList)

Example 42 with HeaderElement

use of org.apache.http.HeaderElement in project robovm by robovm.

the class DefaultConnectionKeepAliveStrategy method getKeepAliveDuration.

public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
            }
        }
    }
    return -1;
}
Also used : BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) HeaderElementIterator(org.apache.http.HeaderElementIterator) HeaderElement(org.apache.http.HeaderElement) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator)

Example 43 with HeaderElement

use of org.apache.http.HeaderElement in project robovm by robovm.

the class LaxContentLengthStrategy method determineLength.

public long determineLength(final HttpMessage message) throws HttpException {
    if (message == null) {
        throw new IllegalArgumentException("HTTP message may not be null");
    }
    HttpParams params = message.getParams();
    boolean strict = params.isParameterTrue(CoreProtocolPNames.STRICT_TRANSFER_ENCODING);
    Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
    Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
    // RFC2616, 4.4 item number 3
    if (transferEncodingHeader != null) {
        HeaderElement[] encodings = null;
        try {
            encodings = transferEncodingHeader.getElements();
        } catch (ParseException px) {
            throw new ProtocolException("Invalid Transfer-Encoding header value: " + transferEncodingHeader, px);
        }
        if (strict) {
            // Currently only chunk and identity are supported
            for (int i = 0; i < encodings.length; i++) {
                String encoding = encodings[i].getName();
                if (encoding != null && encoding.length() > 0 && !encoding.equalsIgnoreCase(HTTP.CHUNK_CODING) && !encoding.equalsIgnoreCase(HTTP.IDENTITY_CODING)) {
                    throw new ProtocolException("Unsupported transfer encoding: " + encoding);
                }
            }
        }
        // The chunked encoding must be the last one applied RFC2616, 14.41
        int len = encodings.length;
        if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) {
            return IDENTITY;
        } else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase(encodings[len - 1].getName()))) {
            return CHUNKED;
        } else {
            if (strict) {
                throw new ProtocolException("Chunk-encoding must be the last one applied");
            }
            return IDENTITY;
        }
    } else if (contentLengthHeader != null) {
        long contentlen = -1;
        Header[] headers = message.getHeaders(HTTP.CONTENT_LEN);
        if (strict && headers.length > 1) {
            throw new ProtocolException("Multiple content length headers");
        }
        for (int i = headers.length - 1; i >= 0; i--) {
            Header header = headers[i];
            try {
                contentlen = Long.parseLong(header.getValue());
                break;
            } catch (NumberFormatException e) {
                if (strict) {
                    throw new ProtocolException("Invalid content length: " + header.getValue());
                }
            }
        // See if we can have better luck with another header, if present
        }
        if (contentlen >= 0) {
            return contentlen;
        } else {
            return IDENTITY;
        }
    } else {
        return IDENTITY;
    }
}
Also used : ProtocolException(org.apache.http.ProtocolException) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HeaderElement(org.apache.http.HeaderElement) ParseException(org.apache.http.ParseException)

Example 44 with HeaderElement

use of org.apache.http.HeaderElement in project robovm by robovm.

the class BasicHeaderElementIterator method parseNextElement.

private void parseNextElement() {
    // loop while there are headers left to parse
    while (this.headerIt.hasNext() || this.cursor != null) {
        if (this.cursor == null || this.cursor.atEnd()) {
            // get next header value
            bufferHeaderValue();
        }
        // Anything buffered?
        if (this.cursor != null) {
            // loop while there is data in the buffer 
            while (!this.cursor.atEnd()) {
                HeaderElement e = this.parser.parseHeaderElement(this.buffer, this.cursor);
                if (!(e.getName().length() == 0 && e.getValue() == null)) {
                    // Found something
                    this.currentElement = e;
                    return;
                }
            }
            // if at the end of the buffer
            if (this.cursor.atEnd()) {
                // discard it
                this.cursor = null;
                this.buffer = null;
            }
        }
    }
}
Also used : HeaderElement(org.apache.http.HeaderElement)

Example 45 with HeaderElement

use of org.apache.http.HeaderElement in project dubbo by alibaba.

the class RestProtocol method doRefer.

protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
    }
    // TODO more configs to add
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager
    connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionMonitor.addConnectionManager(connectionManager);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)).setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)).build();
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            // TODO constant
            return 30 * 1000;
        }
    }).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig).build();
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    clients.add(client);
    client.register(RpcContextFilter.class);
    for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
        if (!StringUtils.isEmpty(clazz)) {
            try {
                client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
            } catch (ClassNotFoundException e) {
                throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
            }
        }
    }
    // TODO protocol
    ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
    return target.proxy(serviceType);
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) SocketConfig(org.apache.http.config.SocketConfig) ConnectionKeepAliveStrategy(org.apache.http.conn.ConnectionKeepAliveStrategy) HeaderElement(org.apache.http.HeaderElement) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) HeaderElementIterator(org.apache.http.HeaderElementIterator) RpcException(com.alibaba.dubbo.rpc.RpcException) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Aggregations

HeaderElement (org.apache.http.HeaderElement)58 Header (org.apache.http.Header)17 NameValuePair (org.apache.http.NameValuePair)14 HeaderElementIterator (org.apache.http.HeaderElementIterator)10 BasicHeaderElementIterator (org.apache.http.message.BasicHeaderElementIterator)10 HttpResponse (org.apache.http.HttpResponse)9 MalformedCookieException (org.apache.http.cookie.MalformedCookieException)9 ParserCursor (org.apache.http.message.ParserCursor)9 ArrayList (java.util.ArrayList)6 IOException (java.io.IOException)5 Cookie (org.apache.http.cookie.Cookie)5 CookieAttributeHandler (org.apache.http.cookie.CookieAttributeHandler)5 HttpContext (org.apache.http.protocol.HttpContext)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 ConnectionKeepAliveStrategy (org.apache.http.conn.ConnectionKeepAliveStrategy)4 HashSet (java.util.HashSet)3 NoSuchElementException (java.util.NoSuchElementException)3 ParseException (org.apache.http.ParseException)3 ProtocolException (org.apache.http.ProtocolException)3