code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.ssl; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * A trust strategy that accepts self-signed certificates as trusted. Verification of all other * certificates is done by the trust manager configured in the SSL context. * * @since 4.1 */ public class TrustSelfSignedStrategy implements TrustStrategy { public boolean isTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { return chain.length == 1; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.ssl; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSocket; import java.io.IOException; import java.security.cert.X509Certificate; /** * Interface for checking if a hostname matches the names stored inside the * server's X.509 certificate. This interface extends * {@link javax.net.ssl.HostnameVerifier}, but it is recommended to use * methods added by X509HostnameVerifier. * * @since 4.0 */ public interface X509HostnameVerifier extends HostnameVerifier { /** * Verifies that the host name is an acceptable match with the server's * authentication scheme based on the given {@link SSLSocket}. * * @param host the host. * @param ssl the SSL socket. * @throws IOException if an I/O error occurs or the verification process * fails. */ void verify(String host, SSLSocket ssl) throws IOException; /** * Verifies that the host name is an acceptable match with the server's * authentication scheme based on the given {@link X509Certificate}. * * @param host the host. * @param cert the certificate. * @throws SSLException if the verification process fails. */ void verify(String host, X509Certificate cert) throws SSLException; /** * Checks to see if the supplied hostname matches any of the supplied CNs * or "DNS" Subject-Alts. Most implementations only look at the first CN, * and ignore any additional CNs. Most implementations do look at all of * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards * according to RFC 2818. * * @param cns CN fields, in order, as extracted from the X.509 * certificate. * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted * from the X.509 certificate. * @param host The hostname to verify. * @throws SSLException if the verification process fails. */ void verify(String host, String[] cns, String[] subjectAlts) throws SSLException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.ssl; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * @since 4.1 */ class TrustManagerDecorator implements X509TrustManager { private final X509TrustManager trustManager; private final TrustStrategy trustStrategy; TrustManagerDecorator(final X509TrustManager trustManager, final TrustStrategy trustStrategy) { super(); this.trustManager = trustManager; this.trustStrategy = trustStrategy; } public void checkClientTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { this.trustManager.checkClientTrusted(chain, authType); } public void checkServerTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { if (!this.trustStrategy.isTrusted(chain, authType)) { this.trustManager.checkServerTrusted(chain, authType); } } public X509Certificate[] getAcceptedIssuers() { return this.trustManager.getAcceptedIssuers(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.ssl; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * A strategy to establish trustworthiness of certificates without consulting the trust manager * configured in the actual SSL context. This interface can be used to override the standard * JSSE certificate verification process. * * @since 4.1 */ public interface TrustStrategy { /** * Determines whether the certificate chain can be trusted without consulting the trust manager * configured in the actual SSL context. This method can be used to override the standard JSSE * certificate verification process. * <p> * Please note that, if this method returns <code>false</code>, the trust manager configured * in the actual SSL context can still clear the certificate as trusted. * * @param chain the peer certificate chain * @param authType the authentication type based on the client certificate * @return <code>true</code> if the certificate can be trusted without verification by * the trust manager, <code>false</code> otherwise. * @throws CertificateException thrown if the certificate is not trusted or invalid. */ boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.ssl; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.ConnectTimeoutException; import org.apache.ogt.http.conn.scheme.HostNameResolver; import org.apache.ogt.http.conn.scheme.LayeredSchemeSocketFactory; import org.apache.ogt.http.conn.scheme.LayeredSocketFactory; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; /** * Layered socket factory for TLS/SSL connections. * <p> * SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of * trusted certificates and to authenticate to the HTTPS server using a private key. * <p> * SSLSocketFactory will enable server authentication when supplied with * a {@link KeyStore trust-store} file containing one or several trusted certificates. The client * secure socket will reject the connection during the SSL session handshake if the target HTTPS * server attempts to authenticate itself with a non-trusted certificate. * <p> * Use JDK keytool utility to import a trusted certificate and generate a trust-store file: * <pre> * keytool -import -alias "my server cert" -file server.crt -keystore my.truststore * </pre> * <p> * In special cases the standard trust verification process can be bypassed by using a custom * {@link TrustStrategy}. This interface is primarily intended for allowing self-signed * certificates to be accepted as trusted without having to add them to the trust-store file. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li> * </ul> * <p> * SSLSocketFactory will enable client authentication when supplied with * a {@link KeyStore key-store} file containing a private key/public certificate * pair. The client secure socket will use the private key to authenticate * itself to the target HTTPS server during the SSL session handshake if * requested to do so by the server. * The target HTTPS server will in its turn verify the certificate presented * by the client in order to establish client's authenticity * <p> * Use the following sequence of actions to generate a key-store file * </p> * <ul> * <li> * <p> * Use JDK keytool utility to generate a new key * <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre> * For simplicity use the same password for the key as that of the key-store * </p> * </li> * <li> * <p> * Issue a certificate signing request (CSR) * <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Send the certificate request to the trusted Certificate Authority for signature. * One may choose to act as her own CA and sign the certificate request using a PKI * tool, such as OpenSSL. * </p> * </li> * <li> * <p> * Import the trusted CA root certificate * <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Import the PKCS#7 file containg the complete certificate chain * <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Verify the content the resultant keystore file * <pre>keytool -list -v -keystore my.keystore</pre> * </p> * </li> * </ul> * * @since 4.0 */ @SuppressWarnings("deprecation") @ThreadSafe public class SSLSocketFactory implements LayeredSchemeSocketFactory, LayeredSocketFactory { public static final String TLS = "TLS"; public static final String SSL = "SSL"; public static final String SSLV2 = "SSLv2"; public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier(); public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER = new BrowserCompatHostnameVerifier(); public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER = new StrictHostnameVerifier(); /** * Gets the default factory, which uses the default JVM settings for secure * connections. * * @return the default factory */ public static SSLSocketFactory getSocketFactory() { return new SSLSocketFactory(); } private final javax.net.ssl.SSLSocketFactory socketfactory; private final HostNameResolver nameResolver; // TODO: make final private volatile X509HostnameVerifier hostnameVerifier; private static SSLContext createSSLContext( String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { if (algorithm == null) { algorithm = TLS; } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray(): null); KeyManager[] keymanagers = kmfactory.getKeyManagers(); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(truststore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); if (trustmanagers != null && trustStrategy != null) { for (int i = 0; i < trustmanagers.length; i++) { TrustManager tm = trustmanagers[i]; if (tm instanceof X509TrustManager) { trustmanagers[i] = new TrustManagerDecorator( (X509TrustManager) tm, trustStrategy); } } } SSLContext sslcontext = SSLContext.getInstance(algorithm); sslcontext.init(keymanagers, trustmanagers, random); return sslcontext; } private static SSLContext createDefaultSSLContext() { try { return createSSLContext(TLS, null, null, null, null, null); } catch (Exception ex) { throw new IllegalStateException("Failure initializing default SSL context", ex); } } /** * @deprecated Use {@link #SSLSocketFactory(String, KeyStore, String, KeyStore, SecureRandom, X509HostnameVerifier)} */ @Deprecated public SSLSocketFactory( final String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(createSSLContext( algorithm, keystore, keystorePassword, truststore, random, null), nameResolver); } /** * @since 4.1 */ public SSLSocketFactory( String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final X509HostnameVerifier hostnameVerifier) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(createSSLContext( algorithm, keystore, keystorePassword, truststore, random, null), hostnameVerifier); } /** * @since 4.1 */ public SSLSocketFactory( String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final TrustStrategy trustStrategy, final X509HostnameVerifier hostnameVerifier) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(createSSLContext( algorithm, keystore, keystorePassword, truststore, random, trustStrategy), hostnameVerifier); } public SSLSocketFactory( final KeyStore keystore, final String keystorePassword, final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, keystore, keystorePassword, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } public SSLSocketFactory( final KeyStore keystore, final String keystorePassword) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException{ this(TLS, keystore, keystorePassword, null, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } public SSLSocketFactory( final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, null, null, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } /** * @since 4.1 */ public SSLSocketFactory( final TrustStrategy trustStrategy, final X509HostnameVerifier hostnameVerifier) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, null, null, null, null, trustStrategy, hostnameVerifier); } /** * @since 4.1 */ public SSLSocketFactory( final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, null, null, null, null, trustStrategy, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } public SSLSocketFactory(final SSLContext sslContext) { this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } /** * @deprecated Use {@link #SSLSocketFactory(SSLContext)} */ @Deprecated public SSLSocketFactory( final SSLContext sslContext, final HostNameResolver nameResolver) { super(); this.socketfactory = sslContext.getSocketFactory(); this.hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; this.nameResolver = nameResolver; } /** * @since 4.1 */ public SSLSocketFactory( final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) { super(); this.socketfactory = sslContext.getSocketFactory(); this.hostnameVerifier = hostnameVerifier; this.nameResolver = null; } private SSLSocketFactory() { this(createDefaultSSLContext()); } /** * @param params Optional parameters. Parameters passed to this method will have no effect. * This method will create a unconnected instance of {@link Socket} class. * @since 4.1 */ public Socket createSocket(final HttpParams params) throws IOException { return this.socketfactory.createSocket(); } @Deprecated public Socket createSocket() throws IOException { return this.socketfactory.createSocket(); } /** * @since 4.1 */ public Socket connectSocket( final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock = socket != null ? socket : new Socket(); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out"); } SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { sslsock = (SSLSocket) this.socketfactory.createSocket( sock, remoteAddress.getHostName(), remoteAddress.getPort(), true); } if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } } return sslsock; } /** * Checks whether a socket connection is secure. * This factory creates TLS/SSL socket connections * which, by default, are considered secure. * <br/> * Derived classes may override this method to perform * runtime checks, for example based on the cypher suite. * * @param sock the connected socket * * @return <code>true</code> * * @throws IllegalArgumentException if the argument is invalid */ public boolean isSecure(final Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null"); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException("Socket not created by this factory"); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed"); } return true; } /** * @since 4.1 */ public Socket createLayeredSocket( final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket( socket, host, port, autoClose ); if (this.hostnameVerifier != null) { this.hostnameVerifier.verify(host, sslSocket); } // verifyHostName() didn't blowup - good! return sslSocket; } @Deprecated public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) { if ( hostnameVerifier == null ) { throw new IllegalArgumentException("Hostname verifier may not be null"); } this.hostnameVerifier = hostnameVerifier; } public X509HostnameVerifier getHostnameVerifier() { return this.hostnameVerifier; } /** * @deprecated Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)} */ @Deprecated public Socket connectSocket( final Socket socket, final String host, int port, final InetAddress localAddress, int localPort, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { InetSocketAddress local = null; if (localAddress != null || localPort > 0) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } local = new InetSocketAddress(localAddress, localPort); } InetAddress remoteAddress; if (this.nameResolver != null) { remoteAddress = this.nameResolver.resolve(host); } else { remoteAddress = InetAddress.getByName(host); } InetSocketAddress remote = new InetSocketAddress(remoteAddress, port); return connectSocket(socket, remote, local, params); } /** * @deprecated Use {@link #createLayeredSocket(Socket, String, int, boolean)} */ @Deprecated public Socket createSocket( final Socket socket, final String host, int port, boolean autoClose) throws IOException, UnknownHostException { return createLayeredSocket(socket, host, port, autoClose); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.ssl; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.conn.util.InetAddressUtils; import java.io.IOException; import java.io.InputStream; import java.security.cert.Certificate; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import java.util.logging.Logger; import java.util.logging.Level; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; /** * Abstract base class for all standard {@link X509HostnameVerifier} * implementations. * * @since 4.0 */ @Immutable public abstract class AbstractVerifier implements X509HostnameVerifier { /** * This contains a list of 2nd-level domains that aren't allowed to * have wildcards when combined with country-codes. * For example: [*.co.uk]. * <p/> * The [*.co.uk] problem is an interesting one. Should we just hope * that CA's would never foolishly allow such a certificate to happen? * Looks like we're the only implementation guarding against this. * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check. */ private final static String[] BAD_COUNTRY_2LDS = { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", "lg", "ne", "net", "or", "org" }; static { // Just in case developer forgot to manually sort the array. :-) Arrays.sort(BAD_COUNTRY_2LDS); } public AbstractVerifier() { super(); } public final void verify(String host, SSLSocket ssl) throws IOException { if(host == null) { throw new NullPointerException("host to verify is null"); } SSLSession session = ssl.getSession(); if(session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: InputStream in = ssl.getInputStream(); in.available(); /* If you're looking at the 2 lines of code above because you're running into a problem, you probably have two options: #1. Clean up the certificate chain that your server is presenting (e.g. edit "/etc/apache2/server.crt" or wherever it is your server's certificate chain is defined). OR #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = ssl.getSession(); if(session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } Certificate[] certs = session.getPeerCertificates(); X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); } public final boolean verify(String host, SSLSession session) { try { Certificate[] certs = session.getPeerCertificates(); X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); return true; } catch(SSLException e) { return false; } } public final void verify(String host, X509Certificate cert) throws SSLException { String[] cns = getCNs(cert); String[] subjectAlts = getSubjectAlts(cert, host); verify(host, cns, subjectAlts); } public final void verify(final String host, final String[] cns, final String[] subjectAlts, final boolean strictWithSubDomains) throws SSLException { // Build the list of names we're going to check. Our DEFAULT and // STRICT implementations of the HostnameVerifier only use the // first CN provided. All other CNs are ignored. // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way). LinkedList<String> names = new LinkedList<String>(); if(cns != null && cns.length > 0 && cns[0] != null) { names.add(cns[0]); } if(subjectAlts != null) { for (String subjectAlt : subjectAlts) { if (subjectAlt != null) { names.add(subjectAlt); } } } if(names.isEmpty()) { String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt"; throw new SSLException(msg); } // StringBuilder for building the error message. StringBuilder buf = new StringBuilder(); // We're can be case-insensitive when comparing the host we used to // establish the socket to the hostname in the certificate. String hostName = host.trim().toLowerCase(Locale.ENGLISH); boolean match = false; for(Iterator<String> it = names.iterator(); it.hasNext();) { // Don't trim the CN, though! String cn = it.next(); cn = cn.toLowerCase(Locale.ENGLISH); // Store CN in StringBuilder in case we need to report an error. buf.append(" <"); buf.append(cn); buf.append('>'); if(it.hasNext()) { buf.append(" OR"); } // The CN better have at least two dots if it wants wildcard // action. It also can't be [*.co.uk] or [*.co.jp] or // [*.org.uk], etc... boolean doWildcard = cn.startsWith("*.") && cn.lastIndexOf('.') >= 0 && acceptableCountryWildcard(cn) && !isIPAddress(host); if(doWildcard) { match = hostName.endsWith(cn.substring(1)); if(match && strictWithSubDomains) { // If we're in strict mode, then [*.foo.com] is not // allowed to match [a.b.foo.com] match = countDots(hostName) == countDots(cn); } } else { match = hostName.equals(cn); } if(match) { break; } } if(!match) { throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf); } } public static boolean acceptableCountryWildcard(String cn) { int cnLen = cn.length(); if(cnLen >= 7 && cnLen <= 9) { // Look for the '.' in the 3rd-last position: if(cn.charAt(cnLen - 3) == '.') { // Trim off the [*.] and the [.XX]. String s = cn.substring(2, cnLen - 3); // And test against the sorted array of bad 2lds: int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s); return x < 0; } } return true; } public static String[] getCNs(X509Certificate cert) { LinkedList<String> cnList = new LinkedList<String>(); /* Sebastian Hauer's original StrictSSLProtocolSocketFactory used getName() and had the following comment: Parses a X.500 distinguished name for the value of the "Common Name" field. This is done a bit sloppy right now and should probably be done a bit more according to <code>RFC 2253</code>. I've noticed that toString() seems to do a better job than getName() on these X500Principal objects, so I'm hoping that addresses Sebastian's concern. For example, getName() gives me this: 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d whereas toString() gives me this: EMAILADDRESS=juliusdavies@cucbc.com Looks like toString() even works with non-ascii domain names! I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine. */ String subjectPrincipal = cert.getSubjectX500Principal().toString(); StringTokenizer st = new StringTokenizer(subjectPrincipal, ","); while(st.hasMoreTokens()) { String tok = st.nextToken(); int x = tok.indexOf("CN="); if(x >= 0) { cnList.add(tok.substring(x + 3)); } } if(!cnList.isEmpty()) { String[] cns = new String[cnList.size()]; cnList.toArray(cns); return cns; } else { return null; } } /** * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate. * Returns null if there aren't any. * * @param cert X509Certificate * @param hostname * @return Array of SubjectALT DNS or IP names stored in the certificate. */ private static String[] getSubjectAlts( final X509Certificate cert, final String hostname) { int subjectType; if (isIPAddress(hostname)) { subjectType = 7; } else { subjectType = 2; } LinkedList<String> subjectAltList = new LinkedList<String>(); Collection<List<?>> c = null; try { c = cert.getSubjectAlternativeNames(); } catch(CertificateParsingException cpe) { Logger.getLogger(AbstractVerifier.class.getName()) .log(Level.FINE, "Error parsing certificate.", cpe); } if(c != null) { for (List<?> aC : c) { List<?> list = aC; int type = ((Integer) list.get(0)).intValue(); if (type == subjectType) { String s = (String) list.get(1); subjectAltList.add(s); } } } if(!subjectAltList.isEmpty()) { String[] subjectAlts = new String[subjectAltList.size()]; subjectAltList.toArray(subjectAlts); return subjectAlts; } else { return null; } } /** * Extracts the array of SubjectAlt DNS names from an X509Certificate. * Returns null if there aren't any. * <p/> * Note: Java doesn't appear able to extract international characters * from the SubjectAlts. It can only extract international characters * from the CN field. * <p/> * (Or maybe the version of OpenSSL I'm using to test isn't storing the * international characters correctly in the SubjectAlts?). * * @param cert X509Certificate * @return Array of SubjectALT DNS names stored in the certificate. */ public static String[] getDNSSubjectAlts(X509Certificate cert) { return getSubjectAlts(cert, null); } /** * Counts the number of dots "." in a string. * @param s string to count dots from * @return number of dots */ public static int countDots(final String s) { int count = 0; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '.') { count++; } } return count; } private static boolean isIPAddress(final String hostname) { return hostname != null && (InetAddressUtils.isIPv4Address(hostname) || InetAddressUtils.isIPv6Address(hostname)); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.params.HttpParams; /** * A factory for creating new {@link ClientConnectionManager} instances. * * * @since 4.0 */ public interface ClientConnectionManagerFactory { ClientConnectionManager newInstance( HttpParams params, SchemeRegistry schemeRegistry); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.IOException; import java.net.Socket; import org.apache.ogt.http.HttpClientConnection; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpInetConnection; import org.apache.ogt.http.params.HttpParams; /** * A client-side connection that relies on outside logic to connect sockets to the * appropriate hosts. It can be operated directly by an application, or through an * {@link ClientConnectionOperator operator}. * * @since 4.0 */ public interface OperatedClientConnection extends HttpClientConnection, HttpInetConnection { /** * Obtains the target host for this connection. * If the connection is to a proxy but not tunnelled, this is * the proxy. If the connection is tunnelled through a proxy, * this is the target of the tunnel. * <br/> * The return value is well-defined only while the connection is open. * It may change even while the connection is open, * because of an {@link #update update}. * * @return the host to which this connection is opened */ HttpHost getTargetHost(); /** * Indicates whether this connection is secure. * The return value is well-defined only while the connection is open. * It may change even while the connection is open, * because of an {@link #update update}. * * @return <code>true</code> if this connection is secure, * <code>false</code> otherwise */ boolean isSecure(); /** * Obtains the socket for this connection. * The return value is well-defined only while the connection is open. * It may change even while the connection is open, * because of an {@link #update update}. * * @return the socket for communicating with the * {@link #getTargetHost target host} */ Socket getSocket(); /** * Signals that this connection is in the process of being open. * <p> * By calling this method, the connection can be re-initialized * with a new Socket instance before {@link #openCompleted} is called. * This enabled the connection to close that socket if * {@link org.apache.ogt.http.HttpConnection#shutdown shutdown} * is called before it is fully open. Closing an unconnected socket * will interrupt a thread that is blocked on the connect. * Otherwise, that thread will either time out on the connect, * or it returns successfully and then opens this connection * which was just shut down. * <p> * This method can be called multiple times if the connection * is layered over another protocol. <b>Note:</b> This method * will <i>not</i> close the previously used socket. It is * the caller's responsibility to close that socket if it is * no longer required. * <p> * The caller must invoke {@link #openCompleted} in order to complete * the process. * * @param sock the unconnected socket which is about to * be connected. * @param target the target host of this connection */ void opening(Socket sock, HttpHost target) throws IOException; /** * Signals that the connection has been successfully open. * An attempt to call this method on an open connection will cause * an exception. * * @param secure <code>true</code> if this connection is secure, for * example if an <code>SSLSocket</code> is used, or * <code>false</code> if it is not secure * @param params parameters for this connection. The parameters will * be used when creating dependent objects, for example * to determine buffer sizes. */ void openCompleted(boolean secure, HttpParams params) throws IOException; /** * Updates this connection. * A connection can be updated only while it is open. * Updates are used for example when a tunnel has been established, * or when a TLS/SSL connection has been layered on top of a plain * socket connection. * <br/> * <b>Note:</b> Updating the connection will <i>not</i> close the * previously used socket. It is the caller's responsibility to close * that socket if it is no longer required. * * @param sock the new socket for communicating with the target host, * or <code>null</code> to continue using the old socket. * If <code>null</code> is passed, helper objects that * depend on the socket should be re-used. In that case, * some changes in the parameters will not take effect. * @param target the new target host of this connection * @param secure <code>true</code> if this connection is now secure, * <code>false</code> if it is not secure * @param params new parameters for this connection */ void update(Socket sock, HttpHost target, boolean secure, HttpParams params) throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.conn.scheme.SchemeSocketFactory; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * ClientConnectionOperator represents a strategy for creating * {@link OperatedClientConnection} instances and updating the underlying * {@link Socket} of those objects. Implementations will most likely make use * of {@link SchemeSocketFactory}s to create {@link Socket} instances. * <p> * The methods in this interface allow the creation of plain and layered * sockets. Creating a tunnelled connection through a proxy, however, * is not within the scope of the operator. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface ClientConnectionOperator { /** * Creates a new connection that can be operated. * * @return a new, unopened connection for use with this operator */ OperatedClientConnection createConnection(); /** * Opens a connection to the given target host. * * @param conn the connection to open * @param target the target host to connect to * @param local the local address to route from, or * <code>null</code> for the default * @param context the context for the connection * @param params the parameters for the connection * * @throws IOException in case of a problem */ void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException; /** * Updates a connection with a layered secure connection. * The typical use of this method is to update a tunnelled plain * connection (HTTP) to a secure TLS/SSL connection (HTTPS). * * @param conn the open connection to update * @param target the target host for the updated connection. * The connection must already be open or tunnelled * to the host and port, but the scheme of the target * will be used to create a layered connection. * @param context the context for the connection * @param params the parameters for the updated connection * * @throws IOException in case of a problem */ void updateSecureConnection(OperatedClientConnection conn, HttpHost target, HttpContext context, HttpParams params) throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import javax.net.ssl.SSLSession; import org.apache.ogt.http.HttpInetConnection; import org.apache.ogt.http.conn.routing.HttpRoute; /** * Interface to access routing information of a client side connection. * * @since 4.1 */ public interface HttpRoutedConnection extends HttpInetConnection { /** * Indicates whether this connection is secure. * The return value is well-defined only while the connection is open. * It may change even while the connection is open. * * @return <code>true</code> if this connection is secure, * <code>false</code> otherwise */ boolean isSecure(); /** * Obtains the current route of this connection. * * @return the route established so far, or * <code>null</code> if not connected */ HttpRoute getRoute(); /** * Obtains the SSL session of the underlying connection, if any. * If this connection is open, and the underlying socket is an * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of * that socket is obtained. This is a potentially blocking operation. * <br/> * <b>Note:</b> Whether the underlying socket is an SSL socket * can not necessarily be determined via {@link #isSecure}. * Plain sockets may be considered secure, for example if they are * connected to a known host in the same network segment. * On the other hand, SSL sockets may be considered insecure, * for example depending on the chosen cipher suite. * * @return the underlying SSL session if available, * <code>null</code> otherwise */ SSLSession getSSLSession(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLSession; import org.apache.ogt.http.HttpClientConnection; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * A client-side connection with advanced connection logic. * Instances are typically obtained from a connection manager. * * @since 4.0 */ public interface ManagedClientConnection extends HttpClientConnection, HttpRoutedConnection, ConnectionReleaseTrigger { /** * Indicates whether this connection is secure. * The return value is well-defined only while the connection is open. * It may change even while the connection is open. * * @return <code>true</code> if this connection is secure, * <code>false</code> otherwise */ boolean isSecure(); /** * Obtains the current route of this connection. * * @return the route established so far, or * <code>null</code> if not connected */ HttpRoute getRoute(); /** * Obtains the SSL session of the underlying connection, if any. * If this connection is open, and the underlying socket is an * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of * that socket is obtained. This is a potentially blocking operation. * <br/> * <b>Note:</b> Whether the underlying socket is an SSL socket * can not necessarily be determined via {@link #isSecure}. * Plain sockets may be considered secure, for example if they are * connected to a known host in the same network segment. * On the other hand, SSL sockets may be considered insecure, * for example depending on the chosen cipher suite. * * @return the underlying SSL session if available, * <code>null</code> otherwise */ SSLSession getSSLSession(); /** * Opens this connection according to the given route. * * @param route the route along which to open. It will be opened to * the first proxy if present, or directly to the target. * @param context the context for opening this connection * @param params the parameters for opening this connection * * @throws IOException in case of a problem */ void open(HttpRoute route, HttpContext context, HttpParams params) throws IOException; /** * Indicates that a tunnel to the target has been established. * The route is the one previously passed to {@link #open open}. * Subsequently, {@link #layerProtocol layerProtocol} can be called * to layer the TLS/SSL protocol on top of the tunnelled connection. * <br/> * <b>Note:</b> In HttpClient 3, a call to the corresponding method * would automatically trigger the layering of the TLS/SSL protocol. * This is not the case anymore, you can establish a tunnel without * layering a new protocol over the connection. * * @param secure <code>true</code> if the tunnel should be considered * secure, <code>false</code> otherwise * @param params the parameters for tunnelling this connection * * @throws IOException in case of a problem */ void tunnelTarget(boolean secure, HttpParams params) throws IOException; /** * Indicates that a tunnel to an intermediate proxy has been established. * This is used exclusively for so-called <i>proxy chains</i>, where * a request has to pass through multiple proxies before reaching the * target. In that case, all proxies but the last need to be tunnelled * when establishing the connection. Tunnelling of the last proxy to the * target is optional and would be indicated via {@link #tunnelTarget}. * * @param next the proxy to which the tunnel was established. * This is <i>not</i> the proxy <i>through</i> which * the tunnel was established, but the new end point * of the tunnel. The tunnel does <i>not</i> yet * reach to the target, use {@link #tunnelTarget} * to indicate an end-to-end tunnel. * @param secure <code>true</code> if the connection should be * considered secure, <code>false</code> otherwise * @param params the parameters for tunnelling this connection * * @throws IOException in case of a problem */ void tunnelProxy(HttpHost next, boolean secure, HttpParams params) throws IOException; /** * Layers a new protocol on top of a {@link #tunnelTarget tunnelled} * connection. This is typically used to create a TLS/SSL connection * through a proxy. * The route is the one previously passed to {@link #open open}. * It is not guaranteed that the layered connection is * {@link #isSecure secure}. * * @param context the context for layering on top of this connection * @param params the parameters for layering on top of this connection * * @throws IOException in case of a problem */ void layerProtocol(HttpContext context, HttpParams params) throws IOException; /** * Marks this connection as being in a reusable communication state. * The checkpoints for reuseable communication states (in the absence * of pipelining) are before sending a request and after receiving * the response in its entirety. * The connection will automatically clear the checkpoint when * used for communication. A call to this method indicates that * the next checkpoint has been reached. * <br/> * A reusable communication state is necessary but not sufficient * for the connection to be reused. * A {@link #getRoute route} mismatch, the connection being closed, * or other circumstances might prevent reuse. */ void markReusable(); /** * Marks this connection as not being in a reusable state. * This can be used immediately before releasing this connection * to prevent its reuse. Reasons for preventing reuse include * error conditions and the evaluation of a * {@link org.apache.ogt.http.ConnectionReuseStrategy reuse strategy}. * <br/> * <b>Note:</b> * It is <i>not</i> necessary to call here before writing to * or reading from this connection. Communication attempts will * automatically unmark the state as non-reusable. It can then * be switched back using {@link #markReusable markReusable}. */ void unmarkReusable(); /** * Indicates whether this connection is in a reusable communication state. * See {@link #markReusable markReusable} and * {@link #unmarkReusable unmarkReusable} for details. * * @return <code>true</code> if this connection is marked as being in * a reusable communication state, * <code>false</code> otherwise */ boolean isMarkedReusable(); /** * Assigns a state object to this connection. Connection managers may make * use of the connection state when allocating persistent connections. * * @param state The state object */ void setState(Object state); /** * Returns the state object associated with this connection. * * @return The state object */ Object getState(); /** * Sets the duration that this connection can remain idle before it is * reused. The connection should not be used again if this time elapses. The * idle duration must be reset after each request sent over this connection. * The elapsed time starts counting when the connection is released, which * is typically after the headers (and any response body, if present) is * fully consumed. */ void setIdleDuration(long duration, TimeUnit unit); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import java.net.InetAddress; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.params.HttpAbstractParamBean; import org.apache.ogt.http.params.HttpParams; /** * This is a Java Bean class that can be used to wrap an instance of * {@link HttpParams} and manipulate connection routing parameters * using Java Beans conventions. * * @since 4.0 */ @NotThreadSafe public class ConnRouteParamBean extends HttpAbstractParamBean { public ConnRouteParamBean (final HttpParams params) { super(params); } /** @see ConnRoutePNames#DEFAULT_PROXY */ public void setDefaultProxy (final HttpHost defaultProxy) { params.setParameter(ConnRoutePNames.DEFAULT_PROXY, defaultProxy); } /** @see ConnRoutePNames#LOCAL_ADDRESS */ public void setLocalAddress (final InetAddress address) { params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, address); } /** @see ConnRoutePNames#FORCED_ROUTE */ public void setForcedRoute (final HttpRoute route) { params.setParameter(ConnRoutePNames.FORCED_ROUTE, route); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; /** * Parameter names for connection routing. * * @since 4.0 */ public interface ConnRoutePNames { /** * Parameter for the default proxy. * The default value will be used by some * {@link org.apache.ogt.http.conn.routing.HttpRoutePlanner HttpRoutePlanner} * implementations, in particular the default implementation. * <p> * This parameter expects a value of type {@link org.apache.ogt.http.HttpHost}. * </p> */ public static final String DEFAULT_PROXY = "http.route.default-proxy"; /** * Parameter for the local address. * On machines with multiple network interfaces, this parameter * can be used to select the network interface from which the * connection originates. * It will be interpreted by the standard * {@link org.apache.ogt.http.conn.routing.HttpRoutePlanner HttpRoutePlanner} * implementations, in particular the default implementation. * <p> * This parameter expects a value of type {@link java.net.InetAddress}. * </p> */ public static final String LOCAL_ADDRESS = "http.route.local-address"; /** * Parameter for an forced route. * The forced route will be interpreted by the standard * {@link org.apache.ogt.http.conn.routing.HttpRoutePlanner HttpRoutePlanner} * implementations. * Instead of computing a route, the given forced route will be * returned, even if it points to the wrong target host. * <p> * This parameter expects a value of type * {@link org.apache.ogt.http.conn.routing.HttpRoute HttpRoute}. * </p> */ public static final String FORCED_ROUTE = "http.route.forced-route"; }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; /** * An adaptor for manipulating HTTP connection management * parameters in {@link HttpParams}. * * @since 4.0 * * @see ConnManagerPNames */ @Deprecated @Immutable public final class ConnManagerParams implements ConnManagerPNames { /** The default maximum number of connections allowed overall */ public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 20; /** * Returns the timeout in milliseconds used when retrieving a * {@link org.apache.ogt.http.conn.ManagedClientConnection} from the * {@link org.apache.ogt.http.conn.ClientConnectionManager}. * * @return timeout in milliseconds. * * @deprecated use {@link HttpConnectionParams#getConnectionTimeout(HttpParams)} */ @Deprecated public static long getTimeout(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getLongParameter(TIMEOUT, 0); } /** * Sets the timeout in milliseconds used when retrieving a * {@link org.apache.ogt.http.conn.ManagedClientConnection} from the * {@link org.apache.ogt.http.conn.ClientConnectionManager}. * * @param timeout the timeout in milliseconds * * @deprecated use {@link HttpConnectionParams#setConnectionTimeout(HttpParams, int)} */ @Deprecated public static void setTimeout(final HttpParams params, long timeout) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setLongParameter(TIMEOUT, timeout); } /** The default maximum number of connections allowed per host */ private static final ConnPerRoute DEFAULT_CONN_PER_ROUTE = new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return ConnPerRouteBean.DEFAULT_MAX_CONNECTIONS_PER_ROUTE; } }; /** * Sets lookup interface for maximum number of connections allowed per route. * * @param params HTTP parameters * @param connPerRoute lookup interface for maximum number of connections allowed * per route * * @deprecated use {@link ThreadSafeClientConnManager#setMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute, int)} */ @Deprecated public static void setMaxConnectionsPerRoute(final HttpParams params, final ConnPerRoute connPerRoute) { if (params == null) { throw new IllegalArgumentException ("HTTP parameters must not be null."); } params.setParameter(MAX_CONNECTIONS_PER_ROUTE, connPerRoute); } /** * Returns lookup interface for maximum number of connections allowed per route. * * @param params HTTP parameters * * @return lookup interface for maximum number of connections allowed per route. * * @deprecated use {@link ThreadSafeClientConnManager#getMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute)} */ @Deprecated public static ConnPerRoute getMaxConnectionsPerRoute(final HttpParams params) { if (params == null) { throw new IllegalArgumentException ("HTTP parameters must not be null."); } ConnPerRoute connPerRoute = (ConnPerRoute) params.getParameter(MAX_CONNECTIONS_PER_ROUTE); if (connPerRoute == null) { connPerRoute = DEFAULT_CONN_PER_ROUTE; } return connPerRoute; } /** * Sets the maximum number of connections allowed. * * @param params HTTP parameters * @param maxTotalConnections The maximum number of connections allowed. * * @deprecated use {@link ThreadSafeClientConnManager#setMaxTotal(int)} */ @Deprecated public static void setMaxTotalConnections( final HttpParams params, int maxTotalConnections) { if (params == null) { throw new IllegalArgumentException ("HTTP parameters must not be null."); } params.setIntParameter(MAX_TOTAL_CONNECTIONS, maxTotalConnections); } /** * Gets the maximum number of connections allowed. * * @param params HTTP parameters * * @return The maximum number of connections allowed. * * @deprecated use {@link ThreadSafeClientConnManager#getMaxTotal()} */ @Deprecated public static int getMaxTotalConnections( final HttpParams params) { if (params == null) { throw new IllegalArgumentException ("HTTP parameters must not be null."); } return params.getIntParameter(MAX_TOTAL_CONNECTIONS, DEFAULT_MAX_TOTAL_CONNECTIONS); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; /** * Parameter names for HTTP client connections. * * @since 4.0 */ public interface ConnConnectionPNames { /** * Defines the maximum number of ignorable lines before we expect * a HTTP response's status line. * <p> * With HTTP/1.1 persistent connections, the problem arises that * broken scripts could return a wrong Content-Length * (there are more bytes sent than specified). * Unfortunately, in some cases, this cannot be detected after the * bad response, but only before the next one. * So HttpClient must be able to skip those surplus lines this way. * </p> * <p> * This parameter expects a value of type {@link Integer}. * 0 disallows all garbage/empty lines before the status line. * Use {@link java.lang.Integer#MAX_VALUE} for unlimited number. * </p> */ public static final String MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.params.HttpAbstractParamBean; import org.apache.ogt.http.params.HttpParams; /** * This is a Java Bean class that can be used to wrap an instance of * {@link HttpParams} and manipulate connection manager parameters * using Java Beans conventions. * * @since 4.0 */ @NotThreadSafe @Deprecated public class ConnManagerParamBean extends HttpAbstractParamBean { public ConnManagerParamBean (final HttpParams params) { super(params); } public void setTimeout (final long timeout) { params.setLongParameter(ConnManagerPNames.TIMEOUT, timeout); } /** @see ConnManagerPNames#MAX_TOTAL_CONNECTIONS */ @Deprecated public void setMaxTotalConnections (final int maxConnections) { params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, maxConnections); } /** @see ConnManagerPNames#MAX_CONNECTIONS_PER_ROUTE */ @Deprecated public void setConnectionsPerRoute(final ConnPerRouteBean connPerRoute) { params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, connPerRoute); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.ogt.http.params.CoreConnectionPNames; /** * Parameter names for connection managers in HttpConn. * * @since 4.0 */ @Deprecated public interface ConnManagerPNames { /** * Defines the timeout in milliseconds used when retrieving an instance of * {@link org.apache.ogt.http.conn.ManagedClientConnection} from the * {@link org.apache.ogt.http.conn.ClientConnectionManager}. * <p> * This parameter expects a value of type {@link Long}. * <p> * @deprecated use {@link CoreConnectionPNames#CONNECTION_TIMEOUT} */ @Deprecated public static final String TIMEOUT = "http.conn-manager.timeout"; /** * Defines the maximum number of connections per route. * This limit is interpreted by client connection managers * and applies to individual manager instances. * <p> * This parameter expects a value of type {@link ConnPerRoute}. * <p> * @deprecated use {@link ThreadSafeClientConnManager#setMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute, int)}, * {@link ThreadSafeClientConnManager#getMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute)} */ @Deprecated public static final String MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route"; /** * Defines the maximum number of connections in total. * This limit is interpreted by client connection managers * and applies to individual manager instances. * <p> * This parameter expects a value of type {@link Integer}. * <p> * @deprecated use {@link ThreadSafeClientConnManager#setMaxTotal(int)}, * {@link ThreadSafeClientConnManager#getMaxTotal()} */ @Deprecated public static final String MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.params.HttpAbstractParamBean; import org.apache.ogt.http.params.HttpParams; /** * This is a Java Bean class that can be used to wrap an instance of * {@link HttpParams} and manipulate HTTP client connection parameters * using Java Beans conventions. * * @since 4.0 */ @NotThreadSafe public class ConnConnectionParamBean extends HttpAbstractParamBean { public ConnConnectionParamBean (final HttpParams params) { super(params); } /** * @see ConnConnectionPNames#MAX_STATUS_LINE_GARBAGE */ public void setMaxStatusLineGarbage (final int maxStatusLineGarbage) { params.setIntParameter(ConnConnectionPNames.MAX_STATUS_LINE_GARBAGE, maxStatusLineGarbage); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.routing.HttpRoute; /** * This class maintains a map of HTTP routes to maximum number of connections allowed * for those routes. This class can be used by pooling * {@link org.apache.ogt.http.conn.ClientConnectionManager connection managers} for * a fine-grained control of connections on a per route basis. * * @since 4.0 */ @ThreadSafe public final class ConnPerRouteBean implements ConnPerRoute { /** The default maximum number of connections allowed per host */ public static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2; // Per RFC 2616 sec 8.1.4 private final ConcurrentHashMap<HttpRoute, Integer> maxPerHostMap; private volatile int defaultMax; public ConnPerRouteBean(int defaultMax) { super(); this.maxPerHostMap = new ConcurrentHashMap<HttpRoute, Integer>(); setDefaultMaxPerRoute(defaultMax); } public ConnPerRouteBean() { this(DEFAULT_MAX_CONNECTIONS_PER_ROUTE); } /** * @deprecated Use {@link #getDefaultMaxPerRoute()} instead */ @Deprecated public int getDefaultMax() { return this.defaultMax; } /** * @since 4.1 */ public int getDefaultMaxPerRoute() { return this.defaultMax; } public void setDefaultMaxPerRoute(int max) { if (max < 1) { throw new IllegalArgumentException ("The maximum must be greater than 0."); } this.defaultMax = max; } public void setMaxForRoute(final HttpRoute route, int max) { if (route == null) { throw new IllegalArgumentException ("HTTP route may not be null."); } if (max < 1) { throw new IllegalArgumentException ("The maximum must be greater than 0."); } this.maxPerHostMap.put(route, Integer.valueOf(max)); } public int getMaxForRoute(final HttpRoute route) { if (route == null) { throw new IllegalArgumentException ("HTTP route may not be null."); } Integer max = this.maxPerHostMap.get(route); if (max != null) { return max.intValue(); } else { return this.defaultMax; } } public void setMaxForRoutes(final Map<HttpRoute, Integer> map) { if (map == null) { return; } this.maxPerHostMap.clear(); this.maxPerHostMap.putAll(map); } @Override public String toString() { return this.maxPerHostMap.toString(); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import org.apache.ogt.http.conn.routing.HttpRoute; /** * This interface is intended for looking up maximum number of connections * allowed for a given route. This class can be used by pooling * {@link org.apache.ogt.http.conn.ClientConnectionManager connection managers} for * a fine-grained control of connections on a per route basis. * * @since 4.0 */ public interface ConnPerRoute { int getMaxForRoute(HttpRoute route); }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.params; import java.net.InetAddress; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.params.HttpParams; /** * An adaptor for manipulating HTTP routing parameters * in {@link HttpParams}. * * @since 4.0 */ @Immutable public class ConnRouteParams implements ConnRoutePNames { /** * A special value indicating "no host". * This relies on a nonsense scheme name to avoid conflicts * with actual hosts. Note that this is a <i>valid</i> host. */ public static final HttpHost NO_HOST = new HttpHost("127.0.0.255", 0, "no-host"); // Immutable /** * A special value indicating "no route". * This is a route with {@link #NO_HOST} as the target. */ public static final HttpRoute NO_ROUTE = new HttpRoute(NO_HOST); // Immutable /** Disabled default constructor. */ private ConnRouteParams() { // no body } /** * Obtains the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY} * parameter value. * {@link #NO_HOST} will be mapped to <code>null</code>, * to allow unsetting in a hierarchy. * * @param params the parameters in which to look up * * @return the default proxy set in the argument parameters, or * <code>null</code> if not set */ public static HttpHost getDefaultProxy(HttpParams params) { if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } HttpHost proxy = (HttpHost) params.getParameter(DEFAULT_PROXY); if ((proxy != null) && NO_HOST.equals(proxy)) { // value is explicitly unset proxy = null; } return proxy; } /** * Sets the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY} * parameter value. * * @param params the parameters in which to set the value * @param proxy the value to set, may be <code>null</code>. * Note that {@link #NO_HOST} will be mapped to * <code>null</code> by {@link #getDefaultProxy}, * to allow for explicit unsetting in hierarchies. */ public static void setDefaultProxy(HttpParams params, HttpHost proxy) { if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } params.setParameter(DEFAULT_PROXY, proxy); } /** * Obtains the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE} * parameter value. * {@link #NO_ROUTE} will be mapped to <code>null</code>, * to allow unsetting in a hierarchy. * * @param params the parameters in which to look up * * @return the forced route set in the argument parameters, or * <code>null</code> if not set */ public static HttpRoute getForcedRoute(HttpParams params) { if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } HttpRoute route = (HttpRoute) params.getParameter(FORCED_ROUTE); if ((route != null) && NO_ROUTE.equals(route)) { // value is explicitly unset route = null; } return route; } /** * Sets the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE} * parameter value. * * @param params the parameters in which to set the value * @param route the value to set, may be <code>null</code>. * Note that {@link #NO_ROUTE} will be mapped to * <code>null</code> by {@link #getForcedRoute}, * to allow for explicit unsetting in hierarchies. */ public static void setForcedRoute(HttpParams params, HttpRoute route) { if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } params.setParameter(FORCED_ROUTE, route); } /** * Obtains the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS} * parameter value. * There is no special value that would automatically be mapped to * <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4, * :: for IPv6) to override a specific local address in a hierarchy. * * @param params the parameters in which to look up * * @return the local address set in the argument parameters, or * <code>null</code> if not set */ public static InetAddress getLocalAddress(HttpParams params) { if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } InetAddress local = (InetAddress) params.getParameter(LOCAL_ADDRESS); // no explicit unsetting return local; } /** * Sets the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS} * parameter value. * * @param params the parameters in which to set the value * @param local the value to set, may be <code>null</code> */ public static void setLocalAddress(HttpParams params, InetAddress local) { if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } params.setParameter(LOCAL_ADDRESS, local); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.util.concurrent.TimeUnit; /** * Encapsulates a request for a {@link ManagedClientConnection}. * * @since 4.0 */ public interface ClientConnectionRequest { /** * Obtains a connection within a given time. * This method will block until a connection becomes available, * the timeout expires, or the connection manager is * {@link ClientConnectionManager#shutdown() shut down}. * Timeouts are handled with millisecond precision. * * If {@link #abortRequest()} is called while this is blocking or * before this began, an {@link InterruptedException} will * be thrown. * * @param timeout the timeout, 0 or negative for no timeout * @param tunit the unit for the <code>timeout</code>, * may be <code>null</code> only if there is no timeout * * @return a connection that can be used to communicate * along the given route * * @throws ConnectionPoolTimeoutException * in case of a timeout * @throws InterruptedException * if the calling thread is interrupted while waiting */ ManagedClientConnection getConnection(long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException; /** * Aborts the call to {@link #getConnection(long, TimeUnit)}, * causing it to throw an {@link InterruptedException}. */ void abortRequest(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.routing; import java.net.InetAddress; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.util.LangUtils; /** * Helps tracking the steps in establishing a route. * * @since 4.0 */ @NotThreadSafe public final class RouteTracker implements RouteInfo, Cloneable { /** The target host to connect to. */ private final HttpHost targetHost; /** * The local address to connect from. * <code>null</code> indicates that the default should be used. */ private final InetAddress localAddress; // the attributes above are fixed at construction time // now follow attributes that indicate the established route /** Whether the first hop of the route is established. */ private boolean connected; /** The proxy chain, if any. */ private HttpHost[] proxyChain; /** Whether the the route is tunnelled end-to-end through proxies. */ private TunnelType tunnelled; /** Whether the route is layered over a tunnel. */ private LayerType layered; /** Whether the route is secure. */ private boolean secure; /** * Creates a new route tracker. * The target and origin need to be specified at creation time. * * @param target the host to which to route * @param local the local address to route from, or * <code>null</code> for the default */ public RouteTracker(HttpHost target, InetAddress local) { if (target == null) { throw new IllegalArgumentException("Target host may not be null."); } this.targetHost = target; this.localAddress = local; this.tunnelled = TunnelType.PLAIN; this.layered = LayerType.PLAIN; } /** * Creates a new tracker for the given route. * Only target and origin are taken from the route, * everything else remains to be tracked. * * @param route the route to track */ public RouteTracker(HttpRoute route) { this(route.getTargetHost(), route.getLocalAddress()); } /** * Tracks connecting to the target. * * @param secure <code>true</code> if the route is secure, * <code>false</code> otherwise */ public final void connectTarget(boolean secure) { if (this.connected) { throw new IllegalStateException("Already connected."); } this.connected = true; this.secure = secure; } /** * Tracks connecting to the first proxy. * * @param proxy the proxy connected to * @param secure <code>true</code> if the route is secure, * <code>false</code> otherwise */ public final void connectProxy(HttpHost proxy, boolean secure) { if (proxy == null) { throw new IllegalArgumentException("Proxy host may not be null."); } if (this.connected) { throw new IllegalStateException("Already connected."); } this.connected = true; this.proxyChain = new HttpHost[]{ proxy }; this.secure = secure; } /** * Tracks tunnelling to the target. * * @param secure <code>true</code> if the route is secure, * <code>false</code> otherwise */ public final void tunnelTarget(boolean secure) { if (!this.connected) { throw new IllegalStateException("No tunnel unless connected."); } if (this.proxyChain == null) { throw new IllegalStateException("No tunnel without proxy."); } this.tunnelled = TunnelType.TUNNELLED; this.secure = secure; } /** * Tracks tunnelling to a proxy in a proxy chain. * This will extend the tracked proxy chain, but it does not mark * the route as tunnelled. Only end-to-end tunnels are considered there. * * @param proxy the proxy tunnelled to * @param secure <code>true</code> if the route is secure, * <code>false</code> otherwise */ public final void tunnelProxy(HttpHost proxy, boolean secure) { if (proxy == null) { throw new IllegalArgumentException("Proxy host may not be null."); } if (!this.connected) { throw new IllegalStateException("No tunnel unless connected."); } if (this.proxyChain == null) { throw new IllegalStateException("No proxy tunnel without proxy."); } // prepare an extended proxy chain HttpHost[] proxies = new HttpHost[this.proxyChain.length+1]; System.arraycopy(this.proxyChain, 0, proxies, 0, this.proxyChain.length); proxies[proxies.length-1] = proxy; this.proxyChain = proxies; this.secure = secure; } /** * Tracks layering a protocol. * * @param secure <code>true</code> if the route is secure, * <code>false</code> otherwise */ public final void layerProtocol(boolean secure) { // it is possible to layer a protocol over a direct connection, // although this case is probably not considered elsewhere if (!this.connected) { throw new IllegalStateException ("No layered protocol unless connected."); } this.layered = LayerType.LAYERED; this.secure = secure; } public final HttpHost getTargetHost() { return this.targetHost; } public final InetAddress getLocalAddress() { return this.localAddress; } public final int getHopCount() { int hops = 0; if (this.connected) { if (proxyChain == null) hops = 1; else hops = proxyChain.length + 1; } return hops; } public final HttpHost getHopTarget(int hop) { if (hop < 0) throw new IllegalArgumentException ("Hop index must not be negative: " + hop); final int hopcount = getHopCount(); if (hop >= hopcount) { throw new IllegalArgumentException ("Hop index " + hop + " exceeds tracked route length " + hopcount +"."); } HttpHost result = null; if (hop < hopcount-1) result = this.proxyChain[hop]; else result = this.targetHost; return result; } public final HttpHost getProxyHost() { return (this.proxyChain == null) ? null : this.proxyChain[0]; } public final boolean isConnected() { return this.connected; } public final TunnelType getTunnelType() { return this.tunnelled; } public final boolean isTunnelled() { return (this.tunnelled == TunnelType.TUNNELLED); } public final LayerType getLayerType() { return this.layered; } public final boolean isLayered() { return (this.layered == LayerType.LAYERED); } public final boolean isSecure() { return this.secure; } /** * Obtains the tracked route. * If a route has been tracked, it is {@link #isConnected connected}. * If not connected, nothing has been tracked so far. * * @return the tracked route, or * <code>null</code> if nothing has been tracked so far */ public final HttpRoute toRoute() { return !this.connected ? null : new HttpRoute(this.targetHost, this.localAddress, this.proxyChain, this.secure, this.tunnelled, this.layered); } /** * Compares this tracked route to another. * * @param o the object to compare with * * @return <code>true</code> if the argument is the same tracked route, * <code>false</code> */ @Override public final boolean equals(Object o) { if (o == this) return true; if (!(o instanceof RouteTracker)) return false; RouteTracker that = (RouteTracker) o; return // Do the cheapest checks first (this.connected == that.connected) && (this.secure == that.secure) && (this.tunnelled == that.tunnelled) && (this.layered == that.layered) && LangUtils.equals(this.targetHost, that.targetHost) && LangUtils.equals(this.localAddress, that.localAddress) && LangUtils.equals(this.proxyChain, that.proxyChain); } /** * Generates a hash code for this tracked route. * Route trackers are modifiable and should therefore not be used * as lookup keys. Use {@link #toRoute toRoute} to obtain an * unmodifiable representation of the tracked route. * * @return the hash code */ @Override public final int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.targetHost); hash = LangUtils.hashCode(hash, this.localAddress); if (this.proxyChain != null) { for (int i = 0; i < this.proxyChain.length; i++) { hash = LangUtils.hashCode(hash, this.proxyChain[i]); } } hash = LangUtils.hashCode(hash, this.connected); hash = LangUtils.hashCode(hash, this.secure); hash = LangUtils.hashCode(hash, this.tunnelled); hash = LangUtils.hashCode(hash, this.layered); return hash; } /** * Obtains a description of the tracked route. * * @return a human-readable representation of the tracked route */ @Override public final String toString() { StringBuilder cab = new StringBuilder(50 + getHopCount()*30); cab.append("RouteTracker["); if (this.localAddress != null) { cab.append(this.localAddress); cab.append("->"); } cab.append('{'); if (this.connected) cab.append('c'); if (this.tunnelled == TunnelType.TUNNELLED) cab.append('t'); if (this.layered == LayerType.LAYERED) cab.append('l'); if (this.secure) cab.append('s'); cab.append("}->"); if (this.proxyChain != null) { for (int i=0; i<this.proxyChain.length; i++) { cab.append(this.proxyChain[i]); cab.append("->"); } } cab.append(this.targetHost); cab.append(']'); return cab.toString(); } // default implementation of clone() is sufficient @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.routing; import org.apache.ogt.http.annotation.Immutable; /** * Basic implementation of an {@link HttpRouteDirector HttpRouteDirector}. * This implementation is stateless and therefore thread-safe. * * @since 4.0 */ @Immutable public class BasicRouteDirector implements HttpRouteDirector { /** * Provides the next step. * * @param plan the planned route * @param fact the currently established route, or * <code>null</code> if nothing is established * * @return one of the constants defined in this class, indicating * either the next step to perform, or success, or failure. * 0 is for success, a negative value for failure. */ public int nextStep(RouteInfo plan, RouteInfo fact) { if (plan == null) { throw new IllegalArgumentException ("Planned route may not be null."); } int step = UNREACHABLE; if ((fact == null) || (fact.getHopCount() < 1)) step = firstStep(plan); else if (plan.getHopCount() > 1) step = proxiedStep(plan, fact); else step = directStep(plan, fact); return step; } // nextStep /** * Determines the first step to establish a route. * * @param plan the planned route * * @return the first step */ protected int firstStep(RouteInfo plan) { return (plan.getHopCount() > 1) ? CONNECT_PROXY : CONNECT_TARGET; } /** * Determines the next step to establish a direct connection. * * @param plan the planned route * @param fact the currently established route * * @return one of the constants defined in this class, indicating * either the next step to perform, or success, or failure */ protected int directStep(RouteInfo plan, RouteInfo fact) { if (fact.getHopCount() > 1) return UNREACHABLE; if (!plan.getTargetHost().equals(fact.getTargetHost())) return UNREACHABLE; // If the security is too low, we could now suggest to layer // a secure protocol on the direct connection. Layering on direct // connections has not been supported in HttpClient 3.x, we don't // consider it here until there is a real-life use case for it. // Should we tolerate if security is better than planned? // (plan.isSecure() && !fact.isSecure()) if (plan.isSecure() != fact.isSecure()) return UNREACHABLE; // Local address has to match only if the plan specifies one. if ((plan.getLocalAddress() != null) && !plan.getLocalAddress().equals(fact.getLocalAddress()) ) return UNREACHABLE; return COMPLETE; } /** * Determines the next step to establish a connection via proxy. * * @param plan the planned route * @param fact the currently established route * * @return one of the constants defined in this class, indicating * either the next step to perform, or success, or failure */ protected int proxiedStep(RouteInfo plan, RouteInfo fact) { if (fact.getHopCount() <= 1) return UNREACHABLE; if (!plan.getTargetHost().equals(fact.getTargetHost())) return UNREACHABLE; final int phc = plan.getHopCount(); final int fhc = fact.getHopCount(); if (phc < fhc) return UNREACHABLE; for (int i=0; i<fhc-1; i++) { if (!plan.getHopTarget(i).equals(fact.getHopTarget(i))) return UNREACHABLE; } // now we know that the target matches and proxies so far are the same if (phc > fhc) return TUNNEL_PROXY; // need to extend the proxy chain // proxy chain and target are the same, check tunnelling and layering if ((fact.isTunnelled() && !plan.isTunnelled()) || (fact.isLayered() && !plan.isLayered())) return UNREACHABLE; if (plan.isTunnelled() && !fact.isTunnelled()) return TUNNEL_TARGET; if (plan.isLayered() && !fact.isLayered()) return LAYER_PROTOCOL; // tunnel and layering are the same, remains to check the security // Should we tolerate if security is better than planned? // (plan.isSecure() && !fact.isSecure()) if (plan.isSecure() != fact.isSecure()) return UNREACHABLE; return COMPLETE; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.routing; import java.net.InetAddress; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.util.LangUtils; /** * The route for a request. * Instances of this class are unmodifiable and therefore suitable * for use as lookup keys. * * @since 4.0 */ @Immutable public final class HttpRoute implements RouteInfo, Cloneable { private static final HttpHost[] EMPTY_HTTP_HOST_ARRAY = new HttpHost[]{}; /** The target host to connect to. */ private final HttpHost targetHost; /** * The local address to connect from. * <code>null</code> indicates that the default should be used. */ private final InetAddress localAddress; /** The proxy servers, if any. Never null. */ private final HttpHost[] proxyChain; /** Whether the the route is tunnelled through the proxy. */ private final TunnelType tunnelled; /** Whether the route is layered. */ private final LayerType layered; /** Whether the route is (supposed to be) secure. */ private final boolean secure; /** * Internal, fully-specified constructor. * This constructor does <i>not</i> clone the proxy chain array, * nor test it for <code>null</code> elements. This conversion and * check is the responsibility of the public constructors. * The order of arguments here is different from the similar public * constructor, as required by Java. * * @param local the local address to route from, or * <code>null</code> for the default * @param target the host to which to route * @param proxies the proxy chain to use, or * <code>null</code> for a direct route * @param secure <code>true</code> if the route is (to be) secure, * <code>false</code> otherwise * @param tunnelled the tunnel type of this route, or * <code>null</code> for PLAIN * @param layered the layering type of this route, or * <code>null</code> for PLAIN */ private HttpRoute(InetAddress local, HttpHost target, HttpHost[] proxies, boolean secure, TunnelType tunnelled, LayerType layered) { if (target == null) { throw new IllegalArgumentException ("Target host may not be null."); } if (proxies == null) { throw new IllegalArgumentException ("Proxies may not be null."); } if ((tunnelled == TunnelType.TUNNELLED) && (proxies.length == 0)) { throw new IllegalArgumentException ("Proxy required if tunnelled."); } // tunnelled is already checked above, that is in line with the default if (tunnelled == null) tunnelled = TunnelType.PLAIN; if (layered == null) layered = LayerType.PLAIN; this.targetHost = target; this.localAddress = local; this.proxyChain = proxies; this.secure = secure; this.tunnelled = tunnelled; this.layered = layered; } /** * Creates a new route with all attributes specified explicitly. * * @param target the host to which to route * @param local the local address to route from, or * <code>null</code> for the default * @param proxies the proxy chain to use, or * <code>null</code> for a direct route * @param secure <code>true</code> if the route is (to be) secure, * <code>false</code> otherwise * @param tunnelled the tunnel type of this route * @param layered the layering type of this route */ public HttpRoute(HttpHost target, InetAddress local, HttpHost[] proxies, boolean secure, TunnelType tunnelled, LayerType layered) { this(local, target, toChain(proxies), secure, tunnelled, layered); } /** * Creates a new route with at most one proxy. * * @param target the host to which to route * @param local the local address to route from, or * <code>null</code> for the default * @param proxy the proxy to use, or * <code>null</code> for a direct route * @param secure <code>true</code> if the route is (to be) secure, * <code>false</code> otherwise * @param tunnelled <code>true</code> if the route is (to be) tunnelled * via the proxy, * <code>false</code> otherwise * @param layered <code>true</code> if the route includes a * layered protocol, * <code>false</code> otherwise */ public HttpRoute(HttpHost target, InetAddress local, HttpHost proxy, boolean secure, TunnelType tunnelled, LayerType layered) { this(local, target, toChain(proxy), secure, tunnelled, layered); } /** * Creates a new direct route. * That is a route without a proxy. * * @param target the host to which to route * @param local the local address to route from, or * <code>null</code> for the default * @param secure <code>true</code> if the route is (to be) secure, * <code>false</code> otherwise */ public HttpRoute(HttpHost target, InetAddress local, boolean secure) { this(local, target, EMPTY_HTTP_HOST_ARRAY, secure, TunnelType.PLAIN, LayerType.PLAIN); } /** * Creates a new direct insecure route. * * @param target the host to which to route */ public HttpRoute(HttpHost target) { this(null, target, EMPTY_HTTP_HOST_ARRAY, false, TunnelType.PLAIN, LayerType.PLAIN); } /** * Creates a new route through a proxy. * When using this constructor, the <code>proxy</code> MUST be given. * For convenience, it is assumed that a secure connection will be * layered over a tunnel through the proxy. * * @param target the host to which to route * @param local the local address to route from, or * <code>null</code> for the default * @param proxy the proxy to use * @param secure <code>true</code> if the route is (to be) secure, * <code>false</code> otherwise */ public HttpRoute(HttpHost target, InetAddress local, HttpHost proxy, boolean secure) { this(local, target, toChain(proxy), secure, secure ? TunnelType.TUNNELLED : TunnelType.PLAIN, secure ? LayerType.LAYERED : LayerType.PLAIN); if (proxy == null) { throw new IllegalArgumentException ("Proxy host may not be null."); } } /** * Helper to convert a proxy to a proxy chain. * * @param proxy the only proxy in the chain, or <code>null</code> * * @return a proxy chain array, may be empty (never null) */ private static HttpHost[] toChain(HttpHost proxy) { if (proxy == null) return EMPTY_HTTP_HOST_ARRAY; return new HttpHost[]{ proxy }; } /** * Helper to duplicate and check a proxy chain. * <code>null</code> is converted to an empty proxy chain. * * @param proxies the proxy chain to duplicate, or <code>null</code> * * @return a new proxy chain array, may be empty (never null) */ private static HttpHost[] toChain(HttpHost[] proxies) { if ((proxies == null) || (proxies.length < 1)) return EMPTY_HTTP_HOST_ARRAY; for (HttpHost proxy : proxies) { if (proxy == null) throw new IllegalArgumentException ("Proxy chain may not contain null elements."); } // copy the proxy chain, the traditional way HttpHost[] result = new HttpHost[proxies.length]; System.arraycopy(proxies, 0, result, 0, proxies.length); return result; } // non-JavaDoc, see interface RouteInfo public final HttpHost getTargetHost() { return this.targetHost; } // non-JavaDoc, see interface RouteInfo public final InetAddress getLocalAddress() { return this.localAddress; } public final int getHopCount() { return proxyChain.length+1; } public final HttpHost getHopTarget(int hop) { if (hop < 0) throw new IllegalArgumentException ("Hop index must not be negative: " + hop); final int hopcount = getHopCount(); if (hop >= hopcount) throw new IllegalArgumentException ("Hop index " + hop + " exceeds route length " + hopcount); HttpHost result = null; if (hop < hopcount-1) result = this.proxyChain[hop]; else result = this.targetHost; return result; } public final HttpHost getProxyHost() { return (this.proxyChain.length == 0) ? null : this.proxyChain[0]; } public final TunnelType getTunnelType() { return this.tunnelled; } public final boolean isTunnelled() { return (this.tunnelled == TunnelType.TUNNELLED); } public final LayerType getLayerType() { return this.layered; } public final boolean isLayered() { return (this.layered == LayerType.LAYERED); } public final boolean isSecure() { return this.secure; } /** * Compares this route to another. * * @param obj the object to compare with * * @return <code>true</code> if the argument is the same route, * <code>false</code> */ @Override public final boolean equals(Object obj) { if (this == obj) return true; if (obj instanceof HttpRoute) { HttpRoute that = (HttpRoute) obj; return // Do the cheapest tests first (this.secure == that.secure) && (this.tunnelled == that.tunnelled) && (this.layered == that.layered) && LangUtils.equals(this.targetHost, that.targetHost) && LangUtils.equals(this.localAddress, that.localAddress) && LangUtils.equals(this.proxyChain, that.proxyChain); } else { return false; } } /** * Generates a hash code for this route. * * @return the hash code */ @Override public final int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.targetHost); hash = LangUtils.hashCode(hash, this.localAddress); for (int i = 0; i < this.proxyChain.length; i++) { hash = LangUtils.hashCode(hash, this.proxyChain[i]); } hash = LangUtils.hashCode(hash, this.secure); hash = LangUtils.hashCode(hash, this.tunnelled); hash = LangUtils.hashCode(hash, this.layered); return hash; } /** * Obtains a description of this route. * * @return a human-readable representation of this route */ @Override public final String toString() { StringBuilder cab = new StringBuilder(50 + getHopCount()*30); cab.append("HttpRoute["); if (this.localAddress != null) { cab.append(this.localAddress); cab.append("->"); } cab.append('{'); if (this.tunnelled == TunnelType.TUNNELLED) cab.append('t'); if (this.layered == LayerType.LAYERED) cab.append('l'); if (this.secure) cab.append('s'); cab.append("}->"); for (HttpHost aProxyChain : this.proxyChain) { cab.append(aProxyChain); cab.append("->"); } cab.append(this.targetHost); cab.append(']'); return cab.toString(); } // default implementation of clone() is sufficient @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.routing; /** * Provides directions on establishing a route. * Implementations of this interface compare a planned route with * a tracked route and indicate the next step required. * * @since 4.0 */ public interface HttpRouteDirector { /** Indicates that the route can not be established at all. */ public final static int UNREACHABLE = -1; /** Indicates that the route is complete. */ public final static int COMPLETE = 0; /** Step: open connection to target. */ public final static int CONNECT_TARGET = 1; /** Step: open connection to proxy. */ public final static int CONNECT_PROXY = 2; /** Step: tunnel through proxy to target. */ public final static int TUNNEL_TARGET = 3; /** Step: tunnel through proxy to other proxy. */ public final static int TUNNEL_PROXY = 4; /** Step: layer protocol (over tunnel). */ public final static int LAYER_PROTOCOL = 5; /** * Provides the next step. * * @param plan the planned route * @param fact the currently established route, or * <code>null</code> if nothing is established * * @return one of the constants defined in this interface, indicating * either the next step to perform, or success, or failure. * 0 is for success, a negative value for failure. */ public int nextStep(RouteInfo plan, RouteInfo fact); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.routing; import java.net.InetAddress; import org.apache.ogt.http.HttpHost; /** * Read-only interface for route information. * * @since 4.0 */ public interface RouteInfo { /** * The tunnelling type of a route. * Plain routes are established by connecting to the target or * the first proxy. * Tunnelled routes are established by connecting to the first proxy * and tunnelling through all proxies to the target. * Routes without a proxy cannot be tunnelled. */ public enum TunnelType { PLAIN, TUNNELLED } /** * The layering type of a route. * Plain routes are established by connecting or tunnelling. * Layered routes are established by layering a protocol such as TLS/SSL * over an existing connection. * Protocols can only be layered over a tunnel to the target, or * or over a direct connection without proxies. * <br/> * Layering a protocol * over a direct connection makes little sense, since the connection * could be established with the new protocol in the first place. * But we don't want to exclude that use case. */ public enum LayerType { PLAIN, LAYERED } /** * Obtains the target host. * * @return the target host */ HttpHost getTargetHost(); /** * Obtains the local address to connect from. * * @return the local address, * or <code>null</code> */ InetAddress getLocalAddress(); /** * Obtains the number of hops in this route. * A direct route has one hop. A route through a proxy has two hops. * A route through a chain of <i>n</i> proxies has <i>n+1</i> hops. * * @return the number of hops in this route */ int getHopCount(); /** * Obtains the target of a hop in this route. * The target of the last hop is the {@link #getTargetHost target host}, * the target of previous hops is the respective proxy in the chain. * For a route through exactly one proxy, target of hop 0 is the proxy * and target of hop 1 is the target host. * * @param hop index of the hop for which to get the target, * 0 for first * * @return the target of the given hop * * @throws IllegalArgumentException * if the argument is negative or not less than * {@link #getHopCount getHopCount()} */ HttpHost getHopTarget(int hop); /** * Obtains the first proxy host. * * @return the first proxy in the proxy chain, or * <code>null</code> if this route is direct */ HttpHost getProxyHost(); /** * Obtains the tunnel type of this route. * If there is a proxy chain, only end-to-end tunnels are considered. * * @return the tunnelling type */ TunnelType getTunnelType(); /** * Checks whether this route is tunnelled through a proxy. * If there is a proxy chain, only end-to-end tunnels are considered. * * @return <code>true</code> if tunnelled end-to-end through at least * one proxy, * <code>false</code> otherwise */ boolean isTunnelled(); /** * Obtains the layering type of this route. * In the presence of proxies, only layering over an end-to-end tunnel * is considered. * * @return the layering type */ LayerType getLayerType(); /** * Checks whether this route includes a layered protocol. * In the presence of proxies, only layering over an end-to-end tunnel * is considered. * * @return <code>true</code> if layered, * <code>false</code> otherwise */ boolean isLayered(); /** * Checks whether this route is secure. * * @return <code>true</code> if secure, * <code>false</code> otherwise */ boolean isSecure(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.routing; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.protocol.HttpContext; /** * Encapsulates logic to compute a {@link HttpRoute} to a target host. * Implementations may for example be based on parameters, or on the * standard Java system properties. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface HttpRoutePlanner { /** * Determines the route for a request. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param context the context to use for the subsequent execution. * Implementations may accept <code>null</code>. * * @return the route that the request should take * * @throws HttpException in case of a problem */ public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException; }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.InputStream; import java.io.IOException; import org.apache.ogt.http.annotation.NotThreadSafe; /** * A stream wrapper that triggers actions on {@link #close close()} and EOF. * Primarily used to auto-release an underlying * {@link ManagedClientConnection connection} * when the response body is consumed or no longer needed. * <p> * This class is based on <code>AutoCloseInputStream</code> in HttpClient 3.1, * but has notable differences. It does not allow mark/reset, distinguishes * different kinds of event, and does not always close the underlying stream * on EOF. That decision is left to the {@link EofSensorWatcher watcher}. * * @see EofSensorWatcher * * @since 4.0 */ // don't use FilterInputStream as the base class, we'd have to // override markSupported(), mark(), and reset() to disable them @NotThreadSafe public class EofSensorInputStream extends InputStream implements ConnectionReleaseTrigger { /** * The wrapped input stream, while accessible. * The value changes to <code>null</code> when the wrapped stream * becomes inaccessible. */ protected InputStream wrappedStream; /** * Indicates whether this stream itself is closed. * If it isn't, but {@link #wrappedStream wrappedStream} * is <code>null</code>, we're running in EOF mode. * All read operations will indicate EOF without accessing * the underlying stream. After closing this stream, read * operations will trigger an {@link IOException IOException}. * * @see #isReadAllowed isReadAllowed */ private boolean selfClosed; /** The watcher to be notified, if any. */ private final EofSensorWatcher eofWatcher; /** * Creates a new EOF sensor. * If no watcher is passed, the underlying stream will simply be * closed when EOF is detected or {@link #close close} is called. * Otherwise, the watcher decides whether the underlying stream * should be closed before detaching from it. * * @param in the wrapped stream * @param watcher the watcher for events, or <code>null</code> for * auto-close behavior without notification */ public EofSensorInputStream(final InputStream in, final EofSensorWatcher watcher) { if (in == null) { throw new IllegalArgumentException ("Wrapped stream may not be null."); } wrappedStream = in; selfClosed = false; eofWatcher = watcher; } /** * Checks whether the underlying stream can be read from. * * @return <code>true</code> if the underlying stream is accessible, * <code>false</code> if this stream is in EOF mode and * detached from the underlying stream * * @throws IOException if this stream is already closed */ protected boolean isReadAllowed() throws IOException { if (selfClosed) { throw new IOException("Attempted read on closed stream."); } return (wrappedStream != null); } @Override public int read() throws IOException { int l = -1; if (isReadAllowed()) { try { l = wrappedStream.read(); checkEOF(l); } catch (IOException ex) { checkAbort(); throw ex; } } return l; } @Override public int read(byte[] b, int off, int len) throws IOException { int l = -1; if (isReadAllowed()) { try { l = wrappedStream.read(b, off, len); checkEOF(l); } catch (IOException ex) { checkAbort(); throw ex; } } return l; } @Override public int read(byte[] b) throws IOException { int l = -1; if (isReadAllowed()) { try { l = wrappedStream.read(b); checkEOF(l); } catch (IOException ex) { checkAbort(); throw ex; } } return l; } @Override public int available() throws IOException { int a = 0; // not -1 if (isReadAllowed()) { try { a = wrappedStream.available(); // no checkEOF() here, available() can't trigger EOF } catch (IOException ex) { checkAbort(); throw ex; } } return a; } @Override public void close() throws IOException { // tolerate multiple calls to close() selfClosed = true; checkClose(); } /** * Detects EOF and notifies the watcher. * This method should only be called while the underlying stream is * still accessible. Use {@link #isReadAllowed isReadAllowed} to * check that condition. * <br/> * If EOF is detected, the watcher will be notified and this stream * is detached from the underlying stream. This prevents multiple * notifications from this stream. * * @param eof the result of the calling read operation. * A negative value indicates that EOF is reached. * * @throws IOException * in case of an IO problem on closing the underlying stream */ protected void checkEOF(int eof) throws IOException { if ((wrappedStream != null) && (eof < 0)) { try { boolean scws = true; // should close wrapped stream? if (eofWatcher != null) scws = eofWatcher.eofDetected(wrappedStream); if (scws) wrappedStream.close(); } finally { wrappedStream = null; } } } /** * Detects stream close and notifies the watcher. * There's not much to detect since this is called by {@link #close close}. * The watcher will only be notified if this stream is closed * for the first time and before EOF has been detected. * This stream will be detached from the underlying stream to prevent * multiple notifications to the watcher. * * @throws IOException * in case of an IO problem on closing the underlying stream */ protected void checkClose() throws IOException { if (wrappedStream != null) { try { boolean scws = true; // should close wrapped stream? if (eofWatcher != null) scws = eofWatcher.streamClosed(wrappedStream); if (scws) wrappedStream.close(); } finally { wrappedStream = null; } } } /** * Detects stream abort and notifies the watcher. * There's not much to detect since this is called by * {@link #abortConnection abortConnection}. * The watcher will only be notified if this stream is aborted * for the first time and before EOF has been detected or the * stream has been {@link #close closed} gracefully. * This stream will be detached from the underlying stream to prevent * multiple notifications to the watcher. * * @throws IOException * in case of an IO problem on closing the underlying stream */ protected void checkAbort() throws IOException { if (wrappedStream != null) { try { boolean scws = true; // should close wrapped stream? if (eofWatcher != null) scws = eofWatcher.streamAbort(wrappedStream); if (scws) wrappedStream.close(); } finally { wrappedStream = null; } } } /** * Same as {@link #close close()}. */ public void releaseConnection() throws IOException { close(); } /** * Aborts this stream. * This is a special version of {@link #close close()} which prevents * re-use of the underlying connection, if any. Calling this method * indicates that there should be no attempt to read until the end of * the stream. */ public void abortConnection() throws IOException { // tolerate multiple calls selfClosed = true; checkAbort(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Arrays; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.conn.scheme.SchemeSocketFactory; import org.apache.ogt.http.conn.scheme.SocketFactory; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; /** * Socket factory that implements a simple multi-home fail-over on connect failure, * provided the same hostname resolves to multiple {@link InetAddress}es. Please note * the {@link #connectSocket(Socket, String, int, InetAddress, int, HttpParams)} * method cannot be reliably interrupted by closing the socket returned by the * {@link #createSocket()} method. * * @since 4.0 * * @deprecated Do not use. For multihome support socket factories must implement * {@link SchemeSocketFactory} interface. */ @Deprecated @Immutable public final class MultihomePlainSocketFactory implements SocketFactory { /** * The factory singleton. */ private static final MultihomePlainSocketFactory DEFAULT_FACTORY = new MultihomePlainSocketFactory(); /** * Gets the singleton instance of this class. * @return the one and only plain socket factory */ public static MultihomePlainSocketFactory getSocketFactory() { return DEFAULT_FACTORY; } /** * Restricted default constructor. */ private MultihomePlainSocketFactory() { super(); } // non-javadoc, see interface org.apache.ogt.http.conn.SocketFactory public Socket createSocket() { return new Socket(); } /** * Attempts to connects the socket to any of the {@link InetAddress}es the * given host name resolves to. If connection to all addresses fail, the * last I/O exception is propagated to the caller. * * @param sock socket to connect to any of the given addresses * @param host Host name to connect to * @param port the port to connect to * @param localAddress local address * @param localPort local port * @param params HTTP parameters * * @throws IOException if an error occurs during the connection * @throws SocketTimeoutException if timeout expires before connecting */ public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } if (sock == null) sock = createSocket(); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) localPort = 0; // indicates "any" InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sock.bind(isa); } int timeout = HttpConnectionParams.getConnectionTimeout(params); InetAddress[] inetadrs = InetAddress.getAllByName(host); List<InetAddress> addresses = new ArrayList<InetAddress>(inetadrs.length); addresses.addAll(Arrays.asList(inetadrs)); Collections.shuffle(addresses); IOException lastEx = null; for (InetAddress remoteAddress: addresses) { try { sock.connect(new InetSocketAddress(remoteAddress, port), timeout); break; } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } catch (IOException ex) { // create new socket sock = new Socket(); // keep the last exception and retry lastEx = ex; } } if (lastEx != null) { throw lastEx; } return sock; } // connectSocket /** * Checks whether a socket connection is secure. * This factory creates plain socket connections * which are not considered secure. * * @param sock the connected socket * * @return <code>false</code> * * @throws IllegalArgumentException if the argument is invalid */ public final boolean isSecure(Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null."); } // This class check assumes that createSocket() calls the constructor // directly. If it was using javax.net.SocketFactory, we couldn't make // an assumption about the socket class here. if (sock.getClass() != Socket.class) { throw new IllegalArgumentException ("Socket not created by this factory."); } // This check is performed last since it calls a method implemented // by the argument object. getClass() is final in java.lang.Object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed."); } return false; } // isSecure }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.IOException; /** * Interface for releasing a connection. This can be implemented by various * "trigger" objects which are associated with a connection, for example * a {@link EofSensorInputStream stream} or an {@link BasicManagedEntity entity} * or the {@link ManagedClientConnection connection} itself. * <p> * The methods in this interface can safely be called multiple times. * The first invocation releases the connection, subsequent calls * are ignored. * * @since 4.0 */ public interface ConnectionReleaseTrigger { /** * Releases the connection with the option of keep-alive. This is a * "graceful" release and may cause IO operations for consuming the * remainder of a response entity. Use * {@link #abortConnection abortConnection} for a hard release. The * connection may be reused as specified by the duration. * * @throws IOException * in case of an IO problem. The connection will be released * anyway. */ void releaseConnection() throws IOException; /** * Releases the connection without the option of keep-alive. * This is a "hard" release that implies a shutdown of the connection. * Use {@link #releaseConnection()} for a graceful release. * * @throws IOException in case of an IO problem. * The connection will be released anyway. */ void abortConnection() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.util.concurrent.TimeUnit; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.conn.scheme.SchemeRegistry; /** * Management interface for {@link ManagedClientConnection client connections}. * The purpose of an HTTP connection manager is to serve as a factory for new * HTTP connections, manage persistent connections and synchronize access to * persistent connections making sure that only one thread of execution can * have access to a connection at a time. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface ClientConnectionManager { /** * Obtains the scheme registry used by this manager. * * @return the scheme registry, never <code>null</code> */ SchemeRegistry getSchemeRegistry(); /** * Returns a new {@link ClientConnectionRequest}, from which a * {@link ManagedClientConnection} can be obtained or the request can be * aborted. */ ClientConnectionRequest requestConnection(HttpRoute route, Object state); /** * Releases a connection for use by others. * You may optionally specify how long the connection is valid * to be reused. Values <= 0 are considered to be valid forever. * If the connection is not marked as reusable, the connection will * not be reused regardless of the valid duration. * * If the connection has been released before, * the call will be ignored. * * @param conn the connection to release * @param validDuration the duration of time this connection is valid for reuse * @param timeUnit the unit of time validDuration is measured in * * @see #closeExpiredConnections() */ void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit); /** * Closes idle connections in the pool. * Open connections in the pool that have not been used for the * timespan given by the argument will be closed. * Currently allocated connections are not subject to this method. * Times will be checked with milliseconds precision * * All expired connections will also be closed. * * @param idletime the idle time of connections to be closed * @param tunit the unit for the <code>idletime</code> * * @see #closeExpiredConnections() */ void closeIdleConnections(long idletime, TimeUnit tunit); /** * Closes all expired connections in the pool. * Open connections in the pool that have not been used for * the timespan defined when the connection was released will be closed. * Currently allocated connections are not subject to this method. * Times will be checked with milliseconds precision. */ void closeExpiredConnections(); /** * Shuts down this connection manager and releases allocated resources. * This includes closing all connections, whether they are currently * used or not. */ void shutdown(); }
Java
/* * $Revision $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.InputStream; import java.io.IOException; import org.apache.ogt.http.annotation.NotThreadSafe; /** * Basic implementation of {@link EofSensorWatcher}. The underlying connection * is released on close or EOF. * * @since 4.0 */ @NotThreadSafe public class BasicEofSensorWatcher implements EofSensorWatcher { /** The connection to auto-release. */ protected final ManagedClientConnection managedConn; /** Whether to keep the connection alive. */ protected final boolean attemptReuse; /** * Creates a new watcher for auto-releasing a connection. * * @param conn the connection to auto-release * @param reuse whether the connection should be re-used */ public BasicEofSensorWatcher(ManagedClientConnection conn, boolean reuse) { if (conn == null) throw new IllegalArgumentException ("Connection may not be null."); managedConn = conn; attemptReuse = reuse; } public boolean eofDetected(InputStream wrapped) throws IOException { try { if (attemptReuse) { // there may be some cleanup required, such as // reading trailers after the response body: wrapped.close(); managedConn.markReusable(); } } finally { managedConn.releaseConnection(); } return false; } public boolean streamClosed(InputStream wrapped) throws IOException { try { if (attemptReuse) { // this assumes that closing the stream will // consume the remainder of the response body: wrapped.close(); managedConn.markReusable(); } } finally { managedConn.releaseConnection(); } return false; } public boolean streamAbort(InputStream wrapped) throws IOException { managedConn.abortConnection(); return false; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.util; import java.util.regex.Pattern; import org.apache.ogt.http.annotation.Immutable; /** * A collection of utilities relating to InetAddresses. * * @since 4.0 */ @Immutable public class InetAddressUtils { private InetAddressUtils() { } private static final Pattern IPV4_PATTERN = Pattern.compile( "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); private static final Pattern IPV6_STD_PATTERN = Pattern.compile( "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile( "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"); public static boolean isIPv4Address(final String input) { return IPV4_PATTERN.matcher(input).matches(); } public static boolean isIPv6StdAddress(final String input) { return IPV6_STD_PATTERN.matcher(input).matches(); } public static boolean isIPv6HexCompressedAddress(final String input) { return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches(); } public static boolean isIPv6Address(final String input) { return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input); } }
Java
/* * $Revision $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.entity.HttpEntityWrapper; import org.apache.ogt.http.util.EntityUtils; /** * An entity that releases a {@link ManagedClientConnection connection}. * A {@link ManagedClientConnection} will * typically <i>not</i> return a managed entity, but you can replace * the unmanaged entity in the response with a managed one. * * @since 4.0 */ @NotThreadSafe public class BasicManagedEntity extends HttpEntityWrapper implements ConnectionReleaseTrigger, EofSensorWatcher { /** The connection to release. */ protected ManagedClientConnection managedConn; /** Whether to keep the connection alive. */ protected final boolean attemptReuse; /** * Creates a new managed entity that can release a connection. * * @param entity the entity of which to wrap the content. * Note that the argument entity can no longer be used * afterwards, since the content will be taken by this * managed entity. * @param conn the connection to release * @param reuse whether the connection should be re-used */ public BasicManagedEntity(HttpEntity entity, ManagedClientConnection conn, boolean reuse) { super(entity); if (conn == null) throw new IllegalArgumentException ("Connection may not be null."); this.managedConn = conn; this.attemptReuse = reuse; } @Override public boolean isRepeatable() { return false; } @Override public InputStream getContent() throws IOException { return new EofSensorInputStream(wrappedEntity.getContent(), this); } private void ensureConsumed() throws IOException { if (managedConn == null) return; try { if (attemptReuse) { // this will not trigger a callback from EofSensorInputStream EntityUtils.consume(wrappedEntity); managedConn.markReusable(); } } finally { releaseManagedConnection(); } } @Deprecated @Override public void consumeContent() throws IOException { ensureConsumed(); } @Override public void writeTo(final OutputStream outstream) throws IOException { super.writeTo(outstream); ensureConsumed(); } public void releaseConnection() throws IOException { ensureConsumed(); } public void abortConnection() throws IOException { if (managedConn != null) { try { managedConn.abortConnection(); } finally { managedConn = null; } } } public boolean eofDetected(InputStream wrapped) throws IOException { try { if (attemptReuse && (managedConn != null)) { // there may be some cleanup required, such as // reading trailers after the response body: wrapped.close(); managedConn.markReusable(); } } finally { releaseManagedConnection(); } return false; } public boolean streamClosed(InputStream wrapped) throws IOException { try { if (attemptReuse && (managedConn != null)) { // this assumes that closing the stream will // consume the remainder of the response body: wrapped.close(); managedConn.markReusable(); } } finally { releaseManagedConnection(); } return false; } public boolean streamAbort(InputStream wrapped) throws IOException { if (managedConn != null) { managedConn.abortConnection(); } return false; } /** * Releases the connection gracefully. * The connection attribute will be nullified. * Subsequent invocations are no-ops. * * @throws IOException in case of an IO problem. * The connection attribute will be nullified anyway. */ protected void releaseManagedConnection() throws IOException { if (managedConn != null) { try { managedConn.releaseConnection(); } finally { managedConn = null; } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import org.apache.ogt.http.annotation.Immutable; /** * A timeout while waiting for an available connection * from a connection manager. * * * @since 4.0 */ @Immutable public class ConnectionPoolTimeoutException extends ConnectTimeoutException { private static final long serialVersionUID = -7898874842020245128L; /** * Creates a ConnectTimeoutException with a <tt>null</tt> detail message. */ public ConnectionPoolTimeoutException() { super(); } /** * Creates a ConnectTimeoutException with the specified detail message. * * @param message The exception detail message */ public ConnectionPoolTimeoutException(String message) { super(message); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn; import java.io.InputStream; import java.io.IOException; /** * A watcher for {@link EofSensorInputStream}. Each stream will notify its * watcher at most once. * * @since 4.0 */ public interface EofSensorWatcher { /** * Indicates that EOF is detected. * * @param wrapped the underlying stream which has reached EOF * * @return <code>true</code> if <code>wrapped</code> should be closed, * <code>false</code> if it should be left alone * * @throws IOException * in case of an IO problem, for example if the watcher itself * closes the underlying stream. The caller will leave the * wrapped stream alone, as if <code>false</code> was returned. */ boolean eofDetected(InputStream wrapped) throws IOException; /** * Indicates that the {@link EofSensorInputStream stream} is closed. * This method will be called only if EOF was <i>not</i> detected * before closing. Otherwise, {@link #eofDetected eofDetected} is called. * * @param wrapped the underlying stream which has not reached EOF * * @return <code>true</code> if <code>wrapped</code> should be closed, * <code>false</code> if it should be left alone * * @throws IOException * in case of an IO problem, for example if the watcher itself * closes the underlying stream. The caller will leave the * wrapped stream alone, as if <code>false</code> was returned. */ boolean streamClosed(InputStream wrapped) throws IOException; /** * Indicates that the {@link EofSensorInputStream stream} is aborted. * This method will be called only if EOF was <i>not</i> detected * before aborting. Otherwise, {@link #eofDetected eofDetected} is called. * <p/> * This method will also be invoked when an input operation causes an * IOException to be thrown to make sure the input stream gets shut down. * * @param wrapped the underlying stream which has not reached EOF * * @return <code>true</code> if <code>wrapped</code> should be closed, * <code>false</code> if it should be left alone * * @throws IOException * in case of an IO problem, for example if the watcher itself * closes the underlying stream. The caller will leave the * wrapped stream alone, as if <code>false</code> was returned. */ boolean streamAbort(InputStream wrapped) throws IOException; }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The field or method to which this annotation is applied can only be accessed * when holding a particular lock, which may be a built-in (synchronization) lock, * or may be an explicit java.util.concurrent.Lock. * * The argument determines which lock guards the annotated field or method: * <ul> * <li> * <code>this</code> : The intrinsic lock of the object in whose class the field is defined. * </li> * <li> * <code>class-name.this</code> : For inner classes, it may be necessary to disambiguate 'this'; * the <em>class-name.this</em> designation allows you to specify which 'this' reference is intended * </li> * <li> * <code>itself</code> : For reference fields only; the object to which the field refers. * </li> * <li> * <code>field-name</code> : The lock object is referenced by the (instance or static) field * specified by <em>field-name</em>. * </li> * <li> * <code>class-name.field-name</code> : The lock object is reference by the static field specified * by <em>class-name.field-name</em>. * </li> * <li> * <code>method-name()</code> : The lock object is returned by calling the named nil-ary method. * </li> * <li> * <code>class-name.class</code> : The Class object for the specified class should be used as the lock object. * </li> * <p> * Based on code developed by Brian Goetz and Tim Peierls and concepts * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. */ @Documented @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME public @interface GuardedBy { String value(); }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The class to which this annotation is applied is not thread-safe. * This annotation primarily exists for clarifying the non-thread-safety of a class * that might otherwise be assumed to be thread-safe, despite the fact that it is a bad * idea to assume a class is thread-safe without good reason. * @see ThreadSafe * <p> * Based on code developed by Brian Goetz and Tim Peierls and concepts * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME public @interface NotThreadSafe { }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The class to which this annotation is applied is immutable. This means that * its state cannot be seen to change by callers, which implies that * <ul> * <li> all public fields are final, </li> * <li> all public final reference fields refer to other immutable objects, and </li> * <li> constructors and methods do not publish references to any internal state * which is potentially mutable by the implementation. </li> * </ul> * Immutable objects may still have internal mutable state for purposes of performance * optimization; some state variables may be lazily computed, so long as they are computed * from immutable state and that callers cannot tell the difference. * <p> * Immutable objects are inherently thread-safe; they may be passed between threads or * published without synchronization. * <p> * Based on code developed by Brian Goetz and Tim Peierls and concepts * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME public @interface Immutable { }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The class to which this annotation is applied is thread-safe. This means that * no sequences of accesses (reads and writes to public fields, calls to public methods) * may put the object into an invalid state, regardless of the interleaving of those actions * by the runtime, and without requiring any additional synchronization or coordination on the * part of the caller. * @see NotThreadSafe * <p> * Based on code developed by Brian Goetz and Tim Peierls and concepts * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME public @interface ThreadSafe { }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.Immutable; /** * Signals violation of HTTP specification caused by an invalid redirect * * * @since 4.0 */ @Immutable public class RedirectException extends ProtocolException { private static final long serialVersionUID = 4418824536372559326L; /** * Creates a new RedirectException with a <tt>null</tt> detail message. */ public RedirectException() { super(); } /** * Creates a new RedirectException with the specified detail message. * * @param message The exception detail message */ public RedirectException(String message) { super(message); } /** * Creates a new RedirectException with the specified detail message and cause. * * @param message the exception detail message * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt> * if the cause is unavailable, unknown, or not a <tt>Throwable</tt> */ public RedirectException(String message, Throwable cause) { super(message, cause); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.protocol.HttpContext; /** * A client-side request director. * The director decides which steps are necessary to execute a request. * It establishes connections and optionally processes redirects and * authentication challenges. The director may therefore generate and * send a sequence of requests in order to execute one initial request. * * @since 4.0 */ public interface RequestDirector { /** * Executes a request. * <br/><b>Note:</b> * For the time being, a new director is instantiated for each request. * This is the same behavior as for <code>HttpMethodDirector</code> * in HttpClient 3. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param context the context for executing the request * * @return the final response to the request. * This is never an intermediate response with status code 1xx. * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem * or if the connection was aborted */ HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.auth.AuthScheme; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.AuthState; import org.apache.ogt.http.auth.Credentials; import org.apache.ogt.http.client.AuthCache; import org.apache.ogt.http.client.CredentialsProvider; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; /** * Request interceptor that can preemptively authenticate against known hosts, * if there is a cached {@link AuthScheme} instance in the local * {@link AuthCache} associated with the given target or proxy host. * * @since 4.1 */ @Immutable public class RequestAuthCache implements HttpRequestInterceptor { private final Log log = LogFactory.getLog(getClass()); public RequestAuthCache() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE); if (authCache == null) { this.log.debug("Auth cache not set in the context"); return; } CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( ClientContext.CREDS_PROVIDER); if (credsProvider == null) { this.log.debug("Credentials provider not set in the context"); return; } HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (target != null && targetState != null && targetState.getAuthScheme() == null) { AuthScheme authScheme = authCache.get(target); if (authScheme != null) { doPreemptiveAuth(target, authScheme, targetState, credsProvider); } } HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST); AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE); if (proxy != null && proxyState != null && proxyState.getAuthScheme() == null) { AuthScheme authScheme = authCache.get(proxy); if (authScheme != null) { doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); } } } private void doPreemptiveAuth( final HttpHost host, final AuthScheme authScheme, final AuthState authState, final CredentialsProvider credsProvider) { String schemeName = authScheme.getSchemeName(); if (this.log.isDebugEnabled()) { this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host); } AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, schemeName); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(authScheme); authState.setCredentials(creds); } else { this.log.debug("No credentials for preemptive authentication"); } } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import java.util.Locale; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.client.entity.DeflateDecompressingEntity; import org.apache.ogt.http.client.entity.GzipDecompressingEntity; import org.apache.ogt.http.protocol.HttpContext; /** * {@link HttpResponseInterceptor} responsible for processing Content-Encoding * responses. * <p> * Instances of this class are stateless and immutable, therefore threadsafe. * * @since 4.1 * */ @Immutable public class ResponseContentEncoding implements HttpResponseInterceptor { /** * Handles the following {@code Content-Encoding}s by * using the appropriate decompressor to wrap the response Entity: * <ul> * <li>gzip - see {@link GzipDecompressingEntity}</li> * <li>deflate - see {@link DeflateDecompressingEntity}</li> * <li>identity - no action needed</li> * </ul> * * @param response the response which contains the entity * @param context not currently used * * @throws HttpException if the {@code Content-Encoding} is none of the above */ public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); // It wasn't a 304 Not Modified response, 204 No Content or similar if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (HeaderElement codec : codecs) { String codecname = codec.getName().toLowerCase(Locale.US); if ("gzip".equals(codecname) || "x-gzip".equals(codecname)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } else if ("deflate".equals(codecname)) { response.setEntity(new DeflateDecompressingEntity(response.getEntity())); return; } else if ("identity".equals(codecname)) { /* Don't need to transform the content - no-op */ return; } else { throw new HttpException("Unsupported Content-Coding: " + codec.getName()); } } } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import java.util.Collection; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.client.params.ClientPNames; import org.apache.ogt.http.protocol.HttpContext; /** * Request interceptor that adds default request headers. * * @since 4.0 */ @Immutable public class RequestDefaultHeaders implements HttpRequestInterceptor { public RequestDefaultHeaders() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return; } // Add default headers @SuppressWarnings("unchecked") Collection<Header> defHeaders = (Collection<Header>) request.getParams().getParameter( ClientPNames.DEFAULT_HEADERS); if (defHeaders != null) { for (Header defHeader : defHeaders) { request.addHeader(defHeader); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.auth.AUTH; import org.apache.ogt.http.auth.AuthScheme; import org.apache.ogt.http.auth.AuthState; import org.apache.ogt.http.auth.AuthenticationException; import org.apache.ogt.http.auth.ContextAwareAuthScheme; import org.apache.ogt.http.auth.Credentials; import org.apache.ogt.http.protocol.HttpContext; /** * Generates authentication header for the target host, if required, * based on the actual state of the HTTP authentication context. * * @since 4.0 */ @Immutable public class RequestTargetAuthentication implements HttpRequestInterceptor { private final Log log = LogFactory.getLog(getClass()); public RequestTargetAuthentication() { super(); } @SuppressWarnings("deprecation") public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return; } if (request.containsHeader(AUTH.WWW_AUTH_RESP)) { return; } // Obtain authentication state AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); if (authState == null) { this.log.debug("Target auth state not set in the context"); return; } AuthScheme authScheme = authState.getAuthScheme(); if (authScheme == null) { return; } Credentials creds = authState.getCredentials(); if (creds == null) { this.log.debug("User credentials not available"); return; } if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) { try { Header header; if (authScheme instanceof ContextAwareAuthScheme) { header = ((ContextAwareAuthScheme) authScheme).authenticate( creds, request, context); } else { header = authScheme.authenticate(creds, request); } request.addHeader(header); } catch (AuthenticationException ex) { if (this.log.isErrorEnabled()) { this.log.error("Authentication error: " + ex.getMessage()); } } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.auth.AUTH; import org.apache.ogt.http.auth.AuthScheme; import org.apache.ogt.http.auth.AuthState; import org.apache.ogt.http.auth.AuthenticationException; import org.apache.ogt.http.auth.ContextAwareAuthScheme; import org.apache.ogt.http.auth.Credentials; import org.apache.ogt.http.conn.HttpRoutedConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; /** * Generates authentication header for the proxy host, if required, * based on the actual state of the HTTP authentication context. * * @since 4.0 */ @Immutable public class RequestProxyAuthentication implements HttpRequestInterceptor { private final Log log = LogFactory.getLog(getClass()); public RequestProxyAuthentication() { super(); } @SuppressWarnings("deprecation") public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) { return; } HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute( ExecutionContext.HTTP_CONNECTION); if (conn == null) { this.log.debug("HTTP connection not set in the context"); return; } HttpRoute route = conn.getRoute(); if (route.isTunnelled()) { return; } // Obtain authentication state AuthState authState = (AuthState) context.getAttribute( ClientContext.PROXY_AUTH_STATE); if (authState == null) { this.log.debug("Proxy auth state not set in the context"); return; } AuthScheme authScheme = authState.getAuthScheme(); if (authScheme == null) { return; } Credentials creds = authState.getCredentials(); if (creds == null) { this.log.debug("User credentials not available"); return; } if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) { try { Header header; if (authScheme instanceof ContextAwareAuthScheme) { header = ((ContextAwareAuthScheme) authScheme).authenticate( creds, request, context); } else { header = authScheme.authenticate(creds, request); } request.addHeader(header); } catch (AuthenticationException ex) { if (this.log.isErrorEnabled()) { this.log.error("Proxy authentication error: " + ex.getMessage()); } } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.conn.HttpRoutedConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.protocol.HttpContext; /** * This protocol interceptor is responsible for adding <code>Connection</code> * or <code>Proxy-Connection</code> headers to the outgoing requests, which * is essential for managing persistence of <code>HTTP/1.0</code> connections. * * @since 4.0 */ @Immutable public class RequestClientConnControl implements HttpRequestInterceptor { private final Log log = LogFactory.getLog(getClass()); private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection"; public RequestClientConnControl() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { request.setHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); return; } // Obtain the client connection (required) HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute( ExecutionContext.HTTP_CONNECTION); if (conn == null) { this.log.debug("HTTP connection not set in the context"); return; } HttpRoute route = conn.getRoute(); if (route.getHopCount() == 1 || route.isTunnelled()) { if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) { request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); } } if (route.getHopCount() == 2 && !route.isTunnelled()) { if (!request.containsHeader(PROXY_CONN_DIRECTIVE)) { request.addHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.client.CookieStore; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.client.params.HttpClientParams; import org.apache.ogt.http.conn.HttpRoutedConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.cookie.Cookie; import org.apache.ogt.http.cookie.CookieOrigin; import org.apache.ogt.http.cookie.CookieSpec; import org.apache.ogt.http.cookie.CookieSpecRegistry; import org.apache.ogt.http.cookie.SetCookie2; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; /** * Request interceptor that matches cookies available in the current * {@link CookieStore} to the request being executed and generates * corresponding <code>Cookie</code> request headers. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li> * <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#COOKIE_POLICY}</li> * </ul> * * @since 4.0 */ @Immutable public class RequestAddCookies implements HttpRequestInterceptor { private final Log log = LogFactory.getLog(getClass()); public RequestAddCookies() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return; } // Obtain cookie store CookieStore cookieStore = (CookieStore) context.getAttribute( ClientContext.COOKIE_STORE); if (cookieStore == null) { this.log.debug("Cookie store not specified in HTTP context"); return; } // Obtain the registry of cookie specs CookieSpecRegistry registry = (CookieSpecRegistry) context.getAttribute( ClientContext.COOKIESPEC_REGISTRY); if (registry == null) { this.log.debug("CookieSpec registry not specified in HTTP context"); return; } // Obtain the target host (required) HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); if (targetHost == null) { this.log.debug("Target host not set in the context"); return; } // Obtain the client connection (required) HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute( ExecutionContext.HTTP_CONNECTION); if (conn == null) { this.log.debug("HTTP connection not set in the context"); return; } String policy = HttpClientParams.getCookiePolicy(request.getParams()); if (this.log.isDebugEnabled()) { this.log.debug("CookieSpec selected: " + policy); } URI requestURI; if (request instanceof HttpUriRequest) { requestURI = ((HttpUriRequest) request).getURI(); } else { try { requestURI = new URI(request.getRequestLine().getUri()); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid request URI: " + request.getRequestLine().getUri(), ex); } } String hostName = targetHost.getHostName(); int port = targetHost.getPort(); if (port < 0) { HttpRoute route = conn.getRoute(); if (route.getHopCount() == 1) { port = conn.getRemotePort(); } else { // Target port will be selected by the proxy. // Use conventional ports for known schemes String scheme = targetHost.getSchemeName(); if (scheme.equalsIgnoreCase("http")) { port = 80; } else if (scheme.equalsIgnoreCase("https")) { port = 443; } else { port = 0; } } } CookieOrigin cookieOrigin = new CookieOrigin( hostName, port, requestURI.getPath(), conn.isSecure()); // Get an instance of the selected cookie policy CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams()); // Get all cookies available in the HTTP state List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies()); // Find cookies matching the given origin List<Cookie> matchedCookies = new ArrayList<Cookie>(); Date now = new Date(); for (Cookie cookie : cookies) { if (!cookie.isExpired(now)) { if (cookieSpec.match(cookie, cookieOrigin)) { if (this.log.isDebugEnabled()) { this.log.debug("Cookie " + cookie + " match " + cookieOrigin); } matchedCookies.add(cookie); } } else { if (this.log.isDebugEnabled()) { this.log.debug("Cookie " + cookie + " expired"); } } } // Generate Cookie request headers if (!matchedCookies.isEmpty()) { List<Header> headers = cookieSpec.formatCookies(matchedCookies); for (Header header : headers) { request.addHeader(header); } } int ver = cookieSpec.getVersion(); if (ver > 0) { boolean needVersionHeader = false; for (Cookie cookie : matchedCookies) { if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) { needVersionHeader = true; } } if (needVersionHeader) { Header header = cookieSpec.getVersionHeader(); if (header != null) { // Advertise cookie version support request.addHeader(header); } } } // Stick the CookieSpec and CookieOrigin instances to the HTTP context // so they could be obtained by the response interceptor context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec); context.setAttribute(ClientContext.COOKIE_ORIGIN, cookieOrigin); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.client.CookieStore; import org.apache.ogt.http.cookie.Cookie; import org.apache.ogt.http.cookie.CookieOrigin; import org.apache.ogt.http.cookie.CookieSpec; import org.apache.ogt.http.cookie.MalformedCookieException; import org.apache.ogt.http.cookie.SM; import org.apache.ogt.http.protocol.HttpContext; /** * Response interceptor that populates the current {@link CookieStore} with data * contained in response cookies received in the given the HTTP response. * * @since 4.0 */ @Immutable public class ResponseProcessCookies implements HttpResponseInterceptor { private final Log log = LogFactory.getLog(getClass()); public ResponseProcessCookies() { super(); } public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } // Obtain actual CookieSpec instance CookieSpec cookieSpec = (CookieSpec) context.getAttribute( ClientContext.COOKIE_SPEC); if (cookieSpec == null) { this.log.debug("Cookie spec not specified in HTTP context"); return; } // Obtain cookie store CookieStore cookieStore = (CookieStore) context.getAttribute( ClientContext.COOKIE_STORE); if (cookieStore == null) { this.log.debug("Cookie store not specified in HTTP context"); return; } // Obtain actual CookieOrigin instance CookieOrigin cookieOrigin = (CookieOrigin) context.getAttribute( ClientContext.COOKIE_ORIGIN); if (cookieOrigin == null) { this.log.debug("Cookie origin not specified in HTTP context"); return; } HeaderIterator it = response.headerIterator(SM.SET_COOKIE); processCookies(it, cookieSpec, cookieOrigin, cookieStore); // see if the cookie spec supports cookie versioning. if (cookieSpec.getVersion() > 0) { // process set-cookie2 headers. // Cookie2 will replace equivalent Cookie instances it = response.headerIterator(SM.SET_COOKIE2); processCookies(it, cookieSpec, cookieOrigin, cookieStore); } } private void processCookies( final HeaderIterator iterator, final CookieSpec cookieSpec, final CookieOrigin cookieOrigin, final CookieStore cookieStore) { while (iterator.hasNext()) { Header header = iterator.nextHeader(); try { List<Cookie> cookies = cookieSpec.parse(header, cookieOrigin); for (Cookie cookie : cookies) { try { cookieSpec.validate(cookie, cookieOrigin); cookieStore.addCookie(cookie); if (this.log.isDebugEnabled()) { this.log.debug("Cookie accepted: \"" + cookie + "\". "); } } catch (MalformedCookieException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Cookie rejected: \"" + cookie + "\". " + ex.getMessage()); } } } } catch (MalformedCookieException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Invalid cookie header: \"" + header + "\". " + ex.getMessage()); } } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; /** * {@link org.apache.ogt.http.protocol.HttpContext} attribute names for * client side HTTP protocol processing. * * @since 4.0 */ public interface ClientContext { /** * Attribute name of a {@link org.apache.ogt.http.conn.scheme.Scheme} * object that represents the actual protocol scheme registry. */ public static final String SCHEME_REGISTRY = "http.scheme-registry"; /** * Attribute name of a {@link org.apache.ogt.http.cookie.CookieSpecRegistry} * object that represents the actual cookie specification registry. */ public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry"; /** * Attribute name of a {@link org.apache.ogt.http.cookie.CookieSpec} * object that represents the actual cookie specification. */ public static final String COOKIE_SPEC = "http.cookie-spec"; /** * Attribute name of a {@link org.apache.ogt.http.cookie.CookieOrigin} * object that represents the actual details of the origin server. */ public static final String COOKIE_ORIGIN = "http.cookie-origin"; /** * Attribute name of a {@link org.apache.ogt.http.client.CookieStore} * object that represents the actual cookie store. */ public static final String COOKIE_STORE = "http.cookie-store"; /** * Attribute name of a {@link org.apache.ogt.http.auth.AuthSchemeRegistry} * object that represents the actual authentication scheme registry. */ public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry"; /** * Attribute name of a {@link org.apache.ogt.http.client.CredentialsProvider} * object that represents the actual credentials provider. */ public static final String CREDS_PROVIDER = "http.auth.credentials-provider"; /** * Attribute name of a {@link org.apache.ogt.http.client.AuthCache} object * that represents the auth scheme cache. */ public static final String AUTH_CACHE = "http.auth.auth-cache"; /** * Attribute name of a {@link org.apache.ogt.http.auth.AuthState} * object that represents the actual target authentication state. */ public static final String TARGET_AUTH_STATE = "http.auth.target-scope"; /** * Attribute name of a {@link org.apache.ogt.http.auth.AuthState} * object that represents the actual proxy authentication state. */ public static final String PROXY_AUTH_STATE = "http.auth.proxy-scope"; /** * @deprecated do not use */ @Deprecated public static final String AUTH_SCHEME_PREF = "http.auth.scheme-pref"; /** * Attribute name of a {@link java.lang.Object} object that represents * the actual user identity such as user {@link java.security.Principal}. */ public static final String USER_TOKEN = "http.user-token"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.util.List; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.auth.AuthSchemeRegistry; import org.apache.ogt.http.client.CookieStore; import org.apache.ogt.http.client.CredentialsProvider; import org.apache.ogt.http.cookie.CookieSpecRegistry; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * Configuration facade for {@link HttpContext} instances. * * @since 4.0 */ @NotThreadSafe public class ClientContextConfigurer implements ClientContext { private final HttpContext context; public ClientContextConfigurer (final HttpContext context) { if (context == null) throw new IllegalArgumentException("HTTP context may not be null"); this.context = context; } public void setCookieSpecRegistry(final CookieSpecRegistry registry) { this.context.setAttribute(COOKIESPEC_REGISTRY, registry); } public void setAuthSchemeRegistry(final AuthSchemeRegistry registry) { this.context.setAttribute(AUTHSCHEME_REGISTRY, registry); } public void setCookieStore(final CookieStore store) { this.context.setAttribute(COOKIE_STORE, store); } public void setCredentialsProvider(final CredentialsProvider provider) { this.context.setAttribute(CREDS_PROVIDER, provider); } /** * @deprecated (4.1-alpha1) Use {@link HttpParams#setParameter(String, Object)} to set the parameters * {@link org.apache.ogt.http.auth.params.AuthPNames#TARGET_AUTH_PREF AuthPNames#TARGET_AUTH_PREF} and * {@link org.apache.ogt.http.auth.params.AuthPNames#PROXY_AUTH_PREF AuthPNames#PROXY_AUTH_PREF} instead */ @Deprecated public void setAuthSchemePref(final List<String> list) { this.context.setAttribute(AUTH_SCHEME_PREF, list); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.protocol.HttpContext; /** * Class responsible for handling Content Encoding requests in HTTP. * <p> * Instances of this class are stateless, therefore they're thread-safe and immutable. * * @see "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5" * * @since 4.1 */ @Immutable public class RequestAcceptEncoding implements HttpRequestInterceptor { /** * Adds the header {@code "Accept-Encoding: gzip,deflate"} to the request. */ public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { /* Signal support for Accept-Encoding transfer encodings. */ request.addHeader("Accept-Encoding", "gzip,deflate"); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.protocol; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.auth.AuthScheme; import org.apache.ogt.http.auth.AuthState; import org.apache.ogt.http.client.AuthCache; import org.apache.ogt.http.client.params.AuthPolicy; import org.apache.ogt.http.impl.client.BasicAuthCache; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; /** * Response interceptor that adds successfully completed {@link AuthScheme}s * to the local {@link AuthCache} instance. Cached {@link AuthScheme}s can be * re-used when executing requests against known hosts, thus avoiding * additional authentication round-trips. * * @since 4.1 */ @Immutable public class ResponseAuthCache implements HttpResponseInterceptor { private final Log log = LogFactory.getLog(getClass()); public ResponseAuthCache() { super(); } public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE); HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (target != null && targetState != null) { if (isCachable(targetState)) { if (authCache == null) { authCache = new BasicAuthCache(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } cache(authCache, target, targetState); } } HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST); AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE); if (proxy != null && proxyState != null) { if (isCachable(proxyState)) { if (authCache == null) { authCache = new BasicAuthCache(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } cache(authCache, proxy, proxyState); } } } private boolean isCachable(final AuthState authState) { AuthScheme authScheme = authState.getAuthScheme(); if (authScheme == null || !authScheme.isComplete()) { return false; } String schemeName = authScheme.getSchemeName(); return schemeName.equalsIgnoreCase(AuthPolicy.BASIC) || schemeName.equalsIgnoreCase(AuthPolicy.DIGEST); } private void cache(final AuthCache authCache, final HttpHost host, final AuthState authState) { AuthScheme authScheme = authState.getAuthScheme(); if (authState.getAuthScope() != null) { if (authState.getCredentials() != null) { if (this.log.isDebugEnabled()) { this.log.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + host); } authCache.put(host, authScheme); } else { authCache.remove(host); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.protocol.HttpContext; /** * A handler for determining if the given execution context is user specific * or not. The token object returned by this handler is expected to uniquely * identify the current user if the context is user specific or to be * <code>null</code> if the context does not contain any resources or details * specific to the current user. * <p/> * The user token will be used to ensure that user specific resources will not * be shared with or reused by other users. * * @since 4.0 */ public interface UserTokenHandler { /** * The token object returned by this method is expected to uniquely * identify the current user if the context is user specific or to be * <code>null</code> if it is not. * * @param context the execution context * * @return user token that uniquely identifies the user or * <code>null</null> if the context is not user specific. */ Object getUserToken(HttpContext context); }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.entity; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.client.utils.URLEncodedUtils; import org.apache.ogt.http.entity.StringEntity; import org.apache.ogt.http.protocol.HTTP; /** * An entity composed of a list of url-encoded pairs. * This is typically useful while sending an HTTP POST request. * * @since 4.0 */ @NotThreadSafe // AbstractHttpEntity is not thread-safe public class UrlEncodedFormEntity extends StringEntity { /** * Constructs a new {@link UrlEncodedFormEntity} with the list * of parameters in the specified encoding. * * @param parameters list of name/value pairs * @param encoding encoding the name/value pairs be encoded with * @throws UnsupportedEncodingException if the encoding isn't supported */ public UrlEncodedFormEntity ( final List <? extends NameValuePair> parameters, final String encoding) throws UnsupportedEncodingException { super(URLEncodedUtils.format(parameters, encoding), encoding); setContentType(URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM + (encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET)); } /** * Constructs a new {@link UrlEncodedFormEntity} with the list * of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET} * * @param parameters list of name/value pairs * @throws UnsupportedEncodingException if the default encoding isn't supported */ public UrlEncodedFormEntity ( final List <? extends NameValuePair> parameters) throws UnsupportedEncodingException { this(parameters, HTTP.DEFAULT_CONTENT_CHARSET); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.entity; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.entity.HttpEntityWrapper; /** * {@link HttpEntityWrapper} responsible for handling deflate Content Coded responses. In RFC2616 * terms, <code>deflate</code> means a <code>zlib</code> stream as defined in RFC1950. Some server * implementations have misinterpreted RFC2616 to mean that a <code>deflate</code> stream as * defined in RFC1951 should be used (or maybe they did that since that's how IE behaves?). It's * confusing that <code>deflate</code> in HTTP 1.1 means <code>zlib</code> streams rather than * <code>deflate</code> streams. We handle both types in here, since that's what is seen on the * internet. Moral - prefer <code>gzip</code>! * * @see GzipDecompressingEntity * * @since 4.1 */ public class DeflateDecompressingEntity extends DecompressingEntity { /** * Creates a new {@link DeflateDecompressingEntity} which will wrap the specified * {@link HttpEntity}. * * @param entity * a non-null {@link HttpEntity} to be wrapped */ public DeflateDecompressingEntity(final HttpEntity entity) { super(entity); } /** * {@inheritDoc} */ @Override public InputStream getContent() throws IOException { InputStream wrapped = this.wrappedEntity.getContent(); /* * A zlib stream will have a header. * * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | * * * CMF is one byte. * * * FLG is one byte. * * * DICTID is four bytes, and only present if FLG.FDICT is set. * * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 * * We need to see if it looks like a proper zlib stream, or whether it is just a deflate * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers * implement deflate Content-Encoding using deflate streams, rather than zlib streams. * * We could start looking at the bytes, but to be honest, someone else has already read * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception * handling to do this. If that proves slow, then we could potentially change this to check * the first byte - does it look like a CMF? What about the second byte - does it look like * a FLG, etc. */ /* We read a small buffer to sniff the content. */ byte[] peeked = new byte[6]; PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); int headerLength = pushback.read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } /* We try to read the first uncompressed byte. */ byte[] dummy = new byte[1]; Inflater inf = new Inflater(); try { int n; while ((n = inf.inflate(dummy)) == 0) { if (inf.finished()) { /* Not expecting this, so fail loudly. */ throw new IOException("Unable to read the response"); } if (inf.needsDictionary()) { /* Need dictionary - then it must be zlib stream with DICTID part? */ break; } if (inf.needsInput()) { inf.setInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } /* * We read something without a problem, so it's a valid zlib stream. Just need to reset * and return an unused InputStream now. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback); } catch (DataFormatException e) { /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try * again. */ pushback.unread(peeked, 0, headerLength); return new InflaterInputStream(pushback, new Inflater(true)); } } /** * {@inheritDoc} */ @Override public Header getContentEncoding() { /* This HttpEntityWrapper has dealt with the Content-Encoding. */ return null; } /** * {@inheritDoc} */ @Override public long getContentLength() { /* Length of inflated content is unknown. */ return -1; } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.entity.HttpEntityWrapper; /** * Common base class for decompressing {@link HttpEntity} implementations. * * @since 4.1 */ abstract class DecompressingEntity extends HttpEntityWrapper { /** * Default buffer size. */ private static final int BUFFER_SIZE = 1024 * 2; /** * Creates a new {@link DecompressingEntity}. * * @param wrapped * the non-null {@link HttpEntity} to be wrapped */ public DecompressingEntity(final HttpEntity wrapped) { super(wrapped); } /** * {@inheritDoc} */ @Override public void writeTo(OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = getContent(); byte[] buffer = new byte[BUFFER_SIZE]; int l; while ((l = instream.read(buffer)) != -1) { outstream.write(buffer, 0, l); } } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.entity; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.entity.HttpEntityWrapper; /** * {@link HttpEntityWrapper} for handling gzip Content Coded responses. * * @since 4.1 */ public class GzipDecompressingEntity extends DecompressingEntity { /** * Creates a new {@link GzipDecompressingEntity} which will wrap the specified * {@link HttpEntity}. * * @param entity * the non-null {@link HttpEntity} to be wrapped */ public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } /** * {@inheritDoc} */ @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } /** * {@inheritDoc} */ @Override public Header getContentEncoding() { /* This HttpEntityWrapper has dealt with the Content-Encoding. */ return null; } /** * {@inheritDoc} */ @Override public long getContentLength() { /* length of ungzipped content is not known */ return -1; } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.io.IOException; import org.apache.ogt.http.annotation.Immutable; /** * Signals an error in the HTTP protocol. * * @since 4.0 */ @Immutable public class ClientProtocolException extends IOException { private static final long serialVersionUID = -5596590843227115865L; public ClientProtocolException() { super(); } public ClientProtocolException(String s) { super(s); } public ClientProtocolException(Throwable cause) { initCause(cause); } public ClientProtocolException(String message, Throwable cause) { super(message); initCause(cause); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.net.URI; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.protocol.HttpContext; /** * A handler for determining if an HTTP request should be redirected to * a new location in response to an HTTP response received from the target * server. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 * * @deprecated use {@link RedirectStrategy} */ @Deprecated public interface RedirectHandler { /** * Determines if a request should be redirected to a new location * given the response from the target server. * * @param response the response received from the target server * @param context the context for the request execution * * @return <code>true</code> if the request should be redirected, <code>false</code> * otherwise */ boolean isRedirectRequested(HttpResponse response, HttpContext context); /** * Determines the location request is expected to be redirected to * given the response from the target server and the current request * execution context. * * @param response the response received from the target server * @param context the context for the request execution * * @return redirect URI */ URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException; }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.util.Date; import java.util.List; import org.apache.ogt.http.cookie.Cookie; /** * This interface represents an abstract store for {@link Cookie} * objects. * * @since 4.0 */ public interface CookieStore { /** * Adds an {@link Cookie}, replacing any existing equivalent cookies. * If the given cookie has already expired it will not be added, but existing * values will still be removed. * * @param cookie the {@link Cookie cookie} to be added */ void addCookie(Cookie cookie); /** * Returns all cookies contained in this store. * * @return all cookies */ List<Cookie> getCookies(); /** * Removes all of {@link Cookie}s in this store that have expired by * the specified {@link java.util.Date}. * * @return true if any cookies were purged. */ boolean clearExpired(Date date); /** * Clears all cookies. */ void clear(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.io.IOException; import org.apache.ogt.http.protocol.HttpContext; /** * A handler for determining if an HttpRequest should be retried after a * recoverable exception during execution. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface HttpRequestRetryHandler { /** * Determines if a method should be retried after an IOException * occurs during execution. * * @param exception the exception that occurred * @param executionCount the number of times this method has been * unsuccessfully executed * @param context the context for the request execution * * @return <code>true</code> if the method should be retried, <code>false</code> * otherwise */ boolean retryRequest(IOException exception, int executionCount, HttpContext context); }
Java
/* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.utils; /** * Abstraction of international domain name (IDN) conversion. * * @since 4.0 */ public interface Idn { /** * Converts a name from its punycode representation to Unicode. * The name may be a single hostname or a dot-separated qualified domain name. * @param punycode the Punycode representation * @return the Unicode domain name */ String toUnicode(String punycode); }
Java
/* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.ogt.http.annotation.Immutable; /** * A collection of utilities to workaround limitations of Java clone framework. * * @since 4.0 */ @Immutable public class CloneUtils { public static Object clone(final Object obj) throws CloneNotSupportedException { if (obj == null) { return null; } if (obj instanceof Cloneable) { Class<?> clazz = obj.getClass (); Method m; try { m = clazz.getMethod("clone", (Class[]) null); } catch (NoSuchMethodException ex) { throw new NoSuchMethodError(ex.getMessage()); } try { return m.invoke(obj, (Object []) null); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause instanceof CloneNotSupportedException) { throw ((CloneNotSupportedException) cause); } else { throw new Error("Unexpected exception", cause); } } catch (IllegalAccessException ex) { throw new IllegalAccessError(ex.getMessage()); } } else { throw new CloneNotSupportedException(); } } /** * This class should not be instantiated. */ private CloneUtils() { } }
Java
/* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.ogt.http.annotation.Immutable; /** * Uses the java.net.IDN class through reflection. * * @since 4.0 */ @Immutable public class JdkIdn implements Idn { private final Method toUnicode; /** * * @throws ClassNotFoundException if java.net.IDN is not available */ public JdkIdn() throws ClassNotFoundException { Class<?> clazz = Class.forName("java.net.IDN"); try { toUnicode = clazz.getMethod("toUnicode", String.class); } catch (SecurityException e) { // doesn't happen throw new IllegalStateException(e.getMessage(), e); } catch (NoSuchMethodException e) { // doesn't happen throw new IllegalStateException(e.getMessage(), e); } } public String toUnicode(String punycode) { try { return (String) toUnicode.invoke(null, punycode); } catch (IllegalAccessException e) { throw new IllegalStateException(e.getMessage(), e); } catch (InvocationTargetException e) { Throwable t = e.getCause(); throw new RuntimeException(t.getMessage(), t); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.message.BasicNameValuePair; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.EntityUtils; /** * A collection of utilities for encoding URLs. * * @since 4.0 */ @Immutable public class URLEncodedUtils { public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; private static final String PARAMETER_SEPARATOR = "&"; private static final String NAME_VALUE_SEPARATOR = "="; /** * Returns a list of {@link NameValuePair NameValuePairs} as built from the * URI's query portion. For example, a URI of * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three * NameValuePairs, one for a=1, one for b=2, and one for c=3. * <p> * This is typically useful while parsing an HTTP PUT. * * @param uri * uri to parse * @param encoding * encoding to use while parsing the query */ public static List <NameValuePair> parse (final URI uri, final String encoding) { List <NameValuePair> result = Collections.emptyList(); final String query = uri.getRawQuery(); if (query != null && query.length() > 0) { result = new ArrayList <NameValuePair>(); parse(result, new Scanner(query), encoding); } return result; } /** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an * {@link HttpEntity}. The encoding is taken from the entity's * Content-Encoding header. * <p> * This is typically used while parsing an HTTP POST. * * @param entity * The entity to parse * @throws IOException * If there was an exception getting the entity's data. */ public static List <NameValuePair> parse ( final HttpEntity entity) throws IOException { List <NameValuePair> result = Collections.emptyList(); String contentType = null; String charset = null; Header h = entity.getContentType(); if (h != null) { HeaderElement[] elems = h.getElements(); if (elems.length > 0) { HeaderElement elem = elems[0]; contentType = elem.getName(); NameValuePair param = elem.getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) { final String content = EntityUtils.toString(entity, HTTP.ASCII); if (content != null && content.length() > 0) { result = new ArrayList <NameValuePair>(); parse(result, new Scanner(content), charset); } } return result; } /** * Returns true if the entity's Content-Type header is * <code>application/x-www-form-urlencoded</code>. */ public static boolean isEncoded (final HttpEntity entity) { Header h = entity.getContentType(); if (h != null) { HeaderElement[] elems = h.getElements(); if (elems.length > 0) { String contentType = elems[0].getName(); return contentType.equalsIgnoreCase(CONTENT_TYPE); } else { return false; } } else { return false; } } /** * Adds all parameters within the Scanner to the list of * <code>parameters</code>, as encoded by <code>encoding</code>. For * example, a scanner containing the string <code>a=1&b=2&c=3</code> would * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the * list of parameters. * * @param parameters * List to add parameters to. * @param scanner * Input that contains the parameters to parse. * @param encoding * Encoding to use when decoding the parameters. */ public static void parse ( final List <NameValuePair> parameters, final Scanner scanner, final String encoding) { scanner.useDelimiter(PARAMETER_SEPARATOR); while (scanner.hasNext()) { final String[] nameValue = scanner.next().split(NAME_VALUE_SEPARATOR); if (nameValue.length == 0 || nameValue.length > 2) throw new IllegalArgumentException("bad parameter"); final String name = decode(nameValue[0], encoding); String value = null; if (nameValue.length == 2) value = decode(nameValue[1], encoding); parameters.add(new BasicNameValuePair(name, value)); } } /** * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code> * list of parameters in an HTTP PUT or HTTP POST. * * @param parameters The parameters to include. * @param encoding The encoding to use. */ public static String format ( final List <? extends NameValuePair> parameters, final String encoding) { final StringBuilder result = new StringBuilder(); for (final NameValuePair parameter : parameters) { final String encodedName = encode(parameter.getName(), encoding); final String value = parameter.getValue(); final String encodedValue = value != null ? encode(value, encoding) : ""; if (result.length() > 0) result.append(PARAMETER_SEPARATOR); result.append(encodedName); result.append(NAME_VALUE_SEPARATOR); result.append(encodedValue); } return result.toString(); } private static String decode (final String content, final String encoding) { try { return URLDecoder.decode(content, encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET); } catch (UnsupportedEncodingException problem) { throw new IllegalArgumentException(problem); } } private static String encode (final String content, final String encoding) { try { return URLEncoder.encode(content, encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET); } catch (UnsupportedEncodingException problem) { throw new IllegalArgumentException(problem); } } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.utils; import java.net.URI; import java.net.URISyntaxException; import java.util.Stack; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.Immutable; /** * A collection of utilities for {@link URI URIs}, to workaround * bugs within the class or for ease-of-use features. * * @since 4.0 */ @Immutable public class URIUtils { /** * Constructs a {@link URI} using all the parameters. This should be * used instead of * {@link URI#URI(String, String, String, int, String, String, String)} * or any of the other URI multi-argument URI constructors. * * @param scheme * Scheme name * @param host * Host name * @param port * Port number * @param path * Path * @param query * Query * @param fragment * Fragment * * @throws URISyntaxException * If both a scheme and a path are given but the path is * relative, if the URI string constructed from the given * components violates RFC&nbsp;2396, or if the authority * component of the string is present but cannot be parsed * as a server-based authority */ public static URI createURI( final String scheme, final String host, int port, final String path, final String query, final String fragment) throws URISyntaxException { StringBuilder buffer = new StringBuilder(); if (host != null) { if (scheme != null) { buffer.append(scheme); buffer.append("://"); } buffer.append(host); if (port > 0) { buffer.append(':'); buffer.append(port); } } if (path == null || !path.startsWith("/")) { buffer.append('/'); } if (path != null) { buffer.append(path); } if (query != null) { buffer.append('?'); buffer.append(query); } if (fragment != null) { buffer.append('#'); buffer.append(fragment); } return new URI(buffer.toString()); } /** * A convenience method for creating a new {@link URI} whose scheme, host * and port are taken from the target host, but whose path, query and * fragment are taken from the existing URI. The fragment is only used if * dropFragment is false. * * @param uri * Contains the path, query and fragment to use. * @param target * Contains the scheme, host and port to use. * @param dropFragment * True if the fragment should not be copied. * * @throws URISyntaxException * If the resulting URI is invalid. */ public static URI rewriteURI( final URI uri, final HttpHost target, boolean dropFragment) throws URISyntaxException { if (uri == null) { throw new IllegalArgumentException("URI may nor be null"); } if (target != null) { return URIUtils.createURI( target.getSchemeName(), target.getHostName(), target.getPort(), normalizePath(uri.getRawPath()), uri.getRawQuery(), dropFragment ? null : uri.getRawFragment()); } else { return URIUtils.createURI( null, null, -1, normalizePath(uri.getRawPath()), uri.getRawQuery(), dropFragment ? null : uri.getRawFragment()); } } private static String normalizePath(String path) { if (path == null) { return null; } int n = 0; for (; n < path.length(); n++) { if (path.charAt(n) != '/') { break; } } if (n > 1) { path = path.substring(n - 1); } return path; } /** * A convenience method for * {@link URIUtils#rewriteURI(URI, HttpHost, boolean)} that always keeps the * fragment. */ public static URI rewriteURI( final URI uri, final HttpHost target) throws URISyntaxException { return rewriteURI(uri, target, false); } /** * Resolves a URI reference against a base URI. Work-around for bug in * java.net.URI (<http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>) * * @param baseURI the base URI * @param reference the URI reference * @return the resulting URI */ public static URI resolve(final URI baseURI, final String reference) { return URIUtils.resolve(baseURI, URI.create(reference)); } /** * Resolves a URI reference against a base URI. Work-around for bugs in * java.net.URI (e.g. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>) * * @param baseURI the base URI * @param reference the URI reference * @return the resulting URI */ public static URI resolve(final URI baseURI, URI reference){ if (baseURI == null) { throw new IllegalArgumentException("Base URI may nor be null"); } if (reference == null) { throw new IllegalArgumentException("Reference URI may nor be null"); } String s = reference.toString(); if (s.startsWith("?")) { return resolveReferenceStartingWithQueryString(baseURI, reference); } boolean emptyReference = s.length() == 0; if (emptyReference) { reference = URI.create("#"); } URI resolved = baseURI.resolve(reference); if (emptyReference) { String resolvedString = resolved.toString(); resolved = URI.create(resolvedString.substring(0, resolvedString.indexOf('#'))); } return removeDotSegments(resolved); } /** * Resolves a reference starting with a query string. * * @param baseURI the base URI * @param reference the URI reference starting with a query string * @return the resulting URI */ private static URI resolveReferenceStartingWithQueryString( final URI baseURI, final URI reference) { String baseUri = baseURI.toString(); baseUri = baseUri.indexOf('?') > -1 ? baseUri.substring(0, baseUri.indexOf('?')) : baseUri; return URI.create(baseUri + reference.toString()); } /** * Removes dot segments according to RFC 3986, section 5.2.4 * * @param uri the original URI * @return the URI without dot segments */ private static URI removeDotSegments(URI uri) { String path = uri.getPath(); if ((path == null) || (path.indexOf("/.") == -1)) { // No dot segments to remove return uri; } String[] inputSegments = path.split("/"); Stack<String> outputSegments = new Stack<String>(); for (int i = 0; i < inputSegments.length; i++) { if ((inputSegments[i].length() == 0) || (".".equals(inputSegments[i]))) { // Do nothing } else if ("..".equals(inputSegments[i])) { if (!outputSegments.isEmpty()) { outputSegments.pop(); } } else { outputSegments.push(inputSegments[i]); } } StringBuilder outputBuffer = new StringBuilder(); for (String outputSegment : outputSegments) { outputBuffer.append('/').append(outputSegment); } try { return new URI(uri.getScheme(), uri.getAuthority(), outputBuffer.toString(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } /** * Extracts target host from the given {@link URI}. * * @param uri * @return the target host if the URI is absolute or <code>null</null> if the URI is * relative or does not contain a valid host name. * * @since 4.1 */ public static HttpHost extractHost(final URI uri) { if (uri == null) { return null; } HttpHost target = null; if (uri.isAbsolute()) { int port = uri.getPort(); // may be overridden later String host = uri.getHost(); if (host == null) { // normal parse failed; let's do it ourselves // authority does not seem to care about the valid character-set for host names host = uri.getAuthority(); if (host != null) { // Strip off any leading user credentials int at = host.indexOf('@'); if (at >= 0) { if (host.length() > at+1 ) { host = host.substring(at+1); } else { host = null; // @ on its own } } // Extract the port suffix, if present if (host != null) { int colon = host.indexOf(':'); if (colon >= 0) { if (colon+1 < host.length()) { port = Integer.parseInt(host.substring(colon+1)); } host = host.substring(0,colon); } } } } String scheme = uri.getScheme(); if (host != null) { target = new HttpHost(host, port, scheme); } } return target; } /** * This class should not be instantiated. */ private URIUtils() { } }
Java
/* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.utils; import org.apache.ogt.http.annotation.Immutable; /** * Facade that provides conversion between Unicode and Punycode domain names. * It will use an appropriate implementation. * * @since 4.0 */ @Immutable public class Punycode { private static final Idn impl; static { Idn _impl; try { _impl = new JdkIdn(); } catch (Exception e) { _impl = new Rfc3492Idn(); } impl = _impl; } public static String toUnicode(String punycode) { return impl.toUnicode(punycode); } }
Java
/* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.utils; import java.util.StringTokenizer; import org.apache.ogt.http.annotation.Immutable; /** * Implementation from pseudo code in RFC 3492. * * @since 4.0 */ @Immutable public class Rfc3492Idn implements Idn { private static final int base = 36; private static final int tmin = 1; private static final int tmax = 26; private static final int skew = 38; private static final int damp = 700; private static final int initial_bias = 72; private static final int initial_n = 128; private static final char delimiter = '-'; private static final String ACE_PREFIX = "xn--"; private int adapt(int delta, int numpoints, boolean firsttime) { if (firsttime) delta = delta / damp; else delta = delta / 2; delta = delta + (delta / numpoints); int k = 0; while (delta > ((base - tmin) * tmax) / 2) { delta = delta / (base - tmin); k = k + base; } return k + (((base - tmin + 1) * delta) / (delta + skew)); } private int digit(char c) { if ((c >= 'A') && (c <= 'Z')) return (c - 'A'); if ((c >= 'a') && (c <= 'z')) return (c - 'a'); if ((c >= '0') && (c <= '9')) return (c - '0') + 26; throw new IllegalArgumentException("illegal digit: "+ c); } public String toUnicode(String punycode) { StringBuilder unicode = new StringBuilder(punycode.length()); StringTokenizer tok = new StringTokenizer(punycode, "."); while (tok.hasMoreTokens()) { String t = tok.nextToken(); if (unicode.length() > 0) unicode.append('.'); if (t.startsWith(ACE_PREFIX)) t = decode(t.substring(4)); unicode.append(t); } return unicode.toString(); } protected String decode(String input) { int n = initial_n; int i = 0; int bias = initial_bias; StringBuilder output = new StringBuilder(input.length()); int lastdelim = input.lastIndexOf(delimiter); if (lastdelim != -1) { output.append(input.subSequence(0, lastdelim)); input = input.substring(lastdelim + 1); } while (input.length() > 0) { int oldi = i; int w = 1; for (int k = base;; k += base) { if (input.length() == 0) break; char c = input.charAt(0); input = input.substring(1); int digit = digit(c); i = i + digit * w; // FIXME fail on overflow int t; if (k <= bias + tmin) { t = tmin; } else if (k >= bias + tmax) { t = tmax; } else { t = k - bias; } if (digit < t) break; w = w * (base - t); // FIXME fail on overflow } bias = adapt(i - oldi, output.length() + 1, (oldi == 0)); n = n + i / (output.length() + 1); // FIXME fail on overflow i = i % (output.length() + 1); // {if n is a basic code point then fail} output.insert(i, (char) n); i++; } return output.toString(); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.Immutable; /** * Signals failure to retry the request due to non-repeatable request * entity. * * * @since 4.0 */ @Immutable public class NonRepeatableRequestException extends ProtocolException { private static final long serialVersionUID = 82685265288806048L; /** * Creates a new NonRepeatableEntityException with a <tt>null</tt> detail message. */ public NonRepeatableRequestException() { super(); } /** * Creates a new NonRepeatableEntityException with the specified detail message. * * @param message The exception detail message */ public NonRepeatableRequestException(String message) { super(message); } /** * Creates a new NonRepeatableEntityException with the specified detail message. * * @param message The exception detail message * @param cause the cause */ public NonRepeatableRequestException(String message, Throwable cause) { super(message, cause); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.io.IOException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * This interface represents only the most basic contract for HTTP request * execution. It imposes no restrictions or particular details on the request * execution process and leaves the specifics of state management, * authentication and redirect handling up to individual implementations. * This should make it easier to decorate the interface with additional * functionality such as response content caching. * <p/> * The usual execution flow can be demonstrated by the code snippet below: * <PRE> * HttpClient httpclient = new DefaultHttpClient(); * * // Prepare a request object * HttpGet httpget = new HttpGet("http://www.apache.org/"); * * // Execute the request * HttpResponse response = httpclient.execute(httpget); * * // Examine the response status * System.out.println(response.getStatusLine()); * * // Get hold of the response entity * HttpEntity entity = response.getEntity(); * * // If the response does not enclose an entity, there is no need * // to worry about connection release * if (entity != null) { * InputStream instream = entity.getContent(); * try { * * BufferedReader reader = new BufferedReader( * new InputStreamReader(instream)); * // do something useful with the response * System.out.println(reader.readLine()); * * } catch (IOException ex) { * * // In case of an IOException the connection will be released * // back to the connection manager automatically * throw ex; * * } catch (RuntimeException ex) { * * // In case of an unexpected exception you may want to abort * // the HTTP request in order to shut down the underlying * // connection and release it back to the connection manager. * httpget.abort(); * throw ex; * * } finally { * * // Closing the input stream will trigger connection release * instream.close(); * * } * * // When HttpClient instance is no longer needed, * // shut down the connection manager to ensure * // immediate deallocation of all system resources * httpclient.getConnectionManager().shutdown(); * } * </PRE> * * @since 4.0 */ public interface HttpClient { /** * Obtains the parameters for this client. * These parameters will become defaults for all requests being * executed with this client, and for the parameters of * dependent objects in this client. * * @return the default parameters */ HttpParams getParams(); /** * Obtains the connection manager used by this client. * * @return the connection manager */ ClientConnectionManager getConnectionManager(); /** * Executes a request using the default context. * * @param request the request to execute * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException; /** * Executes a request using the given context. * The route to the target will be determined by the HTTP client. * * @param request the request to execute * @param context the context to use for the execution, or * <code>null</code> to use the default context * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException; /** * Executes a request to the target using the default context. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException; /** * Executes a request to the target using the given context. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param context the context to use for the execution, or * <code>null</code> to use the default context * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException; /** * Executes a request using the default context and processes the * response using the given response handler. * * @param request the request to execute * @param responseHandler the response handler * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException; /** * Executes a request using the given context and processes the * response using the given response handler. * * @param request the request to execute * @param responseHandler the response handler * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException; /** * Executes a request to the target using the default context and * processes the response using the given response handler. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param responseHandler the response handler * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException; /** * Executes a request to the target using the given context and * processes the response using the given response handler. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param responseHandler the response handler * @param context the context to use for the execution, or * <code>null</code> to use the default context * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException; }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.annotation.Immutable; /** * Signals a circular redirect * * * @since 4.0 */ @Immutable public class CircularRedirectException extends RedirectException { private static final long serialVersionUID = 6830063487001091803L; /** * Creates a new CircularRedirectException with a <tt>null</tt> detail message. */ public CircularRedirectException() { super(); } /** * Creates a new CircularRedirectException with the specified detail message. * * @param message The exception detail message */ public CircularRedirectException(String message) { super(message); } /** * Creates a new CircularRedirectException with the specified detail message and cause. * * @param message the exception detail message * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt> * if the cause is unavailable, unknown, or not a <tt>Throwable</tt> */ public CircularRedirectException(String message, Throwable cause) { super(message, cause); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.util.Map; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.auth.AuthScheme; import org.apache.ogt.http.auth.AuthenticationException; import org.apache.ogt.http.auth.MalformedChallengeException; import org.apache.ogt.http.protocol.HttpContext; /** /** * A handler for determining if an HTTP response represents an authentication * challenge that was sent back to the client as a result of authentication * failure. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface AuthenticationHandler { /** * Determines if the given HTTP response response represents * an authentication challenge that was sent back as a result * of authentication failure * @param response HTTP response. * @param context HTTP context. * @return <code>true</code> if user authentication is required, * <code>false</code> otherwise. */ boolean isAuthenticationRequested( HttpResponse response, HttpContext context); /** * Extracts from the given HTTP response a collection of authentication * challenges, each of which represents an authentication scheme supported * by the authentication host. * * @param response HTTP response. * @param context HTTP context. * @return a collection of challenges keyed by names of corresponding * authentication schemes. * @throws MalformedChallengeException if one of the authentication * challenges is not valid or malformed. */ Map<String, Header> getChallenges( HttpResponse response, HttpContext context) throws MalformedChallengeException; /** * Selects one authentication challenge out of all available and * creates and generates {@link AuthScheme} instance capable of * processing that challenge. * @param challenges collection of challenges. * @param response HTTP response. * @param context HTTP context. * @return authentication scheme to use for authentication. * @throws AuthenticationException if an authentication scheme * could not be selected. */ AuthScheme selectScheme( Map<String, Header> challenges, HttpResponse response, HttpContext context) throws AuthenticationException; }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.annotation.Immutable; /** * Signals a non 2xx HTTP response. * * @since 4.0 */ @Immutable public class HttpResponseException extends ClientProtocolException { private static final long serialVersionUID = -7186627969477257933L; private final int statusCode; public HttpResponseException(int statusCode, final String s) { super(s); this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.params; import org.apache.ogt.http.auth.params.AuthPNames; import org.apache.ogt.http.conn.params.ConnConnectionPNames; import org.apache.ogt.http.conn.params.ConnManagerPNames; import org.apache.ogt.http.conn.params.ConnRoutePNames; import org.apache.ogt.http.cookie.params.CookieSpecPNames; import org.apache.ogt.http.params.CoreConnectionPNames; import org.apache.ogt.http.params.CoreProtocolPNames; /** * Collected parameter names for the HttpClient module. * This interface combines the parameter definitions of the HttpClient * module and all dependency modules or informational units. * It does not define additional parameter names, but references * other interfaces defining parameter names. * <br/> * This interface is meant as a navigation aid for developers. * When referring to parameter names, you should use the interfaces * in which the respective constants are actually defined. * * @since 4.0 */ @SuppressWarnings("deprecation") public interface AllClientPNames extends CoreConnectionPNames, CoreProtocolPNames, ClientPNames, AuthPNames, CookieSpecPNames, ConnConnectionPNames, ConnManagerPNames, ConnRoutePNames { // no additional definitions }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.params; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.params.HttpParams; /** * An adaptor for manipulating HTTP client parameters in {@link HttpParams}. * * @since 4.0 */ @Immutable public class HttpClientParams { private HttpClientParams() { super(); } public static boolean isRedirecting(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getBooleanParameter (ClientPNames.HANDLE_REDIRECTS, true); } public static void setRedirecting(final HttpParams params, boolean value) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setBooleanParameter (ClientPNames.HANDLE_REDIRECTS, value); } public static boolean isAuthenticating(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getBooleanParameter (ClientPNames.HANDLE_AUTHENTICATION, true); } public static void setAuthenticating(final HttpParams params, boolean value) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setBooleanParameter (ClientPNames.HANDLE_AUTHENTICATION, value); } public static String getCookiePolicy(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } String cookiePolicy = (String) params.getParameter(ClientPNames.COOKIE_POLICY); if (cookiePolicy == null) { return CookiePolicy.BEST_MATCH; } return cookiePolicy; } public static void setCookiePolicy(final HttpParams params, final String cookiePolicy) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setParameter(ClientPNames.COOKIE_POLICY, cookiePolicy); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.params; import org.apache.ogt.http.annotation.Immutable; /** * Standard cookie specifications supported by HttpClient. * * @since 4.0 */ @Immutable public final class CookiePolicy { /** * The policy that provides high degree of compatibilty * with common cookie management of popular HTTP agents. */ public static final String BROWSER_COMPATIBILITY = "compatibility"; /** * The Netscape cookie draft compliant policy. */ public static final String NETSCAPE = "netscape"; /** * The RFC 2109 compliant policy. */ public static final String RFC_2109 = "rfc2109"; /** * The RFC 2965 compliant policy. */ public static final String RFC_2965 = "rfc2965"; /** * The default 'best match' policy. */ public static final String BEST_MATCH = "best-match"; /** * The policy that ignores cookies. * * @since 4.1-beta1 */ public static final String IGNORE_COOKIES = "ignoreCookies"; private CookiePolicy() { super(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.params; import java.util.Collection; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.conn.ClientConnectionManagerFactory; import org.apache.ogt.http.params.HttpAbstractParamBean; import org.apache.ogt.http.params.HttpParams; /** * This is a Java Bean class that can be used to wrap an instance of * {@link HttpParams} and manipulate HTTP client parameters using * Java Beans conventions. * * @since 4.0 */ @NotThreadSafe public class ClientParamBean extends HttpAbstractParamBean { public ClientParamBean (final HttpParams params) { super(params); } public void setConnectionManagerFactoryClassName (final String factory) { params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, factory); } @Deprecated public void setConnectionManagerFactory(ClientConnectionManagerFactory factory) { params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY, factory); } public void setHandleRedirects (final boolean handle) { params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, handle); } public void setRejectRelativeRedirect (final boolean reject) { params.setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, reject); } public void setMaxRedirects (final int maxRedirects) { params.setIntParameter(ClientPNames.MAX_REDIRECTS, maxRedirects); } public void setAllowCircularRedirects (final boolean allow) { params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, allow); } public void setHandleAuthentication (final boolean handle) { params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, handle); } public void setCookiePolicy (final String policy) { params.setParameter(ClientPNames.COOKIE_POLICY, policy); } public void setVirtualHost (final HttpHost host) { params.setParameter(ClientPNames.VIRTUAL_HOST, host); } public void setDefaultHeaders (final Collection <Header> headers) { params.setParameter(ClientPNames.DEFAULT_HEADERS, headers); } public void setDefaultHost (final HttpHost host) { params.setParameter(ClientPNames.DEFAULT_HOST, host); } }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.params; /** * Parameter names for HTTP client parameters. * * @since 4.0 */ public interface ClientPNames { /** * Defines the class name of the default {@link org.apache.ogt.http.conn.ClientConnectionManager} * <p> * This parameter expects a value of type {@link String}. * </p> */ public static final String CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name"; /** * @deprecated use #CONNECTION_MANAGER_FACTORY_CLASS_NAME */ @Deprecated public static final String CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object"; /** * Defines whether redirects should be handled automatically * <p> * This parameter expects a value of type {@link Boolean}. * </p> */ public static final String HANDLE_REDIRECTS = "http.protocol.handle-redirects"; /** * Defines whether relative redirects should be rejected. HTTP specification * requires the location value be an absolute URI. * <p> * This parameter expects a value of type {@link Boolean}. * </p> */ public static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; /** * Defines the maximum number of redirects to be followed. * The limit on number of redirects is intended to prevent infinite loops. * <p> * This parameter expects a value of type {@link Integer}. * </p> */ public static final String MAX_REDIRECTS = "http.protocol.max-redirects"; /** * Defines whether circular redirects (redirects to the same location) should be allowed. * The HTTP spec is not sufficiently clear whether circular redirects are permitted, * therefore optionally they can be enabled * <p> * This parameter expects a value of type {@link Boolean}. * </p> */ public static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; /** * Defines whether authentication should be handled automatically. * <p> * This parameter expects a value of type {@link Boolean}. * </p> */ public static final String HANDLE_AUTHENTICATION = "http.protocol.handle-authentication"; /** * Defines the name of the cookie specification to be used for HTTP state management. * <p> * This parameter expects a value of type {@link String}. * </p> */ public static final String COOKIE_POLICY = "http.protocol.cookie-policy"; /** * Defines the virtual host name to be used in the <code>Host</code> * request header instead of the physical host name. * <p> * This parameter expects a value of type {@link org.apache.ogt.http.HttpHost}. * </p> */ public static final String VIRTUAL_HOST = "http.virtual-host"; /** * Defines the request headers to be sent per default with each request. * <p> * This parameter expects a value of type {@link java.util.Collection}. The * collection is expected to contain {@link org.apache.ogt.http.Header}s. * </p> */ public static final String DEFAULT_HEADERS = "http.default-headers"; /** * Defines the default host. The default value will be used if the target host is * not explicitly specified in the request URI. * <p> * This parameter expects a value of type {@link org.apache.ogt.http.HttpHost}. * </p> */ public static final String DEFAULT_HOST = "http.default-host"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.params; import org.apache.ogt.http.annotation.Immutable; /** * Standard authentication schemes supported by HttpClient. * * @since 4.0 */ @Immutable public final class AuthPolicy { private AuthPolicy() { super(); } /** * The NTLM scheme is a proprietary Microsoft Windows Authentication * protocol (considered to be the most secure among currently supported * authentication schemes). */ public static final String NTLM = "NTLM"; /** * Digest authentication scheme as defined in RFC2617. */ public static final String DIGEST = "Digest"; /** * Basic authentication scheme as defined in RFC2617 (considered inherently * insecure, but most widely supported) */ public static final String BASIC = "Basic"; /** * SPNEGO/Kerberos Authentication scheme. * * @since 4.1 */ public static final String SPNEGO = "negotiate"; }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.auth.AuthScheme; /** * Abstract {@link AuthScheme} cache. Initialized {@link AuthScheme} objects * from this cache can be used to preemptively authenticate against known * hosts. * * @since 4.1 */ public interface AuthCache { void put(HttpHost host, AuthScheme authScheme); AuthScheme get(HttpHost host); void remove(HttpHost host); void clear(); }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.Credentials; /** * Abstract credentials provider that maintains a collection of user * credentials. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface CredentialsProvider { /** * Sets the {@link Credentials credentials} for the given authentication * scope. Any previous credentials for the given scope will be overwritten. * * @param authscope the {@link AuthScope authentication scope} * @param credentials the authentication {@link Credentials credentials} * for the given scope. * * @see #getCredentials(AuthScope) */ void setCredentials(AuthScope authscope, Credentials credentials); /** * Get the {@link Credentials credentials} for the given authentication scope. * * @param authscope the {@link AuthScope authentication scope} * @return the credentials * * @see #setCredentials(AuthScope, Credentials) */ Credentials getCredentials(AuthScope authscope); /** * Clears all credentials. */ void clear(); }
Java
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import java.io.IOException; import org.apache.ogt.http.HttpResponse; /** * Handler that encapsulates the process of generating a response object * from a {@link HttpResponse}. * * * @since 4.0 */ public interface ResponseHandler<T> { /** * Processes an {@link HttpResponse} and returns some value * corresponding to that response. * * @param response The response to process * @return A value determined by the response * * @throws ClientProtocolException in case of an http protocol error * @throws IOException in case of a problem or the connection was aborted */ T handleResponse(HttpResponse response) throws ClientProtocolException, IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.protocol.HttpContext; /** * A strategy for determining if an HTTP request should be redirected to * a new location in response to an HTTP response received from the target * server. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.1 */ public interface RedirectStrategy { /** * Determines if a request should be redirected to a new location * given the response from the target server. * * @param request the executed request * @param response the response received from the target server * @param context the context for the request execution * * @return <code>true</code> if the request should be redirected, <code>false</code> * otherwise */ boolean isRedirected( HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException; /** * Determines the redirect location given the response from the target * server and the current request execution context and generates a new * request to be sent to the location. * * @param request the executed request * @param response the response received from the target server * @param context the context for the request execution * * @return redirected request */ HttpUriRequest getRedirect( HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import org.apache.ogt.http.annotation.NotThreadSafe; /** * HTTP GET method. * <p> * The HTTP GET method is defined in section 9.3 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The GET method means retrieve whatever information (in the form of an * entity) is identified by the Request-URI. If the Request-URI refers * to a data-producing process, it is the produced data which shall be * returned as the entity in the response and not the source text of the * process, unless that text happens to be the output of the process. * </blockquote> * </p> * * @since 4.0 */ @NotThreadSafe public class HttpGet extends HttpRequestBase { public final static String METHOD_NAME = "GET"; public HttpGet() { super(); } public HttpGet(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpGet(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.client.utils.CloneUtils; import org.apache.ogt.http.protocol.HTTP; /** * Basic implementation of an entity enclosing HTTP request * that can be modified * * @since 4.0 */ @NotThreadSafe // HttpRequestBase is @NotThreadSafe public abstract class HttpEntityEnclosingRequestBase extends HttpRequestBase implements HttpEntityEnclosingRequest { private HttpEntity entity; public HttpEntityEnclosingRequestBase() { super(); } public HttpEntity getEntity() { return this.entity; } public void setEntity(final HttpEntity entity) { this.entity = entity; } public boolean expectContinue() { Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); } @Override public Object clone() throws CloneNotSupportedException { HttpEntityEnclosingRequestBase clone = (HttpEntityEnclosingRequestBase) super.clone(); if (this.entity != null) { clone.entity = (HttpEntity) CloneUtils.clone(this.entity); } return clone; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import org.apache.ogt.http.annotation.NotThreadSafe; /** * HTTP DELETE method * <p> * The HTTP DELETE method is defined in section 9.7 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The DELETE method requests that the origin server delete the resource * identified by the Request-URI. [...] The client cannot * be guaranteed that the operation has been carried out, even if the * status code returned from the origin server indicates that the action * has been completed successfully. * </blockquote> * * @since 4.0 */ @NotThreadSafe // HttpRequestBase is @NotThreadSafe public class HttpDelete extends HttpRequestBase { public final static String METHOD_NAME = "DELETE"; public HttpDelete() { super(); } public HttpDelete(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpDelete(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import org.apache.ogt.http.annotation.NotThreadSafe; /** * HTTP HEAD method. * <p> * The HTTP HEAD method is defined in section 9.4 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The HEAD method is identical to GET except that the server MUST NOT * return a message-body in the response. The metainformation contained * in the HTTP headers in response to a HEAD request SHOULD be identical * to the information sent in response to a GET request. This method can * be used for obtaining metainformation about the entity implied by the * request without transferring the entity-body itself. This method is * often used for testing hypertext links for validity, accessibility, * and recent modification. * </blockquote> * </p> * * @since 4.0 */ @NotThreadSafe public class HttpHead extends HttpRequestBase { public final static String METHOD_NAME = "HEAD"; public HttpHead() { super(); } public HttpHead(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpHead(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import org.apache.ogt.http.annotation.NotThreadSafe; /** * HTTP TRACE method. * <p> * The HTTP TRACE method is defined in section 9.6 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The TRACE method is used to invoke a remote, application-layer loop- * back of the request message. The final recipient of the request * SHOULD reflect the message received back to the client as the * entity-body of a 200 (OK) response. The final recipient is either the * origin server or the first proxy or gateway to receive a Max-Forwards * value of zero (0) in the request (see section 14.31). A TRACE request * MUST NOT include an entity. * </blockquote> * </p> * * @since 4.0 */ @NotThreadSafe public class HttpTrace extends HttpRequestBase { public final static String METHOD_NAME = "TRACE"; public HttpTrace() { super(); } public HttpTrace(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpTrace(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import org.apache.ogt.http.annotation.NotThreadSafe; /** * HTTP POST method. * <p> * The HTTP POST method is defined in section 9.5 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The POST method is used to request that the origin server accept the entity * enclosed in the request as a new subordinate of the resource identified by * the Request-URI in the Request-Line. POST is designed to allow a uniform * method to cover the following functions: * <ul> * <li>Annotation of existing resources</li> * <li>Posting a message to a bulletin board, newsgroup, mailing list, or * similar group of articles</li> * <li>Providing a block of data, such as the result of submitting a form, * to a data-handling process</li> * <li>Extending a database through an append operation</li> * </ul> * </blockquote> * </p> * * @since 4.0 */ @NotThreadSafe public class HttpPost extends HttpEntityEnclosingRequestBase { public final static String METHOD_NAME = "POST"; public HttpPost() { super(); } public HttpPost(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpPost(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.io.IOException; import java.net.URI; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.client.utils.CloneUtils; import org.apache.ogt.http.conn.ClientConnectionRequest; import org.apache.ogt.http.conn.ConnectionReleaseTrigger; import org.apache.ogt.http.message.AbstractHttpMessage; import org.apache.ogt.http.message.BasicRequestLine; import org.apache.ogt.http.message.HeaderGroup; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; /** * Basic implementation of an HTTP request that can be modified. * * * @since 4.0 */ @NotThreadSafe public abstract class HttpRequestBase extends AbstractHttpMessage implements HttpUriRequest, AbortableHttpRequest, Cloneable { private Lock abortLock; private boolean aborted; private URI uri; private ClientConnectionRequest connRequest; private ConnectionReleaseTrigger releaseTrigger; public HttpRequestBase() { super(); this.abortLock = new ReentrantLock(); } public abstract String getMethod(); public ProtocolVersion getProtocolVersion() { return HttpProtocolParams.getVersion(getParams()); } /** * Returns the original request URI. * <p> * Please note URI remains unchanged in the course of request execution and * is not updated if the request is redirected to another location. */ public URI getURI() { return this.uri; } public RequestLine getRequestLine() { String method = getMethod(); ProtocolVersion ver = getProtocolVersion(); URI uri = getURI(); String uritext = null; if (uri != null) { uritext = uri.toASCIIString(); } if (uritext == null || uritext.length() == 0) { uritext = "/"; } return new BasicRequestLine(method, uritext, ver); } public void setURI(final URI uri) { this.uri = uri; } public void setConnectionRequest(final ClientConnectionRequest connRequest) throws IOException { this.abortLock.lock(); try { if (this.aborted) { throw new IOException("Request already aborted"); } this.releaseTrigger = null; this.connRequest = connRequest; } finally { this.abortLock.unlock(); } } public void setReleaseTrigger(final ConnectionReleaseTrigger releaseTrigger) throws IOException { this.abortLock.lock(); try { if (this.aborted) { throw new IOException("Request already aborted"); } this.connRequest = null; this.releaseTrigger = releaseTrigger; } finally { this.abortLock.unlock(); } } public void abort() { ClientConnectionRequest localRequest; ConnectionReleaseTrigger localTrigger; this.abortLock.lock(); try { if (this.aborted) { return; } this.aborted = true; localRequest = connRequest; localTrigger = releaseTrigger; } finally { this.abortLock.unlock(); } // Trigger the callbacks outside of the lock, to prevent // deadlocks in the scenario where the callbacks have // their own locks that may be used while calling // setReleaseTrigger or setConnectionRequest. if (localRequest != null) { localRequest.abortRequest(); } if (localTrigger != null) { try { localTrigger.abortConnection(); } catch (IOException ex) { // ignore } } } public boolean isAborted() { return this.aborted; } @Override public Object clone() throws CloneNotSupportedException { HttpRequestBase clone = (HttpRequestBase) super.clone(); clone.abortLock = new ReentrantLock(); clone.aborted = false; clone.releaseTrigger = null; clone.connRequest = null; clone.headergroup = (HeaderGroup) CloneUtils.clone(this.headergroup); clone.params = (HttpParams) CloneUtils.clone(this.params); return clone; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import org.apache.ogt.http.HttpRequest; /** * Extended version of the {@link HttpRequest} interface that provides * convenience methods to access request properties such as request URI * and method type. * * * <!-- empty lines to avoid svn diff problems --> * @since 4.0 */ public interface HttpUriRequest extends HttpRequest { /** * Returns the HTTP method this request uses, such as <code>GET</code>, * <code>PUT</code>, <code>POST</code>, or other. */ String getMethod(); /** * Returns the URI this request uses, such as * <code>http://example.org/path/to/file</code>. * <br/> * Note that the URI may be absolute URI (as above) or may be a relative URI. * <p> * Implementations are encouraged to return * the URI that was initially requested. * </p> * <p> * To find the final URI after any redirects have been processed, * please see the section entitled * <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d4e205">HTTP execution context</a> * in the * <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html">HttpClient Tutorial</a> * </p> */ URI getURI(); /** * Aborts execution of the request. * * @throws UnsupportedOperationException if the abort operation * is not supported / cannot be implemented. */ void abort() throws UnsupportedOperationException; /** * Tests if the request execution has been aborted. * * @return <code>true</code> if the request execution has been aborted, * <code>false</code> otherwise. */ boolean isAborted(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import org.apache.ogt.http.annotation.NotThreadSafe; /** * HTTP PUT method. * <p> * The HTTP PUT method is defined in section 9.6 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The PUT method requests that the enclosed entity be stored under the * supplied Request-URI. If the Request-URI refers to an already * existing resource, the enclosed entity SHOULD be considered as a * modified version of the one residing on the origin server. * </blockquote> * </p> * * @since 4.0 */ @NotThreadSafe public class HttpPut extends HttpEntityEnclosingRequestBase { public final static String METHOD_NAME = "PUT"; public HttpPut() { super(); } public HttpPut(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpPut(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.net.URI; import java.util.HashSet; import java.util.Set; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.annotation.NotThreadSafe; /** * HTTP OPTIONS method. * <p> * The HTTP OPTIONS method is defined in section 9.2 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The OPTIONS method represents a request for information about the * communication options available on the request/response chain * identified by the Request-URI. This method allows the client to * determine the options and/or requirements associated with a resource, * or the capabilities of a server, without implying a resource action * or initiating a resource retrieval. * </blockquote> * </p> * * @since 4.0 */ @NotThreadSafe public class HttpOptions extends HttpRequestBase { public final static String METHOD_NAME = "OPTIONS"; public HttpOptions() { super(); } public HttpOptions(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpOptions(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } public Set<String> getAllowedMethods(final HttpResponse response) { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } HeaderIterator it = response.headerIterator("Allow"); Set<String> methods = new HashSet<String>(); while (it.hasNext()) { Header header = it.nextHeader(); HeaderElement[] elements = header.getElements(); for (HeaderElement element : elements) { methods.add(element.getName()); } } return methods; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.client.methods; import java.io.IOException; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.ClientConnectionRequest; import org.apache.ogt.http.conn.ConnectionReleaseTrigger; import org.apache.ogt.http.conn.ManagedClientConnection; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; /** * Interface representing an HTTP request that can be aborted by shutting * down the underlying HTTP connection. * * * <!-- empty lines to avoid svn diff problems --> * @since 4.0 */ public interface AbortableHttpRequest { /** * Sets the {@link ClientConnectionRequest} callback that can be * used to abort a long-lived request for a connection. * If the request is already aborted, throws an {@link IOException}. * * @see ClientConnectionManager * @see ThreadSafeClientConnManager */ void setConnectionRequest(ClientConnectionRequest connRequest) throws IOException; /** * Sets the {@link ConnectionReleaseTrigger} callback that can * be used to abort an active connection. * Typically, this will be the {@link ManagedClientConnection} itself. * If the request is already aborted, throws an {@link IOException}. */ void setReleaseTrigger(ConnectionReleaseTrigger releaseTrigger) throws IOException; /** * Aborts this http request. Any active execution of this method should * return immediately. If the request has not started, it will abort after * the next execution. Aborting this request will cause all subsequent * executions with this request to fail. * * @see HttpClient#execute(HttpUriRequest) * @see HttpClient#execute(org.apache.ogt.http.HttpHost, * org.apache.ogt.http.HttpRequest) * @see HttpClient#execute(HttpUriRequest, * org.apache.ogt.http.protocol.HttpContext) * @see HttpClient#execute(org.apache.ogt.http.HttpHost, * org.apache.ogt.http.HttpRequest, org.apache.ogt.http.protocol.HttpContext) */ void abort(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.cookie; import java.util.Date; /** * This interface represents a <code>Set-Cookie</code> response header sent by the * origin server to the HTTP agent in order to maintain a conversational state. * * @since 4.0 */ public interface SetCookie extends Cookie { void setValue(String value); /** * If a user agent (web browser) presents this cookie to a user, the * cookie's purpose will be described using this comment. * * @param comment * * @see #getComment() */ void setComment(String comment); /** * Sets expiration date. * <p><strong>Note:</strong> the object returned by this method is considered * immutable. Changing it (e.g. using setTime()) could result in undefined * behaviour. Do so at your peril.</p> * * @param expiryDate the {@link Date} after which this cookie is no longer valid. * * @see Cookie#getExpiryDate * */ void setExpiryDate (Date expiryDate); /** * Sets the domain attribute. * * @param domain The value of the domain attribute * * @see Cookie#getDomain */ void setDomain(String domain); /** * Sets the path attribute. * * @param path The value of the path attribute * * @see Cookie#getPath * */ void setPath(String path); /** * Sets the secure attribute of the cookie. * <p> * When <tt>true</tt> the cookie should only be sent * using a secure protocol (https). This should only be set when * the cookie's originating server used a secure protocol to set the * cookie's value. * * @param secure The value of the secure attribute * * @see #isSecure() */ void setSecure (boolean secure); /** * Sets the version of the cookie specification to which this * cookie conforms. * * @param version the version of the cookie. * * @see Cookie#getVersion */ void setVersion(int version); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.cookie; /** * ClientCookie extends the standard {@link Cookie} interface with * additional client specific functionality such ability to retrieve * original cookie attributes exactly as they were specified by the * origin server. This is important for generating the <tt>Cookie</tt> * header because some cookie specifications require that the * <tt>Cookie</tt> header should include certain attributes only if * they were specified in the <tt>Set-Cookie</tt> header. * * * @since 4.0 */ public interface ClientCookie extends Cookie { // RFC2109 attributes public static final String VERSION_ATTR = "version"; public static final String PATH_ATTR = "path"; public static final String DOMAIN_ATTR = "domain"; public static final String MAX_AGE_ATTR = "max-age"; public static final String SECURE_ATTR = "secure"; public static final String COMMENT_ATTR = "comment"; public static final String EXPIRES_ATTR = "expires"; // RFC2965 attributes public static final String PORT_ATTR = "port"; public static final String COMMENTURL_ATTR = "commenturl"; public static final String DISCARD_ATTR = "discard"; String getAttribute(String name); boolean containsAttribute(String name); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.cookie; import java.util.Date; /** * Cookie interface represents a token or short packet of state information * (also referred to as "magic-cookie") that the HTTP agent and the target * server can exchange to maintain a session. In its simples form an HTTP * cookie is merely a name / value pair. * * @since 4.0 */ public interface Cookie { /** * Returns the name. * * @return String name The name */ String getName(); /** * Returns the value. * * @return String value The current value. */ String getValue(); /** * Returns the comment describing the purpose of this cookie, or * <tt>null</tt> if no such comment has been defined. * * @return comment */ String getComment(); /** * If a user agent (web browser) presents this cookie to a user, the * cookie's purpose will be described by the information at this URL. */ String getCommentURL(); /** * Returns the expiration {@link Date} of the cookie, or <tt>null</tt> * if none exists. * <p><strong>Note:</strong> the object returned by this method is * considered immutable. Changing it (e.g. using setTime()) could result * in undefined behaviour. Do so at your peril. </p> * @return Expiration {@link Date}, or <tt>null</tt>. */ Date getExpiryDate(); /** * Returns <tt>false</tt> if the cookie should be discarded at the end * of the "session"; <tt>true</tt> otherwise. * * @return <tt>false</tt> if the cookie should be discarded at the end * of the "session"; <tt>true</tt> otherwise */ boolean isPersistent(); /** * Returns domain attribute of the cookie. The value of the Domain * attribute specifies the domain for which the cookie is valid. * * @return the value of the domain attribute. */ String getDomain(); /** * Returns the path attribute of the cookie. The value of the Path * attribute specifies the subset of URLs on the origin server to which * this cookie applies. * * @return The value of the path attribute. */ String getPath(); /** * Get the Port attribute. It restricts the ports to which a cookie * may be returned in a Cookie request header. */ int[] getPorts(); /** * Indicates whether this cookie requires a secure connection. * * @return <code>true</code> if this cookie should only be sent * over secure connections, <code>false</code> otherwise. */ boolean isSecure(); /** * Returns the version of the cookie specification to which this * cookie conforms. * * @return the version of the cookie. */ int getVersion(); /** * Returns true if this cookie has expired. * @param date Current time * * @return <tt>true</tt> if the cookie has expired. */ boolean isExpired(final Date date); }
Java