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.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
/* * ==================================================================== * 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.Locale; import org.apache.ogt.http.annotation.Immutable; /** * CookieOrigin class encapsulates details of an origin server that * are relevant when parsing, validating or matching HTTP cookies. * * @since 4.0 */ @Immutable public final class CookieOrigin { private final String host; private final int port; private final String path; private final boolean secure; public CookieOrigin(final String host, int port, final String path, boolean secure) { super(); if (host == null) { throw new IllegalArgumentException( "Host of origin may not be null"); } if (host.trim().length() == 0) { throw new IllegalArgumentException( "Host of origin may not be blank"); } if (port < 0) { throw new IllegalArgumentException("Invalid port: " + port); } if (path == null) { throw new IllegalArgumentException( "Path of origin may not be null."); } this.host = host.toLowerCase(Locale.ENGLISH); this.port = port; if (path.trim().length() != 0) { this.path = path; } else { this.path = "/"; } this.secure = secure; } public String getHost() { return this.host; } public String getPath() { return this.path; } public int getPort() { return this.port; } public boolean isSecure() { return this.secure; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append('['); if (this.secure) { buffer.append("(secure)"); } buffer.append(this.host); buffer.append(':'); buffer.append(Integer.toString(this.port)); buffer.append(this.path); buffer.append(']'); return buffer.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.cookie; import java.util.List; import org.apache.ogt.http.Header; /** * Defines the cookie management specification. * <p>Cookie management specification must define * <ul> * <li> rules of parsing "Set-Cookie" header * <li> rules of validation of parsed cookies * <li> formatting of "Cookie" header * </ul> * for a given host, port and path of origin * * * @since 4.0 */ public interface CookieSpec { /** * Returns version of the state management this cookie specification * conforms to. * * @return version of the state management specification */ int getVersion(); /** * Parse the <tt>"Set-Cookie"</tt> Header into an array of Cookies. * * <p>This method will not perform the validation of the resultant * {@link Cookie}s</p> * * @see #validate * * @param header the <tt>Set-Cookie</tt> received from the server * @param origin details of the cookie origin * @return an array of <tt>Cookie</tt>s parsed from the header * @throws MalformedCookieException if an exception occurs during parsing */ List<Cookie> parse(Header header, CookieOrigin origin) throws MalformedCookieException; /** * Validate the cookie according to validation rules defined by the * cookie specification. * * @param cookie the Cookie to validate * @param origin details of the cookie origin * @throws MalformedCookieException if the cookie is invalid */ void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException; /** * Determines if a Cookie matches the target location. * * @param cookie the Cookie to be matched * @param origin the target to test against * * @return <tt>true</tt> if the cookie should be submitted with a request * with given attributes, <tt>false</tt> otherwise. */ boolean match(Cookie cookie, CookieOrigin origin); /** * Create <tt>"Cookie"</tt> headers for an array of Cookies. * * @param cookies the Cookies format into a Cookie header * @return a Header for the given Cookies. * @throws IllegalArgumentException if an input parameter is illegal */ List<Header> formatCookies(List<Cookie> cookies); /** * Returns a request header identifying what version of the state management * specification is understood. May be <code>null</code> if the cookie * specification does not support <tt>Cookie2</tt> header. */ Header getVersionHeader(); }
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 org.apache.ogt.http.params.HttpParams; /** * Factory for {@link CookieSpec} implementations. * * @since 4.0 */ public interface CookieSpecFactory { /** * Creates an instance of {@link CookieSpec} using given HTTP parameters. * * @param params HTTP parameters. * * @return cookie spec. */ CookieSpec newInstance(HttpParams params); }
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.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.params.HttpParams; /** * Cookie specification registry that can be used to obtain the corresponding * cookie specification implementation for a given type of type or version of * cookie. * * * @since 4.0 */ @ThreadSafe public final class CookieSpecRegistry { private final ConcurrentHashMap<String,CookieSpecFactory> registeredSpecs; public CookieSpecRegistry() { super(); this.registeredSpecs = new ConcurrentHashMap<String,CookieSpecFactory>(); } /** * Registers a {@link CookieSpecFactory} with the given identifier. * If a specification with the given name already exists it will be overridden. * This nameis the same one used to retrieve the {@link CookieSpecFactory} * from {@link #getCookieSpec(String)}. * * @param name the identifier for this specification * @param factory the {@link CookieSpecFactory} class to register * * @see #getCookieSpec(String) */ public void register(final String name, final CookieSpecFactory factory) { if (name == null) { throw new IllegalArgumentException("Name may not be null"); } if (factory == null) { throw new IllegalArgumentException("Cookie spec factory may not be null"); } registeredSpecs.put(name.toLowerCase(Locale.ENGLISH), factory); } /** * Unregisters the {@link CookieSpecFactory} with the given ID. * * @param id the identifier of the {@link CookieSpec cookie specification} to unregister */ public void unregister(final String id) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } registeredSpecs.remove(id.toLowerCase(Locale.ENGLISH)); } /** * Gets the {@link CookieSpec cookie specification} with the given ID. * * @param name the {@link CookieSpec cookie specification} identifier * @param params the {@link HttpParams HTTP parameters} for the cookie * specification. * * @return {@link CookieSpec cookie specification} * * @throws IllegalStateException if a policy with the given name cannot be found */ public CookieSpec getCookieSpec(final String name, final HttpParams params) throws IllegalStateException { if (name == null) { throw new IllegalArgumentException("Name may not be null"); } CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase(Locale.ENGLISH)); if (factory != null) { return factory.newInstance(params); } else { throw new IllegalStateException("Unsupported cookie spec: " + name); } } /** * Gets the {@link CookieSpec cookie specification} with the given name. * * @param name the {@link CookieSpec cookie specification} identifier * * @return {@link CookieSpec cookie specification} * * @throws IllegalStateException if a policy with the given name cannot be found */ public CookieSpec getCookieSpec(final String name) throws IllegalStateException { return getCookieSpec(name, null); } /** * Obtains a list containing the names of all registered {@link CookieSpec cookie * specs}. * * Note that the DEFAULT policy (if present) is likely to be the same * as one of the other policies, but does not have to be. * * @return list of registered cookie spec names */ public List<String> getSpecNames(){ return new ArrayList<String>(registeredSpecs.keySet()); } /** * Populates the internal collection of registered {@link CookieSpec cookie * specs} with the content of the map passed as a parameter. * * @param map cookie specs */ public void setItems(final Map<String, CookieSpecFactory> map) { if (map == null) { return; } registeredSpecs.clear(); registeredSpecs.putAll(map); } }
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; /** * This interface represents a <code>Set-Cookie2</code> response header sent by the * origin server to the HTTP agent in order to maintain a conversational state. * * @since 4.0 */ public interface SetCookie2 extends SetCookie { /** * 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. */ void setCommentURL(String commentURL); /** * Sets the Port attribute. It restricts the ports to which a cookie * may be returned in a Cookie request header. */ void setPorts(int[] ports); /** * Set the Discard attribute. * * Note: <tt>Discard</tt> attribute overrides <tt>Max-age</tt>. * * @see #isPersistent() */ void setDiscard(boolean discard); }
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.io.Serializable; import java.util.Comparator; import org.apache.ogt.http.annotation.Immutable; /** * This cookie comparator can be used to compare identity of cookies. * <p> * Cookies are considered identical if their names are equal and * their domain attributes match ignoring case. * * @since 4.0 */ @Immutable public class CookieIdentityComparator implements Serializable, Comparator<Cookie> { private static final long serialVersionUID = 4466565437490631532L; public int compare(final Cookie c1, final Cookie c2) { int res = c1.getName().compareTo(c2.getName()); if (res == 0) { // do not differentiate empty and null domains String d1 = c1.getDomain(); if (d1 == null) { d1 = ""; } else if (d1.indexOf('.') == -1) { d1 = d1 + ".local"; } String d2 = c2.getDomain(); if (d2 == null) { d2 = ""; } else if (d2.indexOf('.') == -1) { d2 = d2 + ".local"; } res = d1.compareToIgnoreCase(d2); } if (res == 0) { String p1 = c1.getPath(); if (p1 == null) { p1 = "/"; } String p2 = c2.getPath(); if (p2 == null) { p2 = "/"; } res = p1.compareTo(p2); } return res; } }
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; /** * Constants and static helpers related to the HTTP state management. * * * @since 4.0 */ public interface SM { public static final String COOKIE = "Cookie"; public static final String COOKIE2 = "Cookie2"; public static final String SET_COOKIE = "Set-Cookie"; public static final String SET_COOKIE2 = "Set-Cookie2"; }
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 org.apache.ogt.http.annotation.Immutable; /** * Signals that a cookie violates a restriction imposed by the cookie * specification. * * @since 4.1 */ @Immutable public class CookieRestrictionViolationException extends MalformedCookieException { private static final long serialVersionUID = 7371235577078589013L; /** * Creates a new CookeFormatViolationException with a <tt>null</tt> detail * message. */ public CookieRestrictionViolationException() { super(); } /** * Creates a new CookeRestrictionViolationException with a specified * message string. * * @param message The exception detail message */ public CookieRestrictionViolationException(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.cookie; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.Immutable; /** * Signals that a cookie is in some way invalid or illegal in a given * context * * * @since 4.0 */ @Immutable public class MalformedCookieException extends ProtocolException { private static final long serialVersionUID = -6695462944287282185L; /** * Creates a new MalformedCookieException with a <tt>null</tt> detail message. */ public MalformedCookieException() { super(); } /** * Creates a new MalformedCookieException with a specified message string. * * @param message The exception detail message */ public MalformedCookieException(String message) { super(message); } /** * Creates a new MalformedCookieException 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 MalformedCookieException(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.cookie.params; import java.util.Collection; 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 cookie parameters using Java Beans * conventions. * * @since 4.0 */ @NotThreadSafe public class CookieSpecParamBean extends HttpAbstractParamBean { public CookieSpecParamBean (final HttpParams params) { super(params); } public void setDatePatterns (final Collection <String> patterns) { params.setParameter(CookieSpecPNames.DATE_PATTERNS, patterns); } public void setSingleHeader (final boolean singleHeader) { params.setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, singleHeader); } }
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.params; /** * Parameter names for HTTP cookie management classes. * * @since 4.0 */ public interface CookieSpecPNames { /** * Defines valid date patterns to be used for parsing non-standard * <code>expires</code> attribute. Only required for compatibility * with non-compliant servers that still use <code>expires</code> * defined in the Netscape draft instead of the standard * <code>max-age</code> attribute. * <p> * This parameter expects a value of type {@link java.util.Collection}. * The collection elements must be of type {@link String} compatible * with the syntax of {@link java.text.SimpleDateFormat}. * </p> */ public static final String DATE_PATTERNS = "http.protocol.cookie-datepatterns"; /** * Defines whether cookies should be forced into a single * <code>Cookie</code> request header. Otherwise, each cookie is formatted * as a separate <code>Cookie</code> header. * <p> * This parameter expects a value of type {@link Boolean}. * </p> */ public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header"; }
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.io.Serializable; import java.util.Comparator; import org.apache.ogt.http.annotation.Immutable; /** * This cookie comparator ensures that multiple cookies satisfying * a common criteria are ordered in the <tt>Cookie</tt> header such * that those with more specific Path attributes precede those with * less specific. * * <p> * This comparator assumes that Path attributes of two cookies * path-match a commmon request-URI. Otherwise, the result of the * comparison is undefined. * </p> * * * @since 4.0 */ @Immutable public class CookiePathComparator implements Serializable, Comparator<Cookie> { private static final long serialVersionUID = 7523645369616405818L; private String normalizePath(final Cookie cookie) { String path = cookie.getPath(); if (path == null) { path = "/"; } if (!path.endsWith("/")) { path = path + '/'; } return path; } public int compare(final Cookie c1, final Cookie c2) { String path1 = normalizePath(c1); String path2 = normalizePath(c2); if (path1.equals(path2)) { return 0; } else if (path1.startsWith(path2)) { return -1; } else if (path2.startsWith(path1)) { return 1; } else { // Does not really matter return 0; } } }
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; /** * This interface represents a cookie attribute handler responsible * for parsing, validating, and matching a specific cookie attribute, * such as path, domain, port, etc. * * Different cookie specifications can provide a specific * implementation for this class based on their cookie handling * rules. * * * @since 4.0 */ public interface CookieAttributeHandler { /** * Parse the given cookie attribute value and update the corresponding * {@link org.apache.ogt.http.cookie.Cookie} property. * * @param cookie {@link org.apache.ogt.http.cookie.Cookie} to be updated * @param value cookie attribute value from the cookie response header */ void parse(SetCookie cookie, String value) throws MalformedCookieException; /** * Peforms cookie validation for the given attribute value. * * @param cookie {@link org.apache.ogt.http.cookie.Cookie} to validate * @param origin the cookie source to validate against * @throws MalformedCookieException if cookie validation fails for this attribute */ void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException; /** * Matches the given value (property of the destination host where request is being * submitted) with the corresponding cookie attribute. * * @param cookie {@link org.apache.ogt.http.cookie.Cookie} to match * @param origin the cookie source to match against * @return <tt>true</tt> if the match is successful; <tt>false</tt> otherwise */ boolean match(Cookie cookie, CookieOrigin origin); }
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.auth; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.Immutable; /** * Signals a failure in authentication process * * * @since 4.0 */ @Immutable public class AuthenticationException extends ProtocolException { private static final long serialVersionUID = -6794031905674764776L; /** * Creates a new AuthenticationException with a <tt>null</tt> detail message. */ public AuthenticationException() { super(); } /** * Creates a new AuthenticationException with the specified message. * * @param message the exception detail message */ public AuthenticationException(String message) { super(message); } /** * Creates a new AuthenticationException 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 AuthenticationException(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.auth; import java.security.Principal; /** * This interface represents a set of credentials consisting of a security * principal and a secret (password) that can be used to establish user * identity * * @since 4.0 */ public interface Credentials { Principal getUserPrincipal(); String getPassword(); }
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.auth; import org.apache.ogt.http.annotation.Immutable; /** * Authentication credentials required to respond to a authentication * challenge are invalid * * * @since 4.0 */ @Immutable public class InvalidCredentialsException extends AuthenticationException { private static final long serialVersionUID = -4834003835215460648L; /** * Creates a new InvalidCredentialsException with a <tt>null</tt> detail message. */ public InvalidCredentialsException() { super(); } /** * Creates a new InvalidCredentialsException with the specified message. * * @param message the exception detail message */ public InvalidCredentialsException(String message) { super(message); } /** * Creates a new InvalidCredentialsException 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 InvalidCredentialsException(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.auth; import java.io.Serializable; import java.security.Principal; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.util.LangUtils; /** * Basic user principal used for HTTP authentication * * @since 4.0 */ @Immutable public final class BasicUserPrincipal implements Principal, Serializable { private static final long serialVersionUID = -2266305184969850467L; private final String username; public BasicUserPrincipal(final String username) { super(); if (username == null) { throw new IllegalArgumentException("User name may not be null"); } this.username = username; } public String getName() { return this.username; } @Override public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.username); return hash; } @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof BasicUserPrincipal) { BasicUserPrincipal that = (BasicUserPrincipal) o; if (LangUtils.equals(this.username, that.username)) { return true; } } return false; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("[principal: "); buffer.append(this.username); buffer.append("]"); return buffer.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.auth; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpRequest; /** * This interface represents an abstract challenge-response oriented * authentication scheme. * <p> * An authentication scheme should be able to support the following * functions: * <ul> * <li>Parse and process the challenge sent by the target server * in response to request for a protected resource * <li>Provide its textual designation * <li>Provide its parameters, if available * <li>Provide the realm this authentication scheme is applicable to, * if available * <li>Generate authorization string for the given set of credentials * and the HTTP request in response to the authorization challenge. * </ul> * <p> * Authentication schemes may be stateful involving a series of * challenge-response exchanges. * <p> * IMPORTANT: implementations of this interface MUST also implement {@link ContextAwareAuthScheme} * interface in order to remain API compatible with newer versions of HttpClient. * * @since 4.0 */ public interface AuthScheme { /** * Processes the given challenge token. Some authentication schemes * may involve multiple challenge-response exchanges. Such schemes must be able * to maintain the state information when dealing with sequential challenges * * @param header the challenge header */ void processChallenge(final Header header) throws MalformedChallengeException; /** * Returns textual designation of the given authentication scheme. * * @return the name of the given authentication scheme */ String getSchemeName(); /** * Returns authentication parameter with the given name, if available. * * @param name The name of the parameter to be returned * * @return the parameter with the given name */ String getParameter(final String name); /** * Returns authentication realm. If the concept of an authentication * realm is not applicable to the given authentication scheme, returns * <code>null</code>. * * @return the authentication realm */ String getRealm(); /** * Tests if the authentication scheme is provides authorization on a per * connection basis instead of usual per request basis * * @return <tt>true</tt> if the scheme is connection based, <tt>false</tt> * if the scheme is request based. */ boolean isConnectionBased(); /** * Authentication process may involve a series of challenge-response exchanges. * This method tests if the authorization process has been completed, either * successfully or unsuccessfully, that is, all the required authorization * challenges have been processed in their entirety. * * @return <tt>true</tt> if the authentication process has been completed, * <tt>false</tt> otherwise. */ boolean isComplete(); /** * Produces an authorization string for the given set of {@link Credentials}. * * @param credentials The set of credentials to be used for athentication * @param request The request being authenticated * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return the authorization string * * @deprecated Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.ogt.http.protocol.HttpContext)} */ @Deprecated Header authenticate(Credentials credentials, HttpRequest request) 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.auth; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.params.HttpParams; /** * Authentication scheme registry that can be used to obtain the corresponding * authentication scheme implementation for a given type of authorization challenge. * * @since 4.0 */ @ThreadSafe public final class AuthSchemeRegistry { private final ConcurrentHashMap<String,AuthSchemeFactory> registeredSchemes; public AuthSchemeRegistry() { super(); this.registeredSchemes = new ConcurrentHashMap<String,AuthSchemeFactory>(); } /** * Registers a {@link AuthSchemeFactory} with the given identifier. If a factory with the * given name already exists it will be overridden. This name is the same one used to * retrieve the {@link AuthScheme authentication scheme} from {@link #getAuthScheme}. * * <p> * Please note that custom authentication preferences, if used, need to be updated accordingly * for the new {@link AuthScheme authentication scheme} to take effect. * </p> * * @param name the identifier for this scheme * @param factory the {@link AuthSchemeFactory} class to register * * @see #getAuthScheme */ public void register( final String name, final AuthSchemeFactory factory) { if (name == null) { throw new IllegalArgumentException("Name may not be null"); } if (factory == null) { throw new IllegalArgumentException("Authentication scheme factory may not be null"); } registeredSchemes.put(name.toLowerCase(Locale.ENGLISH), factory); } /** * Unregisters the class implementing an {@link AuthScheme authentication scheme} with * the given name. * * @param name the identifier of the class to unregister */ public void unregister(final String name) { if (name == null) { throw new IllegalArgumentException("Name may not be null"); } registeredSchemes.remove(name.toLowerCase(Locale.ENGLISH)); } /** * Gets the {@link AuthScheme authentication scheme} with the given name. * * @param name the {@link AuthScheme authentication scheme} identifier * @param params the {@link HttpParams HTTP parameters} for the authentication * scheme. * * @return {@link AuthScheme authentication scheme} * * @throws IllegalStateException if a scheme with the given name cannot be found */ public AuthScheme getAuthScheme(final String name, final HttpParams params) throws IllegalStateException { if (name == null) { throw new IllegalArgumentException("Name may not be null"); } AuthSchemeFactory factory = registeredSchemes.get(name.toLowerCase(Locale.ENGLISH)); if (factory != null) { return factory.newInstance(params); } else { throw new IllegalStateException("Unsupported authentication scheme: " + name); } } /** * Obtains a list containing the names of all registered {@link AuthScheme authentication * schemes} * * @return list of registered scheme names */ public List<String> getSchemeNames() { return new ArrayList<String>(registeredSchemes.keySet()); } /** * Populates the internal collection of registered {@link AuthScheme authentication schemes} * with the content of the map passed as a parameter. * * @param map authentication schemes */ public void setItems(final Map<String, AuthSchemeFactory> map) { if (map == null) { return; } registeredSchemes.clear(); registeredSchemes.putAll(map); } }
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.auth; import java.io.Serializable; import java.security.Principal; import java.util.Locale; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.util.LangUtils; /** * Microsoft Windows specific user principal implementation. * * @since 4.0 */ @Immutable public class NTUserPrincipal implements Principal, Serializable { private static final long serialVersionUID = -6870169797924406894L; private final String username; private final String domain; private final String ntname; public NTUserPrincipal( final String domain, final String username) { super(); if (username == null) { throw new IllegalArgumentException("User name may not be null"); } this.username = username; if (domain != null) { this.domain = domain.toUpperCase(Locale.ENGLISH); } else { this.domain = null; } if (this.domain != null && this.domain.length() > 0) { StringBuilder buffer = new StringBuilder(); buffer.append(this.domain); buffer.append('/'); buffer.append(this.username); this.ntname = buffer.toString(); } else { this.ntname = this.username; } } public String getName() { return this.ntname; } public String getDomain() { return this.domain; } public String getUsername() { return this.username; } @Override public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.username); hash = LangUtils.hashCode(hash, this.domain); return hash; } @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof NTUserPrincipal) { NTUserPrincipal that = (NTUserPrincipal) o; if (LangUtils.equals(this.username, that.username) && LangUtils.equals(this.domain, that.domain)) { return true; } } return false; } @Override public String toString() { return this.ntname; } }
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.auth; import org.apache.ogt.http.annotation.Immutable; /** * Constants and static helpers related to the HTTP authentication. * * * @since 4.0 */ @Immutable public final class AUTH { /** * The www authenticate challange header. */ public static final String WWW_AUTH = "WWW-Authenticate"; /** * The www authenticate response header. */ public static final String WWW_AUTH_RESP = "Authorization"; /** * The proxy authenticate challange header. */ public static final String PROXY_AUTH = "Proxy-Authenticate"; /** * The proxy authenticate response header. */ public static final String PROXY_AUTH_RESP = "Proxy-Authorization"; private AUTH() { } }
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.auth; import java.io.Serializable; import java.security.Principal; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.util.LangUtils; /** * Simple {@link Credentials} implementation based on a user name / password * pair. * * @since 4.0 */ @Immutable public class UsernamePasswordCredentials implements Credentials, Serializable { private static final long serialVersionUID = 243343858802739403L; private final BasicUserPrincipal principal; private final String password; /** * The constructor with the username and password combined string argument. * * @param usernamePassword the username:password formed string * @see #toString */ public UsernamePasswordCredentials(String usernamePassword) { super(); if (usernamePassword == null) { throw new IllegalArgumentException("Username:password string may not be null"); } int atColon = usernamePassword.indexOf(':'); if (atColon >= 0) { this.principal = new BasicUserPrincipal(usernamePassword.substring(0, atColon)); this.password = usernamePassword.substring(atColon + 1); } else { this.principal = new BasicUserPrincipal(usernamePassword); this.password = null; } } /** * The constructor with the username and password arguments. * * @param userName the user name * @param password the password */ public UsernamePasswordCredentials(String userName, String password) { super(); if (userName == null) { throw new IllegalArgumentException("Username may not be null"); } this.principal = new BasicUserPrincipal(userName); this.password = password; } public Principal getUserPrincipal() { return this.principal; } public String getUserName() { return this.principal.getName(); } public String getPassword() { return password; } @Override public int hashCode() { return this.principal.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof UsernamePasswordCredentials) { UsernamePasswordCredentials that = (UsernamePasswordCredentials) o; if (LangUtils.equals(this.principal, that.principal)) { return true; } } return false; } @Override public String toString() { return this.principal.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.auth; import org.apache.ogt.http.params.HttpParams; /** * Factory for {@link AuthScheme} implementations. * * @since 4.0 */ public interface AuthSchemeFactory { /** * Creates an instance of {@link AuthScheme} using given HTTP parameters. * * @param params HTTP parameters. * * @return auth scheme. */ AuthScheme newInstance(HttpParams params); }
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.auth; import java.util.Locale; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.util.LangUtils; /** * The class represents an authentication scope consisting of a host name, * a port number, a realm name and an authentication scheme name which * {@link Credentials Credentials} apply to. * * * @since 4.0 */ @Immutable public class AuthScope { /** * The <tt>null</tt> value represents any host. In the future versions of * HttpClient the use of this parameter will be discontinued. */ public static final String ANY_HOST = null; /** * The <tt>-1</tt> value represents any port. */ public static final int ANY_PORT = -1; /** * The <tt>null</tt> value represents any realm. */ public static final String ANY_REALM = null; /** * The <tt>null</tt> value represents any authentication scheme. */ public static final String ANY_SCHEME = null; /** * Default scope matching any host, port, realm and authentication scheme. * In the future versions of HttpClient the use of this parameter will be * discontinued. */ public static final AuthScope ANY = new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME); /** The authentication scheme the credentials apply to. */ private final String scheme; /** The realm the credentials apply to. */ private final String realm; /** The host the credentials apply to. */ private final String host; /** The port the credentials apply to. */ private final int port; /** Creates a new credentials scope for the given * <tt>host</tt>, <tt>port</tt>, <tt>realm</tt>, and * <tt>authentication scheme</tt>. * * @param host the host the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credentials are applicable to * any port. * @param realm the realm the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any realm. * @param scheme the authentication scheme the credentials apply to. * May be set to <tt>null</tt> if credentials are applicable to * any authentication scheme. */ public AuthScope(final String host, int port, final String realm, final String scheme) { this.host = (host == null) ? ANY_HOST: host.toLowerCase(Locale.ENGLISH); this.port = (port < 0) ? ANY_PORT: port; this.realm = (realm == null) ? ANY_REALM: realm; this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase(Locale.ENGLISH); } /** Creates a new credentials scope for the given * <tt>host</tt>, <tt>port</tt>, <tt>realm</tt>, and any * authentication scheme. * * @param host the host the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credentials are applicable to * any port. * @param realm the realm the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any realm. */ public AuthScope(final String host, int port, final String realm) { this(host, port, realm, ANY_SCHEME); } /** Creates a new credentials scope for the given * <tt>host</tt>, <tt>port</tt>, any realm name, and any * authentication scheme. * * @param host the host the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credentials are applicable to * any port. */ public AuthScope(final String host, int port) { this(host, port, ANY_REALM, ANY_SCHEME); } /** * Creates a copy of the given credentials scope. */ public AuthScope(final AuthScope authscope) { super(); if (authscope == null) { throw new IllegalArgumentException("Scope may not be null"); } this.host = authscope.getHost(); this.port = authscope.getPort(); this.realm = authscope.getRealm(); this.scheme = authscope.getScheme(); } /** * @return the host */ public String getHost() { return this.host; } /** * @return the port */ public int getPort() { return this.port; } /** * @return the realm name */ public String getRealm() { return this.realm; } /** * @return the scheme type */ public String getScheme() { return this.scheme; } /** * Tests if the authentication scopes match. * * @return the match factor. Negative value signifies no match. * Non-negative signifies a match. The greater the returned value * the closer the match. */ public int match(final AuthScope that) { int factor = 0; if (LangUtils.equals(this.scheme, that.scheme)) { factor += 1; } else { if (this.scheme != ANY_SCHEME && that.scheme != ANY_SCHEME) { return -1; } } if (LangUtils.equals(this.realm, that.realm)) { factor += 2; } else { if (this.realm != ANY_REALM && that.realm != ANY_REALM) { return -1; } } if (this.port == that.port) { factor += 4; } else { if (this.port != ANY_PORT && that.port != ANY_PORT) { return -1; } } if (LangUtils.equals(this.host, that.host)) { factor += 8; } else { if (this.host != ANY_HOST && that.host != ANY_HOST) { return -1; } } return factor; } /** * @see java.lang.Object#equals(Object) */ @Override public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!(o instanceof AuthScope)) { return super.equals(o); } AuthScope that = (AuthScope) o; return LangUtils.equals(this.host, that.host) && this.port == that.port && LangUtils.equals(this.realm, that.realm) && LangUtils.equals(this.scheme, that.scheme); } /** * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); if (this.scheme != null) { buffer.append(this.scheme.toUpperCase(Locale.ENGLISH)); buffer.append(' '); } if (this.realm != null) { buffer.append('\''); buffer.append(this.realm); buffer.append('\''); } else { buffer.append("<any realm>"); } if (this.host != null) { buffer.append('@'); buffer.append(this.host); if (this.port >= 0) { buffer.append(':'); buffer.append(this.port); } } return buffer.toString(); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.host); hash = LangUtils.hashCode(hash, this.port); hash = LangUtils.hashCode(hash, this.realm); hash = LangUtils.hashCode(hash, this.scheme); return hash; } }
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.auth.params; 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 authentication parameters * using Java Beans conventions. * * @since 4.0 */ public class AuthParamBean extends HttpAbstractParamBean { public AuthParamBean (final HttpParams params) { super(params); } public void setCredentialCharset (final String charset) { AuthParams.setCredentialCharset(params, 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.auth.params; import org.apache.ogt.http.auth.AuthScheme; /** * Parameter names for HTTP authentication classes. * * @since 4.0 */ public interface AuthPNames { /** * Defines the charset to be used when encoding * {@link org.apache.ogt.http.auth.Credentials}. * <p> * This parameter expects a value of type {@link String}. */ public static final String CREDENTIAL_CHARSET = "http.auth.credential-charset"; /** * Defines the order of preference for supported {@link AuthScheme}s when * authenticating with the target host. * <p> * This parameter expects a value of type {@link java.util.Collection}. The * collection is expected to contain {@link String} instances representing * a name of an authentication scheme as returned by * {@link AuthScheme#getSchemeName()}. */ public static final String TARGET_AUTH_PREF = "http.auth.target-scheme-pref"; /** * Defines the order of preference for supported {@link AuthScheme}s when * authenticating with the proxy host. * <p> * This parameter expects a value of type {@link java.util.Collection}. The * collection is expected to contain {@link String} instances representing * a name of an authentication scheme as returned by * {@link AuthScheme#getSchemeName()}. */ public static final String PROXY_AUTH_PREF = "http.auth.proxy-scheme-pref"; }
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.auth.params; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HTTP; /** * An adaptor for manipulating HTTP authentication parameters * in {@link HttpParams}. * * @since 4.0 * * @see AuthPNames */ @Immutable public final class AuthParams { private AuthParams() { super(); } /** * Obtains the charset for encoding * {@link org.apache.ogt.http.auth.Credentials}.If not configured, * {@link HTTP#DEFAULT_PROTOCOL_CHARSET}is used instead. * * @return The charset */ public static String getCredentialCharset(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } String charset = (String) params.getParameter (AuthPNames.CREDENTIAL_CHARSET); if (charset == null) { charset = HTTP.DEFAULT_PROTOCOL_CHARSET; } return charset; } /** * Sets the charset to be used when encoding * {@link org.apache.ogt.http.auth.Credentials}. * * @param charset The charset */ public static void setCredentialCharset(final HttpParams params, final String charset) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setParameter(AuthPNames.CREDENTIAL_CHARSET, 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.auth; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.Immutable; /** * Signals that authentication challenge is in some way invalid or * illegal in the given context * * * @since 4.0 */ @Immutable public class MalformedChallengeException extends ProtocolException { private static final long serialVersionUID = 814586927989932284L; /** * Creates a new MalformedChallengeException with a <tt>null</tt> detail message. */ public MalformedChallengeException() { super(); } /** * Creates a new MalformedChallengeException with the specified message. * * @param message the exception detail message */ public MalformedChallengeException(String message) { super(message); } /** * Creates a new MalformedChallengeException 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 MalformedChallengeException(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.auth; import java.io.Serializable; import java.security.Principal; import java.util.Locale; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.util.LangUtils; /** * {@link Credentials} implementation for Microsoft Windows platforms that includes * Windows specific attributes such as name of the domain the user belongs to. * * @since 4.0 */ @Immutable public class NTCredentials implements Credentials, Serializable { private static final long serialVersionUID = -7385699315228907265L; /** The user principal */ private final NTUserPrincipal principal; /** Password */ private final String password; /** The host the authentication request is originating from. */ private final String workstation; /** * The constructor with the fully qualified username and password combined * string argument. * * @param usernamePassword the domain/username:password formed string */ public NTCredentials(String usernamePassword) { super(); if (usernamePassword == null) { throw new IllegalArgumentException("Username:password string may not be null"); } String username; int atColon = usernamePassword.indexOf(':'); if (atColon >= 0) { username = usernamePassword.substring(0, atColon); this.password = usernamePassword.substring(atColon + 1); } else { username = usernamePassword; this.password = null; } int atSlash = username.indexOf('/'); if (atSlash >= 0) { this.principal = new NTUserPrincipal( username.substring(0, atSlash).toUpperCase(Locale.ENGLISH), username.substring(atSlash + 1)); } else { this.principal = new NTUserPrincipal( null, username.substring(atSlash + 1)); } this.workstation = null; } /** * Constructor. * @param userName The user name. This should not include the domain to authenticate with. * For example: "user" is correct whereas "DOMAIN\\user" is not. * @param password The password. * @param workstation The workstation the authentication request is originating from. * Essentially, the computer name for this machine. * @param domain The domain to authenticate within. */ public NTCredentials( final String userName, final String password, final String workstation, final String domain) { super(); if (userName == null) { throw new IllegalArgumentException("User name may not be null"); } this.principal = new NTUserPrincipal(domain, userName); this.password = password; if (workstation != null) { this.workstation = workstation.toUpperCase(Locale.ENGLISH); } else { this.workstation = null; } } public Principal getUserPrincipal() { return this.principal; } public String getUserName() { return this.principal.getUsername(); } public String getPassword() { return this.password; } /** * Retrieves the name to authenticate with. * * @return String the domain these credentials are intended to authenticate with. */ public String getDomain() { return this.principal.getDomain(); } /** * Retrieves the workstation name of the computer originating the request. * * @return String the workstation the user is logged into. */ public String getWorkstation() { return this.workstation; } @Override public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.principal); hash = LangUtils.hashCode(hash, this.workstation); return hash; } @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof NTCredentials) { NTCredentials that = (NTCredentials) o; if (LangUtils.equals(this.principal, that.principal) && LangUtils.equals(this.workstation, that.workstation)) { return true; } } return false; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("[principal: "); buffer.append(this.principal); buffer.append("][workstation: "); buffer.append(this.workstation); buffer.append("]"); return buffer.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.auth; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.protocol.HttpContext; /** * This interface represents an extended authentication scheme * that requires access to {@link HttpContext} in order to * generate an authorization string. * * TODO: Fix AuthScheme interface in the next major version * * @since 4.1 */ public interface ContextAwareAuthScheme extends AuthScheme { /** * Produces an authorization string for the given set of * {@link Credentials}. * * @param credentials The set of credentials to be used for athentication * @param request The request being authenticated * @param context HTTP context * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return the authorization string */ Header authenticate( Credentials credentials, HttpRequest request, 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.auth; import org.apache.ogt.http.annotation.NotThreadSafe; /** * This class provides detailed information about the state of the * authentication process. * * * @since 4.0 */ @NotThreadSafe public class AuthState { /** Actual authentication scheme */ private AuthScheme authScheme; /** Actual authentication scope */ private AuthScope authScope; /** Credentials selected for authentication */ private Credentials credentials; /** * Default constructor. * */ public AuthState() { super(); } /** * Invalidates the authentication state by resetting its parameters. */ public void invalidate() { this.authScheme = null; this.authScope = null; this.credentials = null; } public boolean isValid() { return this.authScheme != null; } /** * Assigns the given {@link AuthScheme authentication scheme}. * * @param authScheme the {@link AuthScheme authentication scheme} */ public void setAuthScheme(final AuthScheme authScheme) { if (authScheme == null) { invalidate(); return; } this.authScheme = authScheme; } /** * Returns the {@link AuthScheme authentication scheme}. * * @return {@link AuthScheme authentication scheme} */ public AuthScheme getAuthScheme() { return this.authScheme; } /** * Returns user {@link Credentials} selected for authentication if available * * @return user credentials if available, <code>null</code otherwise */ public Credentials getCredentials() { return this.credentials; } /** * Sets user {@link Credentials} to be used for authentication * * @param credentials User credentials */ public void setCredentials(final Credentials credentials) { this.credentials = credentials; } /** * Returns actual {@link AuthScope} if available * * @return actual authentication scope if available, <code>null</code otherwise */ public AuthScope getAuthScope() { return this.authScope; } /** * Sets actual {@link AuthScope}. * * @param authScope Authentication scope */ public void setAuthScope(final AuthScope authScope) { this.authScope = authScope; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("auth scope ["); buffer.append(this.authScope); buffer.append("]; credentials set ["); buffer.append(this.credentials != null ? "true" : "false"); buffer.append("]"); return buffer.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.impl.conn; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.annotation.GuardedBy; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.ClientConnectionOperator; import org.apache.ogt.http.conn.ClientConnectionRequest; import org.apache.ogt.http.conn.ManagedClientConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.conn.routing.RouteTracker; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.params.HttpParams; /** * A connection manager for a single connection. This connection manager * maintains only one active connection at a time. Even though this class * is thread-safe it ought to be used by one execution thread only. * <p> * SingleClientConnManager will make an effort to reuse the connection * for subsequent requests with the same {@link HttpRoute route}. * It will, however, close the existing connection and open it * for the given route, if the route of the persistent connection does * not match that of the connection request. If the connection has been * already been allocated {@link IllegalStateException} is thrown. * * @since 4.0 */ @ThreadSafe public class SingleClientConnManager implements ClientConnectionManager { private final Log log = LogFactory.getLog(getClass()); /** The message to be logged on multiple allocation. */ public final static String MISUSE_MESSAGE = "Invalid use of SingleClientConnManager: connection still allocated.\n" + "Make sure to release the connection before allocating another one."; /** The schemes supported by this connection manager. */ protected final SchemeRegistry schemeRegistry; /** The operator for opening and updating connections. */ protected final ClientConnectionOperator connOperator; /** Whether the connection should be shut down on release. */ protected final boolean alwaysShutDown; /** The one and only entry in this pool. */ @GuardedBy("this") protected PoolEntry uniquePoolEntry; /** The currently issued managed connection, if any. */ @GuardedBy("this") protected ConnAdapter managedConn; /** The time of the last connection release, or -1. */ @GuardedBy("this") protected long lastReleaseTime; /** The time the last released connection expires and shouldn't be reused. */ @GuardedBy("this") protected long connectionExpiresTime; /** Indicates whether this connection manager is shut down. */ protected volatile boolean isShutDown; /** * Creates a new simple connection manager. * * @param params the parameters for this manager * @param schreg the scheme registry * * @deprecated use {@link SingleClientConnManager#SingleClientConnManager(SchemeRegistry)} */ @Deprecated public SingleClientConnManager(HttpParams params, SchemeRegistry schreg) { this(schreg); } /** * Creates a new simple connection manager. * * @param schreg the scheme registry */ public SingleClientConnManager(final SchemeRegistry schreg) { if (schreg == null) { throw new IllegalArgumentException ("Scheme registry must not be null."); } this.schemeRegistry = schreg; this.connOperator = createConnectionOperator(schreg); this.uniquePoolEntry = new PoolEntry(); this.managedConn = null; this.lastReleaseTime = -1L; this.alwaysShutDown = false; //@@@ from params? as argument? this.isShutDown = false; } /** * @since 4.1 */ public SingleClientConnManager() { this(SchemeRegistryFactory.createDefault()); } @Override protected void finalize() throws Throwable { try { shutdown(); } finally { // Make sure we call overridden method even if shutdown barfs super.finalize(); } } public SchemeRegistry getSchemeRegistry() { return this.schemeRegistry; } /** * Hook for creating the connection operator. * It is called by the constructor. * Derived classes can override this method to change the * instantiation of the operator. * The default implementation here instantiates * {@link DefaultClientConnectionOperator DefaultClientConnectionOperator}. * * @param schreg the scheme registry to use, or <code>null</code> * * @return the connection operator to use */ protected ClientConnectionOperator createConnectionOperator(SchemeRegistry schreg) { return new DefaultClientConnectionOperator(schreg); } /** * Asserts that this manager is not shut down. * * @throws IllegalStateException if this manager is shut down */ protected final void assertStillUp() throws IllegalStateException { if (this.isShutDown) throw new IllegalStateException("Manager is shut down."); } public final ClientConnectionRequest requestConnection( final HttpRoute route, final Object state) { return new ClientConnectionRequest() { public void abortRequest() { // Nothing to abort, since requests are immediate. } public ManagedClientConnection getConnection( long timeout, TimeUnit tunit) { return SingleClientConnManager.this.getConnection( route, state); } }; } /** * Obtains a connection. * * @param route where the connection should point to * * @return a connection that can be used to communicate * along the given route */ public synchronized ManagedClientConnection getConnection(HttpRoute route, Object state) { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } assertStillUp(); if (log.isDebugEnabled()) { log.debug("Get connection for route " + route); } if (managedConn != null) throw new IllegalStateException(MISUSE_MESSAGE); // check re-usability of the connection boolean recreate = false; boolean shutdown = false; // Kill the connection if it expired. closeExpiredConnections(); if (uniquePoolEntry.connection.isOpen()) { RouteTracker tracker = uniquePoolEntry.tracker; shutdown = (tracker == null || // can happen if method is aborted !tracker.toRoute().equals(route)); } else { // If the connection is not open, create a new PoolEntry, // as the connection may have been marked not reusable, // due to aborts -- and the PoolEntry should not be reused // either. There's no harm in recreating an entry if // the connection is closed. recreate = true; } if (shutdown) { recreate = true; try { uniquePoolEntry.shutdown(); } catch (IOException iox) { log.debug("Problem shutting down connection.", iox); } } if (recreate) uniquePoolEntry = new PoolEntry(); managedConn = new ConnAdapter(uniquePoolEntry, route); return managedConn; } public synchronized void releaseConnection( ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { assertStillUp(); if (!(conn instanceof ConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } if (log.isDebugEnabled()) { log.debug("Releasing connection " + conn); } ConnAdapter sca = (ConnAdapter) conn; if (sca.poolEntry == null) return; // already released ClientConnectionManager manager = sca.getManager(); if (manager != null && manager != this) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } try { // make sure that the response has been read completely if (sca.isOpen() && (this.alwaysShutDown || !sca.isMarkedReusable()) ) { if (log.isDebugEnabled()) { log.debug ("Released connection open but not reusable."); } // make sure this connection will not be re-used // we might have gotten here because of a shutdown trigger // shutdown of the adapter also clears the tracked route sca.shutdown(); } } catch (IOException iox) { if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { sca.detach(); managedConn = null; lastReleaseTime = System.currentTimeMillis(); if(validDuration > 0) connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime; else connectionExpiresTime = Long.MAX_VALUE; } } public synchronized void closeExpiredConnections() { if(System.currentTimeMillis() >= connectionExpiresTime) { closeIdleConnections(0, TimeUnit.MILLISECONDS); } } public synchronized void closeIdleConnections(long idletime, TimeUnit tunit) { assertStillUp(); // idletime can be 0 or negative, no problem there if (tunit == null) { throw new IllegalArgumentException("Time unit must not be null."); } if ((managedConn == null) && uniquePoolEntry.connection.isOpen()) { final long cutoff = System.currentTimeMillis() - tunit.toMillis(idletime); if (lastReleaseTime <= cutoff) { try { uniquePoolEntry.close(); } catch (IOException iox) { // ignore log.debug("Problem closing idle connection.", iox); } } } } public synchronized void shutdown() { this.isShutDown = true; if (managedConn != null) managedConn.detach(); try { if (uniquePoolEntry != null) // and connection open? uniquePoolEntry.shutdown(); } catch (IOException iox) { // ignore log.debug("Problem while shutting down manager.", iox); } finally { uniquePoolEntry = null; } } /** * @deprecated no longer used */ @Deprecated protected synchronized void revokeConnection() { if (managedConn == null) return; managedConn.detach(); try { uniquePoolEntry.shutdown(); } catch (IOException iox) { // ignore log.debug("Problem while shutting down connection.", iox); } } /** * The pool entry for this connection manager. */ protected class PoolEntry extends AbstractPoolEntry { /** * Creates a new pool entry. * */ protected PoolEntry() { super(SingleClientConnManager.this.connOperator, null); } /** * Closes the connection in this pool entry. */ protected void close() throws IOException { shutdownEntry(); if (connection.isOpen()) connection.close(); } /** * Shuts down the connection in this pool entry. */ protected void shutdown() throws IOException { shutdownEntry(); if (connection.isOpen()) connection.shutdown(); } } /** * The connection adapter used by this manager. */ protected class ConnAdapter extends AbstractPooledConnAdapter { /** * Creates a new connection adapter. * * @param entry the pool entry for the connection being wrapped * @param route the planned route for this connection */ protected ConnAdapter(PoolEntry entry, HttpRoute route) { super(SingleClientConnManager.this, entry); markReusable(); entry.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.impl.conn; import java.io.IOException; import java.net.Socket; import java.util.HashMap; import java.util.Map; 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.HttpResponse; import org.apache.ogt.http.HttpResponseFactory; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.impl.SocketHttpClientConnection; import org.apache.ogt.http.io.HttpMessageParser; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; import org.apache.ogt.http.protocol.HttpContext; /** * Default implementation of an operated client connection. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * </ul> * * @since 4.0 */ @NotThreadSafe // connSecure, targetHost public class DefaultClientConnection extends SocketHttpClientConnection implements OperatedClientConnection, HttpContext { private final Log log = LogFactory.getLog(getClass()); private final Log headerLog = LogFactory.getLog("org.apache.ogt.http.headers"); private final Log wireLog = LogFactory.getLog("org.apache.ogt.http.wire"); /** The unconnected socket */ private volatile Socket socket; /** The target host of this connection. */ private HttpHost targetHost; /** Whether this connection is secure. */ private boolean connSecure; /** True if this connection was shutdown. */ private volatile boolean shutdown; /** connection specific attributes */ private final Map<String, Object> attributes; public DefaultClientConnection() { super(); this.attributes = new HashMap<String, Object>(); } public final HttpHost getTargetHost() { return this.targetHost; } public final boolean isSecure() { return this.connSecure; } @Override public final Socket getSocket() { return this.socket; } public void opening(Socket sock, HttpHost target) throws IOException { assertNotOpen(); this.socket = sock; this.targetHost = target; // Check for shutdown after assigning socket, so that if (this.shutdown) { sock.close(); // allow this to throw... // ...but if it doesn't, explicitly throw one ourselves. throw new IOException("Connection already shutdown"); } } public void openCompleted(boolean secure, HttpParams params) throws IOException { assertNotOpen(); if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } this.connSecure = secure; bind(this.socket, params); } /** * Force-closes this connection. * If the connection is still in the process of being open (the method * {@link #opening opening} was already called but * {@link #openCompleted openCompleted} was not), the associated * socket that is being connected to a remote address will be closed. * That will interrupt a thread that is blocked on connecting * the socket. * If the connection is not yet open, this will prevent the connection * from being opened. * * @throws IOException in case of a problem */ @Override public void shutdown() throws IOException { shutdown = true; try { super.shutdown(); log.debug("Connection shut down"); Socket sock = this.socket; // copy volatile attribute if (sock != null) sock.close(); } catch (IOException ex) { log.debug("I/O error shutting down connection", ex); } } @Override public void close() throws IOException { try { super.close(); log.debug("Connection closed"); } catch (IOException ex) { log.debug("I/O error closing connection", ex); } } @Override protected SessionInputBuffer createSessionInputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { if (buffersize == -1) { buffersize = 8192; } SessionInputBuffer inbuffer = super.createSessionInputBuffer( socket, buffersize, params); if (wireLog.isDebugEnabled()) { inbuffer = new LoggingSessionInputBuffer( inbuffer, new Wire(wireLog), HttpProtocolParams.getHttpElementCharset(params)); } return inbuffer; } @Override protected SessionOutputBuffer createSessionOutputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { if (buffersize == -1) { buffersize = 8192; } SessionOutputBuffer outbuffer = super.createSessionOutputBuffer( socket, buffersize, params); if (wireLog.isDebugEnabled()) { outbuffer = new LoggingSessionOutputBuffer( outbuffer, new Wire(wireLog), HttpProtocolParams.getHttpElementCharset(params)); } return outbuffer; } @Override protected HttpMessageParser createResponseParser( final SessionInputBuffer buffer, final HttpResponseFactory responseFactory, final HttpParams params) { // override in derived class to specify a line parser return new DefaultResponseParser (buffer, null, responseFactory, params); } public void update(Socket sock, HttpHost target, boolean secure, HttpParams params) throws IOException { assertOpen(); if (target == null) { throw new IllegalArgumentException ("Target host must not be null."); } if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } if (sock != null) { this.socket = sock; bind(sock, params); } targetHost = target; connSecure = secure; } @Override public HttpResponse receiveResponseHeader() throws HttpException, IOException { HttpResponse response = super.receiveResponseHeader(); if (log.isDebugEnabled()) { log.debug("Receiving response: " + response.getStatusLine()); } if (headerLog.isDebugEnabled()) { headerLog.debug("<< " + response.getStatusLine().toString()); Header[] headers = response.getAllHeaders(); for (Header header : headers) { headerLog.debug("<< " + header.toString()); } } return response; } @Override public void sendRequestHeader(HttpRequest request) throws HttpException, IOException { if (log.isDebugEnabled()) { log.debug("Sending request: " + request.getRequestLine()); } super.sendRequestHeader(request); if (headerLog.isDebugEnabled()) { headerLog.debug(">> " + request.getRequestLine().toString()); Header[] headers = request.getAllHeaders(); for (Header header : headers) { headerLog.debug(">> " + header.toString()); } } } public Object getAttribute(final String id) { return this.attributes.get(id); } public Object removeAttribute(final String id) { return this.attributes.remove(id); } public void setAttribute(final String id, final Object obj) { this.attributes.put(id, obj); } }
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.impl.conn; 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.HttpMessage; import org.apache.ogt.http.HttpResponseFactory; import org.apache.ogt.http.NoHttpResponseException; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.params.ConnConnectionPNames; import org.apache.ogt.http.impl.io.AbstractMessageParser; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.message.LineParser; import org.apache.ogt.http.message.ParserCursor; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.util.CharArrayBuffer; /** * Default HTTP response parser implementation. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * <li>{@link org.apache.ogt.http.conn.params.ConnConnectionPNames#MAX_STATUS_LINE_GARBAGE}</li> * </ul> * * @since 4.0 */ @ThreadSafe // no public methods public class DefaultResponseParser extends AbstractMessageParser { private final Log log = LogFactory.getLog(getClass()); private final HttpResponseFactory responseFactory; private final CharArrayBuffer lineBuf; private final int maxGarbageLines; public DefaultResponseParser( final SessionInputBuffer buffer, final LineParser parser, final HttpResponseFactory responseFactory, final HttpParams params) { super(buffer, parser, params); if (responseFactory == null) { throw new IllegalArgumentException ("Response factory may not be null"); } this.responseFactory = responseFactory; this.lineBuf = new CharArrayBuffer(128); this.maxGarbageLines = params.getIntParameter( ConnConnectionPNames.MAX_STATUS_LINE_GARBAGE, Integer.MAX_VALUE); } @Override protected HttpMessage parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException { //read out the HTTP status string int count = 0; ParserCursor cursor = null; do { // clear the buffer this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1 && count == 0) { // The server just dropped connection on us throw new NoHttpResponseException("The target server failed to respond"); } cursor = new ParserCursor(0, this.lineBuf.length()); if (lineParser.hasProtocolVersion(this.lineBuf, cursor)) { // Got one break; } else if (i == -1 || count >= this.maxGarbageLines) { // Giving up throw new ProtocolException("The server failed to respond with a " + "valid HTTP response"); } if (this.log.isDebugEnabled()) { this.log.debug("Garbage in response: " + this.lineBuf.toString()); } count++; } while(true); //create the status line from the status string StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); return this.responseFactory.newHttpResponse(statusline, 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.impl.conn; import java.io.IOException; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.io.HttpTransportMetrics; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.CharArrayBuffer; /** * Logs all data written to the wire LOG. * * * @since 4.0 */ @Immutable public class LoggingSessionOutputBuffer implements SessionOutputBuffer { /** Original data transmitter. */ private final SessionOutputBuffer out; /** The wire log to use. */ private final Wire wire; private final String charset; /** * Create an instance that wraps the specified session output buffer. * @param out The session output buffer. * @param wire The Wire log to use. * @param charset protocol charset, <code>ASCII</code> if <code>null</code> */ public LoggingSessionOutputBuffer( final SessionOutputBuffer out, final Wire wire, final String charset) { super(); this.out = out; this.wire = wire; this.charset = charset != null ? charset : HTTP.ASCII; } public LoggingSessionOutputBuffer(final SessionOutputBuffer out, final Wire wire) { this(out, wire, null); } public void write(byte[] b, int off, int len) throws IOException { this.out.write(b, off, len); if (this.wire.enabled()) { this.wire.output(b, off, len); } } public void write(int b) throws IOException { this.out.write(b); if (this.wire.enabled()) { this.wire.output(b); } } public void write(byte[] b) throws IOException { this.out.write(b); if (this.wire.enabled()) { this.wire.output(b); } } public void flush() throws IOException { this.out.flush(); } public void writeLine(final CharArrayBuffer buffer) throws IOException { this.out.writeLine(buffer); if (this.wire.enabled()) { String s = new String(buffer.buffer(), 0, buffer.length()); String tmp = s + "\r\n"; this.wire.output(tmp.getBytes(this.charset)); } } public void writeLine(final String s) throws IOException { this.out.writeLine(s); if (this.wire.enabled()) { String tmp = s + "\r\n"; this.wire.output(tmp.getBytes(this.charset)); } } public HttpTransportMetrics getMetrics() { return this.out.getMetrics(); } }
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.impl.conn; import java.io.IOException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * Abstract adapter from pool {@link AbstractPoolEntry entries} to * {@link org.apache.ogt.http.conn.ManagedClientConnection managed} * client connections. * The connection in the pool entry is used to initialize the base class. * In addition, methods to establish a route are delegated to the * pool entry. {@link #shutdown shutdown} and {@link #close close} * will clear the tracked route in the pool entry and call the * respective method of the wrapped connection. * * @since 4.0 */ public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapter { /** The wrapped pool entry. */ protected volatile AbstractPoolEntry poolEntry; /** * Creates a new connection adapter. * * @param manager the connection manager * @param entry the pool entry for the connection being wrapped */ protected AbstractPooledConnAdapter(ClientConnectionManager manager, AbstractPoolEntry entry) { super(manager, entry.connection); this.poolEntry = entry; } /** * Obtains the pool entry. * * @return the pool entry, or <code>null</code> if detached */ protected AbstractPoolEntry getPoolEntry() { return this.poolEntry; } /** * Asserts that there is a valid pool entry. * * @throws ConnectionShutdownException if there is no pool entry * or connection has been aborted * * @see #assertValid(OperatedClientConnection) */ protected void assertValid(final AbstractPoolEntry entry) { if (isReleased() || entry == null) { throw new ConnectionShutdownException(); } } /** * @deprecated use {@link #assertValid(AbstractPoolEntry)} */ @Deprecated protected final void assertAttached() { if (poolEntry == null) { throw new ConnectionShutdownException(); } } /** * Detaches this adapter from the wrapped connection. * This adapter becomes useless. */ @Override protected synchronized void detach() { poolEntry = null; super.detach(); } public HttpRoute getRoute() { AbstractPoolEntry entry = getPoolEntry(); assertValid(entry); return (entry.tracker == null) ? null : entry.tracker.toRoute(); } public void open(HttpRoute route, HttpContext context, HttpParams params) throws IOException { AbstractPoolEntry entry = getPoolEntry(); assertValid(entry); entry.open(route, context, params); } public void tunnelTarget(boolean secure, HttpParams params) throws IOException { AbstractPoolEntry entry = getPoolEntry(); assertValid(entry); entry.tunnelTarget(secure, params); } public void tunnelProxy(HttpHost next, boolean secure, HttpParams params) throws IOException { AbstractPoolEntry entry = getPoolEntry(); assertValid(entry); entry.tunnelProxy(next, secure, params); } public void layerProtocol(HttpContext context, HttpParams params) throws IOException { AbstractPoolEntry entry = getPoolEntry(); assertValid(entry); entry.layerProtocol(context, params); } public void close() throws IOException { AbstractPoolEntry entry = getPoolEntry(); if (entry != null) entry.shutdownEntry(); OperatedClientConnection conn = getWrappedConnection(); if (conn != null) { conn.close(); } } public void shutdown() throws IOException { AbstractPoolEntry entry = getPoolEntry(); if (entry != null) entry.shutdownEntry(); OperatedClientConnection conn = getWrappedConnection(); if (conn != null) { conn.shutdown(); } } public Object getState() { AbstractPoolEntry entry = getPoolEntry(); assertValid(entry); return entry.getState(); } public void setState(final Object state) { AbstractPoolEntry entry = getPoolEntry(); assertValid(entry); entry.setState(state); } }
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.impl.conn; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.conn.params.ConnRouteParams; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.conn.routing.HttpRoutePlanner; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.protocol.HttpContext; /** * Default implementation of an {@link HttpRoutePlanner}. * This implementation is based on {@link java.net.ProxySelector}. * By default, it will pick up the proxy settings of the JVM, either * from system properties or from the browser running the application. * Additionally, it interprets some * {@link org.apache.ogt.http.conn.params.ConnRoutePNames parameters}, * though not the {@link * org.apache.ogt.http.conn.params.ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li> * </ul> * * @since 4.0 */ @NotThreadSafe // e.g [gs]etProxySelector() public class ProxySelectorRoutePlanner implements HttpRoutePlanner { /** The scheme registry. */ protected final SchemeRegistry schemeRegistry; // @ThreadSafe /** The proxy selector to use, or <code>null</code> for system default. */ protected ProxySelector proxySelector; /** * Creates a new proxy selector route planner. * * @param schreg the scheme registry * @param prosel the proxy selector, or * <code>null</code> for the system default */ public ProxySelectorRoutePlanner(SchemeRegistry schreg, ProxySelector prosel) { if (schreg == null) { throw new IllegalArgumentException ("SchemeRegistry must not be null."); } schemeRegistry = schreg; proxySelector = prosel; } /** * Obtains the proxy selector to use. * * @return the proxy selector, or <code>null</code> for the system default */ public ProxySelector getProxySelector() { return this.proxySelector; } /** * Sets the proxy selector to use. * * @param prosel the proxy selector, or * <code>null</code> to use the system default */ public void setProxySelector(ProxySelector prosel) { this.proxySelector = prosel; } public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (request == null) { throw new IllegalStateException ("Request must not be null."); } // If we have a forced route, we can do without a target. HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) return route; // If we get here, there is no forced route. // So we need a target to compute a route. if (target == null) { throw new IllegalStateException ("Target host must not be null."); } final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams()); final HttpHost proxy = determineProxy(target, request, context); final Scheme schm = this.schemeRegistry.getScheme(target.getSchemeName()); // as it is typically used for TLS/SSL, we assume that // a layered scheme implies a secure connection final boolean secure = schm.isLayered(); if (proxy == null) { route = new HttpRoute(target, local, secure); } else { route = new HttpRoute(target, local, proxy, secure); } return route; } /** * Determines a proxy for the given target. * * @param target the planned target, never <code>null</code> * @param request the request to be sent, never <code>null</code> * @param context the context, or <code>null</code> * * @return the proxy to use, or <code>null</code> for a direct route * * @throws HttpException * in case of system proxy settings that cannot be handled */ protected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { // the proxy selector can be 'unset', so we better deal with null here ProxySelector psel = this.proxySelector; if (psel == null) psel = ProxySelector.getDefault(); if (psel == null) return null; URI targetURI = null; try { targetURI = new URI(target.toURI()); } catch (URISyntaxException usx) { throw new HttpException ("Cannot convert host to URI: " + target, usx); } List<Proxy> proxies = psel.select(targetURI); Proxy p = chooseProxy(proxies, target, request, context); HttpHost result = null; if (p.type() == Proxy.Type.HTTP) { // convert the socket address to an HttpHost if (!(p.address() instanceof InetSocketAddress)) { throw new HttpException ("Unable to handle non-Inet proxy address: "+p.address()); } final InetSocketAddress isa = (InetSocketAddress) p.address(); // assume default scheme (http) result = new HttpHost(getHost(isa), isa.getPort()); } return result; } /** * Obtains a host from an {@link InetSocketAddress}. * * @param isa the socket address * * @return a host string, either as a symbolic name or * as a literal IP address string * <br/> * (TODO: determine format for IPv6 addresses, with or without [brackets]) */ protected String getHost(InetSocketAddress isa) { //@@@ Will this work with literal IPv6 addresses, or do we //@@@ need to wrap these in [] for the string representation? //@@@ Having it in this method at least allows for easy workarounds. return isa.isUnresolved() ? isa.getHostName() : isa.getAddress().getHostAddress(); } /** * Chooses a proxy from a list of available proxies. * The default implementation just picks the first non-SOCKS proxy * from the list. If there are only SOCKS proxies, * {@link Proxy#NO_PROXY Proxy.NO_PROXY} is returned. * Derived classes may implement more advanced strategies, * such as proxy rotation if there are multiple options. * * @param proxies the list of proxies to choose from, * never <code>null</code> or empty * @param target the planned target, never <code>null</code> * @param request the request to be sent, never <code>null</code> * @param context the context, or <code>null</code> * * @return a proxy type */ protected Proxy chooseProxy(List<Proxy> proxies, HttpHost target, HttpRequest request, HttpContext context) { if ((proxies == null) || proxies.isEmpty()) { throw new IllegalArgumentException ("Proxy list must not be empty."); } Proxy result = null; // check the list for one we can use for (int i=0; (result == null) && (i < proxies.size()); i++) { Proxy p = proxies.get(i); switch (p.type()) { case DIRECT: case HTTP: result = p; break; case SOCKS: // SOCKS hosts are not handled on the route level. // The socket may make use of the SOCKS host though. break; } } if (result == null) { //@@@ log as warning or info that only a socks proxy is available? // result can only be null if all proxies are socks proxies // socks proxies are not handled on the route planning level result = Proxy.NO_PROXY; } return result; } }
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.impl.conn; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.scheme.PlainSocketFactory; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.conn.ssl.SSLSocketFactory; /** * @since 4.1 */ @ThreadSafe public final class SchemeRegistryFactory { public static SchemeRegistry createDefault() { SchemeRegistry registry = new SchemeRegistry(); registry.register( new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register( new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); return registry; } }
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.impl.conn; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.HttpConnection; // Currently only used by AbstractConnPool /** * A helper class for connection managers to track idle connections. * * <p>This class is not synchronized.</p> * * @see org.apache.ogt.http.conn.ClientConnectionManager#closeIdleConnections * * @since 4.0 * * @deprecated no longer used */ @Deprecated public class IdleConnectionHandler { private final Log log = LogFactory.getLog(getClass()); /** Holds connections and the time they were added. */ private final Map<HttpConnection,TimeValues> connectionToTimes; public IdleConnectionHandler() { super(); connectionToTimes = new HashMap<HttpConnection,TimeValues>(); } /** * Registers the given connection with this handler. The connection will be held until * {@link #remove} or {@link #closeIdleConnections} is called. * * @param connection the connection to add * * @see #remove */ public void add(HttpConnection connection, long validDuration, TimeUnit unit) { long timeAdded = System.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("Adding connection at: " + timeAdded); } connectionToTimes.put(connection, new TimeValues(timeAdded, validDuration, unit)); } /** * Removes the given connection from the list of connections to be closed when idle. * This will return true if the connection is still valid, and false * if the connection should be considered expired and not used. * * @param connection * @return True if the connection is still valid. */ public boolean remove(HttpConnection connection) { TimeValues times = connectionToTimes.remove(connection); if(times == null) { log.warn("Removing a connection that never existed!"); return true; } else { return System.currentTimeMillis() <= times.timeExpires; } } /** * Removes all connections referenced by this handler. */ public void removeAll() { this.connectionToTimes.clear(); } /** * Closes connections that have been idle for at least the given amount of time. * * @param idleTime the minimum idle time, in milliseconds, for connections to be closed */ public void closeIdleConnections(long idleTime) { // the latest time for which connections will be closed long idleTimeout = System.currentTimeMillis() - idleTime; if (log.isDebugEnabled()) { log.debug("Checking for connections, idle timeout: " + idleTimeout); } for (Entry<HttpConnection, TimeValues> entry : connectionToTimes.entrySet()) { HttpConnection conn = entry.getKey(); TimeValues times = entry.getValue(); long connectionTime = times.timeAdded; if (connectionTime <= idleTimeout) { if (log.isDebugEnabled()) { log.debug("Closing idle connection, connection time: " + connectionTime); } try { conn.close(); } catch (IOException ex) { log.debug("I/O error closing connection", ex); } } } } public void closeExpiredConnections() { long now = System.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("Checking for expired connections, now: " + now); } for (Entry<HttpConnection, TimeValues> entry : connectionToTimes.entrySet()) { HttpConnection conn = entry.getKey(); TimeValues times = entry.getValue(); if(times.timeExpires <= now) { if (log.isDebugEnabled()) { log.debug("Closing connection, expired @: " + times.timeExpires); } try { conn.close(); } catch (IOException ex) { log.debug("I/O error closing connection", ex); } } } } private static class TimeValues { private final long timeAdded; private final long timeExpires; /** * @param now The current time in milliseconds * @param validDuration The duration this connection is valid for * @param validUnit The unit of time the duration is specified in. */ TimeValues(long now, long validDuration, TimeUnit validUnit) { this.timeAdded = now; if(validDuration > 0) { this.timeExpires = now + validUnit.toMillis(validDuration); } else { this.timeExpires = Long.MAX_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.impl.conn.tsccm; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; /** * A worker thread for processing queued references. * {@link Reference Reference}s can be * {@link ReferenceQueue queued} * automatically by the garbage collector. * If that feature is used, a daemon thread should be executing * this worker. It will pick up the queued references and pass them * on to a handler for appropriate processing. * * @deprecated do not use */ @Deprecated public class RefQueueWorker implements Runnable { /** The reference queue to monitor. */ protected final ReferenceQueue<?> refQueue; /** The handler for the references found. */ protected final RefQueueHandler refHandler; /** * The thread executing this handler. * This attribute is also used as a shutdown indicator. */ protected volatile Thread workerThread; /** * Instantiates a new worker to listen for lost connections. * * @param queue the queue on which to wait for references * @param handler the handler to pass the references to */ public RefQueueWorker(ReferenceQueue<?> queue, RefQueueHandler handler) { if (queue == null) { throw new IllegalArgumentException("Queue must not be null."); } if (handler == null) { throw new IllegalArgumentException("Handler must not be null."); } refQueue = queue; refHandler = handler; } /** * The main loop of this worker. * If initialization succeeds, this method will only return * after {@link #shutdown shutdown()}. Only one thread can * execute the main loop at any time. */ public void run() { if (this.workerThread == null) { this.workerThread = Thread.currentThread(); } while (this.workerThread == Thread.currentThread()) { try { // remove the next reference and process it Reference<?> ref = refQueue.remove(); refHandler.handleReference(ref); } catch (InterruptedException ignore) { } } } /** * Shuts down this worker. * It can be re-started afterwards by another call to {@link #run run()}. */ public void shutdown() { Thread wt = this.workerThread; if (wt != null) { this.workerThread = null; // indicate shutdown wt.interrupt(); } } /** * Obtains a description of this worker. * * @return a descriptive string for this worker */ @Override public String toString() { return "RefQueueWorker::" + this.workerThread; } } // class RefQueueWorker
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.impl.conn.tsccm; import java.lang.ref.WeakReference; import java.lang.ref.ReferenceQueue; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.conn.routing.HttpRoute; /** * A weak reference to a {@link BasicPoolEntry BasicPoolEntry}. * This reference explicitly keeps the planned route, so the connection * can be reclaimed if it is lost to garbage collection. * * @since 4.0 */ @Immutable public class BasicPoolEntryRef extends WeakReference<BasicPoolEntry> { /** The planned route of the entry. */ private final HttpRoute route; // HttpRoute is @Immutable /** * Creates a new reference to a pool entry. * * @param entry the pool entry, must not be <code>null</code> * @param queue the reference queue, or <code>null</code> */ public BasicPoolEntryRef(BasicPoolEntry entry, ReferenceQueue<Object> queue) { super(entry, queue); if (entry == null) { throw new IllegalArgumentException ("Pool entry must not be null."); } route = entry.getPlannedRoute(); } /** * Obtain the planned route for the referenced entry. * The planned route is still available, even if the entry is gone. * * @return the planned route */ public final HttpRoute getRoute() { return this.route; } } // class BasicPoolEntryRef
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.impl.conn.tsccm; import java.util.concurrent.TimeUnit; import org.apache.ogt.http.conn.ConnectionPoolTimeoutException; /** * Encapsulates a request for a {@link BasicPoolEntry}. * * @since 4.0 */ public interface PoolEntryRequest { /** * Obtains a pool entry with a connection within the given timeout. * If {@link #abortRequest()} is called before this completes * an {@link InterruptedException} is 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 pool entry holding a connection for the route * * @throws ConnectionPoolTimeoutException * if the timeout expired * @throws InterruptedException * if the calling thread was interrupted or the request was aborted */ BasicPoolEntry getPoolEntry( long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException; /** * Aborts the active or next call to * {@link #getPoolEntry(long, TimeUnit)}. */ 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.impl.conn.tsccm; import java.lang.ref.Reference; /** * @deprecated do not use * * @since 4.0 */ @Deprecated public interface RefQueueHandler { /** * Invoked when a reference is found on the queue. * * @param ref the reference to handle */ public void handleReference(Reference<?> ref) ; }
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.impl.conn.tsccm; import java.util.Date; import java.util.concurrent.locks.Condition; import org.apache.ogt.http.annotation.NotThreadSafe; /** * Represents a thread waiting for a connection. * This class implements throwaway objects. It is instantiated whenever * a thread needs to wait. Instances are not re-used, except if the * waiting thread experiences a spurious wakeup and continues to wait. * <br/> * All methods assume external synchronization on the condition * passed to the constructor. * Instances of this class do <i>not</i> synchronize access! * * * @since 4.0 */ @NotThreadSafe public class WaitingThread { /** The condition on which the thread is waiting. */ private final Condition cond; /** The route specific pool on which the thread is waiting. */ //@@@ replace with generic pool interface private final RouteSpecificPool pool; /** The thread that is waiting for an entry. */ private Thread waiter; /** True if this was interrupted. */ private boolean aborted; /** * Creates a new entry for a waiting thread. * * @param cond the condition for which to wait * @param pool the pool on which the thread will be waiting, * or <code>null</code> */ public WaitingThread(Condition cond, RouteSpecificPool pool) { if (cond == null) { throw new IllegalArgumentException("Condition must not be null."); } this.cond = cond; this.pool = pool; } /** * Obtains the condition. * * @return the condition on which to wait, never <code>null</code> */ public final Condition getCondition() { // not synchronized return this.cond; } /** * Obtains the pool, if there is one. * * @return the pool on which a thread is or was waiting, * or <code>null</code> */ public final RouteSpecificPool getPool() { // not synchronized return this.pool; } /** * Obtains the thread, if there is one. * * @return the thread which is waiting, or <code>null</code> */ public final Thread getThread() { // not synchronized return this.waiter; } /** * Blocks the calling thread. * This method returns when the thread is notified or interrupted, * if a timeout occurrs, or if there is a spurious wakeup. * <br/> * This method assumes external synchronization. * * @param deadline when to time out, or <code>null</code> for no timeout * * @return <code>true</code> if the condition was satisfied, * <code>false</code> in case of a timeout. * Typically, a call to {@link #wakeup} is used to indicate * that the condition was satisfied. Since the condition is * accessible outside, this cannot be guaranteed though. * * @throws InterruptedException if the waiting thread was interrupted * * @see #wakeup */ public boolean await(Date deadline) throws InterruptedException { // This is only a sanity check. We cannot synchronize here, // the lock would not be released on calling cond.await() below. if (this.waiter != null) { throw new IllegalStateException ("A thread is already waiting on this object." + "\ncaller: " + Thread.currentThread() + "\nwaiter: " + this.waiter); } if (aborted) throw new InterruptedException("Operation interrupted"); this.waiter = Thread.currentThread(); boolean success = false; try { if (deadline != null) { success = this.cond.awaitUntil(deadline); } else { this.cond.await(); success = true; } if (aborted) throw new InterruptedException("Operation interrupted"); } finally { this.waiter = null; } return success; } // await /** * Wakes up the waiting thread. * <br/> * This method assumes external synchronization. */ public void wakeup() { // If external synchronization and pooling works properly, // this cannot happen. Just a sanity check. if (this.waiter == null) { throw new IllegalStateException ("Nobody waiting on this object."); } // One condition might be shared by several WaitingThread instances. // It probably isn't, but just in case: wake all, not just one. this.cond.signalAll(); } public void interrupt() { aborted = true; this.cond.signalAll(); } } // class WaitingThread
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.impl.conn.tsccm; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.annotation.GuardedBy; import org.apache.ogt.http.conn.ConnectionPoolTimeoutException; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.impl.conn.IdleConnectionHandler; /** * An abstract connection pool. * It is used by the {@link ThreadSafeClientConnManager}. * The abstract pool includes a {@link #poolLock}, which is used to * synchronize access to the internal pool datastructures. * Don't use <code>synchronized</code> for that purpose! * * @since 4.0 */ @Deprecated public abstract class AbstractConnPool implements RefQueueHandler { private final Log log; /** * The global lock for this pool. */ protected final Lock poolLock; /** References to issued connections */ @GuardedBy("poolLock") protected Set<BasicPoolEntry> leasedConnections; /** The current total number of connections. */ @GuardedBy("poolLock") protected int numConnections; /** Indicates whether this pool is shut down. */ protected volatile boolean isShutDown; protected Set<BasicPoolEntryRef> issuedConnections; protected ReferenceQueue<Object> refQueue; protected IdleConnectionHandler idleConnHandler; /** * Creates a new connection pool. */ protected AbstractConnPool() { super(); this.log = LogFactory.getLog(getClass()); this.leasedConnections = new HashSet<BasicPoolEntry>(); this.idleConnHandler = new IdleConnectionHandler(); this.poolLock = new ReentrantLock(); } public void enableConnectionGC() throws IllegalStateException { } /** * Obtains a pool entry with a connection within the given timeout. * * @param route the route for which to get the connection * @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 pool entry holding a connection for the route * * @throws ConnectionPoolTimeoutException * if the timeout expired * @throws InterruptedException * if the calling thread was interrupted */ public final BasicPoolEntry getEntry( HttpRoute route, Object state, long timeout, TimeUnit tunit) throws ConnectionPoolTimeoutException, InterruptedException { return requestPoolEntry(route, state).getPoolEntry(timeout, tunit); } /** * Returns a new {@link PoolEntryRequest}, from which a {@link BasicPoolEntry} * can be obtained, or the request can be aborted. */ public abstract PoolEntryRequest requestPoolEntry(HttpRoute route, Object state); /** * Returns an entry into the pool. * The connection of the entry is expected to be in a suitable state, * either open and re-usable, or closed. The pool will not make any * attempt to determine whether it can be re-used or not. * * @param entry the entry for the connection to release * @param reusable <code>true</code> if the entry is deemed * reusable, <code>false</code> otherwise. * @param validDuration The duration that the entry should remain free and reusable. * @param timeUnit The unit of time the duration is measured in. */ public abstract void freeEntry(BasicPoolEntry entry, boolean reusable, long validDuration, TimeUnit timeUnit) ; public void handleReference(Reference<?> ref) { } protected abstract void handleLostEntry(HttpRoute route); /** * Closes idle connections. * * @param idletime the time the connections should have been idle * in order to be closed now * @param tunit the unit for the <code>idletime</code> */ public void closeIdleConnections(long idletime, TimeUnit tunit) { // idletime can be 0 or negative, no problem there if (tunit == null) { throw new IllegalArgumentException("Time unit must not be null."); } poolLock.lock(); try { idleConnHandler.closeIdleConnections(tunit.toMillis(idletime)); } finally { poolLock.unlock(); } } public void closeExpiredConnections() { poolLock.lock(); try { idleConnHandler.closeExpiredConnections(); } finally { poolLock.unlock(); } } /** * Deletes all entries for closed connections. */ public abstract void deleteClosedConnections(); /** * Shuts down this pool and all associated resources. * Overriding methods MUST call the implementation here! */ public void shutdown() { poolLock.lock(); try { if (isShutDown) return; // close all connections that are issued to an application Iterator<BasicPoolEntry> iter = leasedConnections.iterator(); while (iter.hasNext()) { BasicPoolEntry entry = iter.next(); iter.remove(); closeConnection(entry.getConnection()); } idleConnHandler.removeAll(); isShutDown = true; } finally { poolLock.unlock(); } } /** * Closes a connection from this pool. * * @param conn the connection to close, or <code>null</code> */ protected void closeConnection(final OperatedClientConnection conn) { if (conn != null) { try { conn.close(); } catch (IOException ex) { log.debug("I/O error closing connection", ex); } } } } // class AbstractConnPool
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.impl.conn.tsccm; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Queue; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.ClientConnectionOperator; import org.apache.ogt.http.conn.ConnectionPoolTimeoutException; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.params.ConnManagerParams; import org.apache.ogt.http.conn.params.ConnPerRoute; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.params.HttpParams; /** * A connection pool that maintains connections by route. * This class is derived from <code>MultiThreadedHttpConnectionManager</code> * in HttpClient 3.x, see there for original authors. It implements the same * algorithm for connection re-use and connection-per-host enforcement: * <ul> * <li>connections are re-used only for the exact same route</li> * <li>connection limits are enforced per route rather than per host</li> * </ul> * Note that access to the pool data structures is synchronized via the * {@link AbstractConnPool#poolLock poolLock} in the base class, * not via <code>synchronized</code> methods. * * @since 4.0 */ @ThreadSafe @SuppressWarnings("deprecation") public class ConnPoolByRoute extends AbstractConnPool { //TODO: remove dependency on AbstractConnPool private final Log log = LogFactory.getLog(getClass()); private final Lock poolLock; /** Connection operator for this pool */ protected final ClientConnectionOperator operator; /** Connections per route lookup */ protected final ConnPerRoute connPerRoute; /** References to issued connections */ protected final Set<BasicPoolEntry> leasedConnections; /** The list of free connections */ protected final Queue<BasicPoolEntry> freeConnections; /** The list of WaitingThreads waiting for a connection */ protected final Queue<WaitingThread> waitingThreads; /** Map of route-specific pools */ protected final Map<HttpRoute, RouteSpecificPool> routeToPool; private final long connTTL; private final TimeUnit connTTLTimeUnit; protected volatile boolean shutdown; protected volatile int maxTotalConnections; protected volatile int numConnections; /** * Creates a new connection pool, managed by route. * * @since 4.1 */ public ConnPoolByRoute( final ClientConnectionOperator operator, final ConnPerRoute connPerRoute, int maxTotalConnections) { this(operator, connPerRoute, maxTotalConnections, -1, TimeUnit.MILLISECONDS); } /** * @since 4.1 */ public ConnPoolByRoute( final ClientConnectionOperator operator, final ConnPerRoute connPerRoute, int maxTotalConnections, long connTTL, final TimeUnit connTTLTimeUnit) { super(); if (operator == null) { throw new IllegalArgumentException("Connection operator may not be null"); } if (connPerRoute == null) { throw new IllegalArgumentException("Connections per route may not be null"); } this.poolLock = super.poolLock; this.leasedConnections = super.leasedConnections; this.operator = operator; this.connPerRoute = connPerRoute; this.maxTotalConnections = maxTotalConnections; this.freeConnections = createFreeConnQueue(); this.waitingThreads = createWaitingThreadQueue(); this.routeToPool = createRouteToPoolMap(); this.connTTL = connTTL; this.connTTLTimeUnit = connTTLTimeUnit; } protected Lock getLock() { return this.poolLock; } /** * Creates a new connection pool, managed by route. * * @deprecated use {@link ConnPoolByRoute#ConnPoolByRoute(ClientConnectionOperator, ConnPerRoute, int)} */ @Deprecated public ConnPoolByRoute(final ClientConnectionOperator operator, final HttpParams params) { this(operator, ConnManagerParams.getMaxConnectionsPerRoute(params), ConnManagerParams.getMaxTotalConnections(params)); } /** * Creates the queue for {@link #freeConnections}. * Called once by the constructor. * * @return a queue */ protected Queue<BasicPoolEntry> createFreeConnQueue() { return new LinkedList<BasicPoolEntry>(); } /** * Creates the queue for {@link #waitingThreads}. * Called once by the constructor. * * @return a queue */ protected Queue<WaitingThread> createWaitingThreadQueue() { return new LinkedList<WaitingThread>(); } /** * Creates the map for {@link #routeToPool}. * Called once by the constructor. * * @return a map */ protected Map<HttpRoute, RouteSpecificPool> createRouteToPoolMap() { return new HashMap<HttpRoute, RouteSpecificPool>(); } /** * Creates a new route-specific pool. * Called by {@link #getRoutePool} when necessary. * * @param route the route * * @return the new pool */ protected RouteSpecificPool newRouteSpecificPool(HttpRoute route) { return new RouteSpecificPool(route, this.connPerRoute); } /** * Creates a new waiting thread. * Called by {@link #getRoutePool} when necessary. * * @param cond the condition to wait for * @param rospl the route specific pool, or <code>null</code> * * @return a waiting thread representation */ protected WaitingThread newWaitingThread(Condition cond, RouteSpecificPool rospl) { return new WaitingThread(cond, rospl); } private void closeConnection(final BasicPoolEntry entry) { OperatedClientConnection conn = entry.getConnection(); if (conn != null) { try { conn.close(); } catch (IOException ex) { log.debug("I/O error closing connection", ex); } } } /** * Get a route-specific pool of available connections. * * @param route the route * @param create whether to create the pool if it doesn't exist * * @return the pool for the argument route, * never <code>null</code> if <code>create</code> is <code>true</code> */ protected RouteSpecificPool getRoutePool(HttpRoute route, boolean create) { RouteSpecificPool rospl = null; poolLock.lock(); try { rospl = routeToPool.get(route); if ((rospl == null) && create) { // no pool for this route yet (or anymore) rospl = newRouteSpecificPool(route); routeToPool.put(route, rospl); } } finally { poolLock.unlock(); } return rospl; } public int getConnectionsInPool(HttpRoute route) { poolLock.lock(); try { // don't allow a pool to be created here! RouteSpecificPool rospl = getRoutePool(route, false); return (rospl != null) ? rospl.getEntryCount() : 0; } finally { poolLock.unlock(); } } public int getConnectionsInPool() { poolLock.lock(); try { return numConnections; } finally { poolLock.unlock(); } } @Override public PoolEntryRequest requestPoolEntry( final HttpRoute route, final Object state) { final WaitingThreadAborter aborter = new WaitingThreadAborter(); return new PoolEntryRequest() { public void abortRequest() { poolLock.lock(); try { aborter.abort(); } finally { poolLock.unlock(); } } public BasicPoolEntry getPoolEntry( long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { return getEntryBlocking(route, state, timeout, tunit, aborter); } }; } /** * Obtains a pool entry with a connection within the given timeout. * If a {@link WaitingThread} is used to block, {@link WaitingThreadAborter#setWaitingThread(WaitingThread)} * must be called before blocking, to allow the thread to be interrupted. * * @param route the route for which to get the connection * @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 * @param aborter an object which can abort a {@link WaitingThread}. * * @return pool entry holding a connection for the route * * @throws ConnectionPoolTimeoutException * if the timeout expired * @throws InterruptedException * if the calling thread was interrupted */ protected BasicPoolEntry getEntryBlocking( HttpRoute route, Object state, long timeout, TimeUnit tunit, WaitingThreadAborter aborter) throws ConnectionPoolTimeoutException, InterruptedException { Date deadline = null; if (timeout > 0) { deadline = new Date (System.currentTimeMillis() + tunit.toMillis(timeout)); } BasicPoolEntry entry = null; poolLock.lock(); try { RouteSpecificPool rospl = getRoutePool(route, true); WaitingThread waitingThread = null; while (entry == null) { if (shutdown) { throw new IllegalStateException("Connection pool shut down"); } if (log.isDebugEnabled()) { log.debug("[" + route + "] total kept alive: " + freeConnections.size() + ", total issued: " + leasedConnections.size() + ", total allocated: " + numConnections + " out of " + maxTotalConnections); } // the cases to check for: // - have a free connection for that route // - allowed to create a free connection for that route // - can delete and replace a free connection for another route // - need to wait for one of the things above to come true entry = getFreeEntry(rospl, state); if (entry != null) { break; } boolean hasCapacity = rospl.getCapacity() > 0; if (log.isDebugEnabled()) { log.debug("Available capacity: " + rospl.getCapacity() + " out of " + rospl.getMaxEntries() + " [" + route + "][" + state + "]"); } if (hasCapacity && numConnections < maxTotalConnections) { entry = createEntry(rospl, operator); } else if (hasCapacity && !freeConnections.isEmpty()) { deleteLeastUsedEntry(); // if least used entry's route was the same as rospl, // rospl is now out of date : we preemptively refresh rospl = getRoutePool(route, true); entry = createEntry(rospl, operator); } else { if (log.isDebugEnabled()) { log.debug("Need to wait for connection" + " [" + route + "][" + state + "]"); } if (waitingThread == null) { waitingThread = newWaitingThread(poolLock.newCondition(), rospl); aborter.setWaitingThread(waitingThread); } boolean success = false; try { rospl.queueThread(waitingThread); waitingThreads.add(waitingThread); success = waitingThread.await(deadline); } finally { // In case of 'success', we were woken up by the // connection pool and should now have a connection // waiting for us, or else we're shutting down. // Just continue in the loop, both cases are checked. rospl.removeThread(waitingThread); waitingThreads.remove(waitingThread); } // check for spurious wakeup vs. timeout if (!success && (deadline != null) && (deadline.getTime() <= System.currentTimeMillis())) { throw new ConnectionPoolTimeoutException ("Timeout waiting for connection"); } } } // while no entry } finally { poolLock.unlock(); } return entry; } @Override public void freeEntry(BasicPoolEntry entry, boolean reusable, long validDuration, TimeUnit timeUnit) { HttpRoute route = entry.getPlannedRoute(); if (log.isDebugEnabled()) { log.debug("Releasing connection" + " [" + route + "][" + entry.getState() + "]"); } poolLock.lock(); try { if (shutdown) { // the pool is shut down, release the // connection's resources and get out of here closeConnection(entry); return; } // no longer issued, we keep a hard reference now leasedConnections.remove(entry); RouteSpecificPool rospl = getRoutePool(route, true); if (reusable) { if (log.isDebugEnabled()) { String s; if (validDuration > 0) { s = "for " + validDuration + " " + timeUnit; } else { s = "indefinitely"; } log.debug("Pooling connection" + " [" + route + "][" + entry.getState() + "]; keep alive " + s); } rospl.freeEntry(entry); entry.updateExpiry(validDuration, timeUnit); freeConnections.add(entry); } else { rospl.dropEntry(); numConnections--; } notifyWaitingThread(rospl); } finally { poolLock.unlock(); } } /** * If available, get a free pool entry for a route. * * @param rospl the route-specific pool from which to get an entry * * @return an available pool entry for the given route, or * <code>null</code> if none is available */ protected BasicPoolEntry getFreeEntry(RouteSpecificPool rospl, Object state) { BasicPoolEntry entry = null; poolLock.lock(); try { boolean done = false; while(!done) { entry = rospl.allocEntry(state); if (entry != null) { if (log.isDebugEnabled()) { log.debug("Getting free connection" + " [" + rospl.getRoute() + "][" + state + "]"); } freeConnections.remove(entry); if (entry.isExpired(System.currentTimeMillis())) { // If the free entry isn't valid anymore, get rid of it // and loop to find another one that might be valid. if (log.isDebugEnabled()) log.debug("Closing expired free connection" + " [" + rospl.getRoute() + "][" + state + "]"); closeConnection(entry); // We use dropEntry instead of deleteEntry because the entry // is no longer "free" (we just allocated it), and deleteEntry // can only be used to delete free entries. rospl.dropEntry(); numConnections--; } else { leasedConnections.add(entry); done = true; } } else { done = true; if (log.isDebugEnabled()) { log.debug("No free connections" + " [" + rospl.getRoute() + "][" + state + "]"); } } } } finally { poolLock.unlock(); } return entry; } /** * Creates a new pool entry. * This method assumes that the new connection will be handed * out immediately. * * @param rospl the route-specific pool for which to create the entry * @param op the operator for creating a connection * * @return the new pool entry for a new connection */ protected BasicPoolEntry createEntry(RouteSpecificPool rospl, ClientConnectionOperator op) { if (log.isDebugEnabled()) { log.debug("Creating new connection [" + rospl.getRoute() + "]"); } // the entry will create the connection when needed BasicPoolEntry entry = new BasicPoolEntry(op, rospl.getRoute(), connTTL, connTTLTimeUnit); poolLock.lock(); try { rospl.createdEntry(entry); numConnections++; leasedConnections.add(entry); } finally { poolLock.unlock(); } return entry; } /** * Deletes a given pool entry. * This closes the pooled connection and removes all references, * so that it can be GCed. * * <p><b>Note:</b> Does not remove the entry from the freeConnections list. * It is assumed that the caller has already handled this step.</p> * <!-- @@@ is that a good idea? or rather fix it? --> * * @param entry the pool entry for the connection to delete */ protected void deleteEntry(BasicPoolEntry entry) { HttpRoute route = entry.getPlannedRoute(); if (log.isDebugEnabled()) { log.debug("Deleting connection" + " [" + route + "][" + entry.getState() + "]"); } poolLock.lock(); try { closeConnection(entry); RouteSpecificPool rospl = getRoutePool(route, true); rospl.deleteEntry(entry); numConnections--; if (rospl.isUnused()) { routeToPool.remove(route); } } finally { poolLock.unlock(); } } /** * Delete an old, free pool entry to make room for a new one. * Used to replace pool entries with ones for a different route. */ protected void deleteLeastUsedEntry() { poolLock.lock(); try { BasicPoolEntry entry = freeConnections.remove(); if (entry != null) { deleteEntry(entry); } else if (log.isDebugEnabled()) { log.debug("No free connection to delete"); } } finally { poolLock.unlock(); } } @Override protected void handleLostEntry(HttpRoute route) { poolLock.lock(); try { RouteSpecificPool rospl = getRoutePool(route, true); rospl.dropEntry(); if (rospl.isUnused()) { routeToPool.remove(route); } numConnections--; notifyWaitingThread(rospl); } finally { poolLock.unlock(); } } /** * Notifies a waiting thread that a connection is available. * This will wake a thread waiting in the specific route pool, * if there is one. * Otherwise, a thread in the connection pool will be notified. * * @param rospl the pool in which to notify, or <code>null</code> */ protected void notifyWaitingThread(RouteSpecificPool rospl) { //@@@ while this strategy provides for best connection re-use, //@@@ is it fair? only do this if the connection is open? // Find the thread we are going to notify. We want to ensure that // each waiting thread is only interrupted once, so we will remove // it from all wait queues before interrupting. WaitingThread waitingThread = null; poolLock.lock(); try { if ((rospl != null) && rospl.hasThread()) { if (log.isDebugEnabled()) { log.debug("Notifying thread waiting on pool" + " [" + rospl.getRoute() + "]"); } waitingThread = rospl.nextThread(); } else if (!waitingThreads.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Notifying thread waiting on any pool"); } waitingThread = waitingThreads.remove(); } else if (log.isDebugEnabled()) { log.debug("Notifying no-one, there are no waiting threads"); } if (waitingThread != null) { waitingThread.wakeup(); } } finally { poolLock.unlock(); } } @Override public void deleteClosedConnections() { poolLock.lock(); try { Iterator<BasicPoolEntry> iter = freeConnections.iterator(); while (iter.hasNext()) { BasicPoolEntry entry = iter.next(); if (!entry.getConnection().isOpen()) { iter.remove(); deleteEntry(entry); } } } finally { poolLock.unlock(); } } /** * Closes idle connections. * * @param idletime the time the connections should have been idle * in order to be closed now * @param tunit the unit for the <code>idletime</code> */ @Override public void closeIdleConnections(long idletime, TimeUnit tunit) { if (tunit == null) { throw new IllegalArgumentException("Time unit must not be null."); } if (idletime < 0) { idletime = 0; } if (log.isDebugEnabled()) { log.debug("Closing connections idle longer than " + idletime + " " + tunit); } // the latest time for which connections will be closed long deadline = System.currentTimeMillis() - tunit.toMillis(idletime); poolLock.lock(); try { Iterator<BasicPoolEntry> iter = freeConnections.iterator(); while (iter.hasNext()) { BasicPoolEntry entry = iter.next(); if (entry.getUpdated() <= deadline) { if (log.isDebugEnabled()) { log.debug("Closing connection last used @ " + new Date(entry.getUpdated())); } iter.remove(); deleteEntry(entry); } } } finally { poolLock.unlock(); } } @Override public void closeExpiredConnections() { log.debug("Closing expired connections"); long now = System.currentTimeMillis(); poolLock.lock(); try { Iterator<BasicPoolEntry> iter = freeConnections.iterator(); while (iter.hasNext()) { BasicPoolEntry entry = iter.next(); if (entry.isExpired(now)) { if (log.isDebugEnabled()) { log.debug("Closing connection expired @ " + new Date(entry.getExpiry())); } iter.remove(); deleteEntry(entry); } } } finally { poolLock.unlock(); } } @Override public void shutdown() { poolLock.lock(); try { if (shutdown) { return; } shutdown = true; // close all connections that are issued to an application Iterator<BasicPoolEntry> iter1 = leasedConnections.iterator(); while (iter1.hasNext()) { BasicPoolEntry entry = iter1.next(); iter1.remove(); closeConnection(entry); } // close all free connections Iterator<BasicPoolEntry> iter2 = freeConnections.iterator(); while (iter2.hasNext()) { BasicPoolEntry entry = iter2.next(); iter2.remove(); if (log.isDebugEnabled()) { log.debug("Closing connection" + " [" + entry.getPlannedRoute() + "][" + entry.getState() + "]"); } closeConnection(entry); } // wake up all waiting threads Iterator<WaitingThread> iwth = waitingThreads.iterator(); while (iwth.hasNext()) { WaitingThread waiter = iwth.next(); iwth.remove(); waiter.wakeup(); } routeToPool.clear(); } finally { poolLock.unlock(); } } /** * since 4.1 */ public void setMaxTotalConnections(int max) { poolLock.lock(); try { maxTotalConnections = max; } finally { poolLock.unlock(); } } /** * since 4.1 */ public int getMaxTotalConnections() { return maxTotalConnections; } }
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.impl.conn.tsccm; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.impl.conn.AbstractPoolEntry; import org.apache.ogt.http.impl.conn.AbstractPooledConnAdapter; /** * A connection wrapper and callback handler. * All connections given out by the manager are wrappers which * can be {@link #detach detach}ed to prevent further use on release. * * @since 4.0 */ public class BasicPooledConnAdapter extends AbstractPooledConnAdapter { /** * Creates a new adapter. * * @param tsccm the connection manager * @param entry the pool entry for the connection being wrapped */ protected BasicPooledConnAdapter(ThreadSafeClientConnManager tsccm, AbstractPoolEntry entry) { super(tsccm, entry); markReusable(); } @Override protected ClientConnectionManager getManager() { // override needed only to make method visible in this package return super.getManager(); } @Override protected AbstractPoolEntry getPoolEntry() { // override needed only to make method visible in this package return super.getPoolEntry(); } @Override protected void detach() { // override needed only to make method visible in this package super.detach(); } }
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.impl.conn.tsccm; import org.apache.ogt.http.annotation.NotThreadSafe; // TODO - only called from ConnPoolByRoute currently; consider adding it as nested class /** * A simple class that can interrupt a {@link WaitingThread}. * * Must be called with the pool lock held. * * @since 4.0 */ @NotThreadSafe public class WaitingThreadAborter { private WaitingThread waitingThread; private boolean aborted; /** * If a waiting thread has been set, interrupts it. */ public void abort() { aborted = true; if (waitingThread != null) waitingThread.interrupt(); } /** * Sets the waiting thread. If this has already been aborted, * the waiting thread is immediately interrupted. * * @param waitingThread The thread to interrupt when aborting. */ public void setWaitingThread(WaitingThread waitingThread) { this.waitingThread = waitingThread; if (aborted) waitingThread.interrupt(); } }
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.impl.conn.tsccm; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.ClientConnectionOperator; import org.apache.ogt.http.conn.ClientConnectionRequest; import org.apache.ogt.http.conn.ConnectionPoolTimeoutException; import org.apache.ogt.http.conn.ManagedClientConnection; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.params.ConnPerRouteBean; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.impl.conn.DefaultClientConnectionOperator; import org.apache.ogt.http.impl.conn.SchemeRegistryFactory; import org.apache.ogt.http.params.HttpParams; /** * Manages a pool of {@link OperatedClientConnection client connections} and * is able to service connection requests from multiple execution threads. * Connections are pooled on a per route basis. A request for a route which * already the manager has persistent connections for available in the pool * will be services by leasing a connection from the pool rather than * creating a brand new connection. * <p> * ThreadSafeClientConnManager maintains a maximum limit of connection on * a per route basis and in total. Per default this implementation will * create no more than than 2 concurrent connections per given route * and no more 20 connections in total. For many real-world applications * these limits may prove too constraining, especially if they use HTTP * as a transport protocol for their services. Connection limits, however, * can be adjusted using HTTP parameters. * * @since 4.0 */ @ThreadSafe public class ThreadSafeClientConnManager implements ClientConnectionManager { private final Log log; /** The schemes supported by this connection manager. */ protected final SchemeRegistry schemeRegistry; // @ThreadSafe @Deprecated protected final AbstractConnPool connectionPool; /** The pool of connections being managed. */ protected final ConnPoolByRoute pool; /** The operator for opening and updating connections. */ protected final ClientConnectionOperator connOperator; // DefaultClientConnectionOperator is @ThreadSafe protected final ConnPerRouteBean connPerRoute; /** * Creates a new thread safe connection manager. * * @param schreg the scheme registry. */ public ThreadSafeClientConnManager(final SchemeRegistry schreg) { this(schreg, -1, TimeUnit.MILLISECONDS); } /** * @since 4.1 */ public ThreadSafeClientConnManager() { this(SchemeRegistryFactory.createDefault()); } /** * Creates a new thread safe connection manager. * * @param schreg the scheme registry. * @param connTTL max connection lifetime, <=0 implies "infinity" * @param connTTLTimeUnit TimeUnit of connTTL * * @since 4.1 */ public ThreadSafeClientConnManager(final SchemeRegistry schreg, long connTTL, TimeUnit connTTLTimeUnit) { super(); if (schreg == null) { throw new IllegalArgumentException("Scheme registry may not be null"); } this.log = LogFactory.getLog(getClass()); this.schemeRegistry = schreg; this.connPerRoute = new ConnPerRouteBean(); this.connOperator = createConnectionOperator(schreg); this.pool = createConnectionPool(connTTL, connTTLTimeUnit) ; this.connectionPool = this.pool; } /** * Creates a new thread safe connection manager. * * @param params the parameters for this manager. * @param schreg the scheme registry. * * @deprecated use {@link ThreadSafeClientConnManager#ThreadSafeClientConnManager(SchemeRegistry)} */ @Deprecated public ThreadSafeClientConnManager(HttpParams params, SchemeRegistry schreg) { if (schreg == null) { throw new IllegalArgumentException("Scheme registry may not be null"); } this.log = LogFactory.getLog(getClass()); this.schemeRegistry = schreg; this.connPerRoute = new ConnPerRouteBean(); this.connOperator = createConnectionOperator(schreg); this.pool = (ConnPoolByRoute) createConnectionPool(params) ; this.connectionPool = this.pool; } @Override protected void finalize() throws Throwable { try { shutdown(); } finally { super.finalize(); } } /** * Hook for creating the connection pool. * * @return the connection pool to use * * @deprecated use #createConnectionPool(long, TimeUnit)) */ @Deprecated protected AbstractConnPool createConnectionPool(final HttpParams params) { return new ConnPoolByRoute(connOperator, params); } /** * Hook for creating the connection pool. * * @return the connection pool to use * * @since 4.1 */ protected ConnPoolByRoute createConnectionPool(long connTTL, TimeUnit connTTLTimeUnit) { return new ConnPoolByRoute(connOperator, connPerRoute, 20, connTTL, connTTLTimeUnit); } /** * Hook for creating the connection operator. * It is called by the constructor. * Derived classes can override this method to change the * instantiation of the operator. * The default implementation here instantiates * {@link DefaultClientConnectionOperator DefaultClientConnectionOperator}. * * @param schreg the scheme registry. * * @return the connection operator to use */ protected ClientConnectionOperator createConnectionOperator(SchemeRegistry schreg) { return new DefaultClientConnectionOperator(schreg);// @ThreadSafe } public SchemeRegistry getSchemeRegistry() { return this.schemeRegistry; } public ClientConnectionRequest requestConnection( final HttpRoute route, final Object state) { final PoolEntryRequest poolRequest = pool.requestPoolEntry( route, state); return new ClientConnectionRequest() { public void abortRequest() { poolRequest.abortRequest(); } public ManagedClientConnection getConnection( long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } if (log.isDebugEnabled()) { log.debug("Get connection: " + route + ", timeout = " + timeout); } BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit); return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry); } }; } public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) { if (!(conn instanceof BasicPooledConnAdapter)) { throw new IllegalArgumentException ("Connection class mismatch, " + "connection not obtained from this manager."); } BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn; if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) { throw new IllegalArgumentException ("Connection not obtained from this manager."); } synchronized (hca) { BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry(); if (entry == null) { return; } try { // make sure that the response has been read completely if (hca.isOpen() && !hca.isMarkedReusable()) { // In MTHCM, there would be a call to // SimpleHttpConnectionManager.finishLastResponse(conn); // Consuming the response is handled outside in 4.0. // make sure this connection will not be re-used // Shut down rather than close, we might have gotten here // because of a shutdown trigger. // Shutdown of the adapter also clears the tracked route. hca.shutdown(); } } catch (IOException iox) { if (log.isDebugEnabled()) log.debug("Exception shutting down released connection.", iox); } finally { boolean reusable = hca.isMarkedReusable(); if (log.isDebugEnabled()) { if (reusable) { log.debug("Released connection is reusable."); } else { log.debug("Released connection is not reusable."); } } hca.detach(); pool.freeEntry(entry, reusable, validDuration, timeUnit); } } } public void shutdown() { log.debug("Shutting down"); pool.shutdown(); } /** * Gets the total number of pooled connections for the given route. * This is the total number of connections that have been created and * are still in use by this connection manager for the route. * This value will not exceed the maximum number of connections per host. * * @param route the route in question * * @return the total number of pooled connections for that route */ public int getConnectionsInPool(final HttpRoute route) { return pool.getConnectionsInPool(route); } /** * Gets the total number of pooled connections. This is the total number of * connections that have been created and are still in use by this connection * manager. This value will not exceed the maximum number of connections * in total. * * @return the total number of pooled connections */ public int getConnectionsInPool() { return pool.getConnectionsInPool(); } public void closeIdleConnections(long idleTimeout, TimeUnit tunit) { if (log.isDebugEnabled()) { log.debug("Closing connections idle longer than " + idleTimeout + " " + tunit); } pool.closeIdleConnections(idleTimeout, tunit); } public void closeExpiredConnections() { log.debug("Closing expired connections"); pool.closeExpiredConnections(); } /** * since 4.1 */ public int getMaxTotal() { return pool.getMaxTotalConnections(); } /** * since 4.1 */ public void setMaxTotal(int max) { pool.setMaxTotalConnections(max); } /** * @since 4.1 */ public int getDefaultMaxPerRoute() { return connPerRoute.getDefaultMaxPerRoute(); } /** * @since 4.1 */ public void setDefaultMaxPerRoute(int max) { connPerRoute.setDefaultMaxPerRoute(max); } /** * @since 4.1 */ public int getMaxForRoute(final HttpRoute route) { return connPerRoute.getMaxForRoute(route); } /** * @since 4.1 */ public void setMaxForRoute(final HttpRoute route, int max) { connPerRoute.setMaxForRoute(route, max); } }
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.impl.conn.tsccm; import java.lang.ref.ReferenceQueue; import java.util.concurrent.TimeUnit; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.conn.ClientConnectionOperator; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.impl.conn.AbstractPoolEntry; /** * Basic implementation of a connection pool entry. * * @since 4.0 */ @NotThreadSafe public class BasicPoolEntry extends AbstractPoolEntry { private final long created; private long updated; private long validUntil; private long expiry; /** * @deprecated do not use */ @Deprecated public BasicPoolEntry(ClientConnectionOperator op, HttpRoute route, ReferenceQueue<Object> queue) { super(op, route); if (route == null) { throw new IllegalArgumentException("HTTP route may not be null"); } this.created = System.currentTimeMillis(); this.validUntil = Long.MAX_VALUE; this.expiry = this.validUntil; } /** * Creates a new pool entry. * * @param op the connection operator * @param route the planned route for the connection */ public BasicPoolEntry(ClientConnectionOperator op, HttpRoute route) { this(op, route, -1, TimeUnit.MILLISECONDS); } /** * Creates a new pool entry with a specified maximum lifetime. * * @param op the connection operator * @param route the planned route for the connection * @param connTTL maximum lifetime of this entry, <=0 implies "infinity" * @param timeunit TimeUnit of connTTL * * @since 4.1 */ public BasicPoolEntry(ClientConnectionOperator op, HttpRoute route, long connTTL, TimeUnit timeunit) { super(op, route); if (route == null) { throw new IllegalArgumentException("HTTP route may not be null"); } this.created = System.currentTimeMillis(); if (connTTL > 0) { this.validUntil = this.created + timeunit.toMillis(connTTL); } else { this.validUntil = Long.MAX_VALUE; } this.expiry = this.validUntil; } protected final OperatedClientConnection getConnection() { return super.connection; } protected final HttpRoute getPlannedRoute() { return super.route; } @Deprecated protected final BasicPoolEntryRef getWeakRef() { return null; } @Override protected void shutdownEntry() { super.shutdownEntry(); } /** * @since 4.1 */ public long getCreated() { return this.created; } /** * @since 4.1 */ public long getUpdated() { return this.updated; } /** * @since 4.1 */ public long getExpiry() { return this.expiry; } public long getValidUntil() { return this.validUntil; } /** * @since 4.1 */ public void updateExpiry(long time, TimeUnit timeunit) { this.updated = System.currentTimeMillis(); long newExpiry; if (time > 0) { newExpiry = this.updated + timeunit.toMillis(time); } else { newExpiry = Long.MAX_VALUE; } this.expiry = Math.min(validUntil, newExpiry); } /** * @since 4.1 */ public boolean isExpired(long now) { return now >= this.expiry; } }
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.impl.conn.tsccm; import java.io.IOException; import java.util.ListIterator; import java.util.Queue; import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.params.ConnPerRoute; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.util.LangUtils; /** * A connection sub-pool for a specific route, used by {@link ConnPoolByRoute}. * The methods in this class are unsynchronized. It is expected that the * containing pool takes care of synchronization. * * @since 4.0 */ @NotThreadSafe // e.g. numEntries, freeEntries, public class RouteSpecificPool { private final Log log = LogFactory.getLog(getClass()); /** The route this pool is for. */ protected final HttpRoute route; //Immutable @Deprecated protected final int maxEntries; /** Connections per route */ protected final ConnPerRoute connPerRoute; /** * The list of free entries. * This list is managed LIFO, to increase idle times and * allow for closing connections that are not really needed. */ protected final LinkedList<BasicPoolEntry> freeEntries; /** The list of threads waiting for this pool. */ protected final Queue<WaitingThread> waitingThreads; /** The number of created entries. */ protected int numEntries; /** * @deprecated use {@link RouteSpecificPool#RouteSpecificPool(HttpRoute, ConnPerRoute)} */ @Deprecated public RouteSpecificPool(HttpRoute route, int maxEntries) { this.route = route; this.maxEntries = maxEntries; this.connPerRoute = new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return RouteSpecificPool.this.maxEntries; } }; this.freeEntries = new LinkedList<BasicPoolEntry>(); this.waitingThreads = new LinkedList<WaitingThread>(); this.numEntries = 0; } /** * Creates a new route-specific pool. * * @param route the route for which to pool * @param connPerRoute the connections per route configuration */ public RouteSpecificPool(HttpRoute route, ConnPerRoute connPerRoute) { this.route = route; this.connPerRoute = connPerRoute; this.maxEntries = connPerRoute.getMaxForRoute(route); this.freeEntries = new LinkedList<BasicPoolEntry>(); this.waitingThreads = new LinkedList<WaitingThread>(); this.numEntries = 0; } /** * Obtains the route for which this pool is specific. * * @return the route */ public final HttpRoute getRoute() { return route; } /** * Obtains the maximum number of entries allowed for this pool. * * @return the max entry number */ public final int getMaxEntries() { return maxEntries; } /** * Indicates whether this pool is unused. * A pool is unused if there is neither an entry nor a waiting thread. * All entries count, not only the free but also the allocated ones. * * @return <code>true</code> if this pool is unused, * <code>false</code> otherwise */ public boolean isUnused() { return (numEntries < 1) && waitingThreads.isEmpty(); } /** * Return remaining capacity of this pool * * @return capacity */ public int getCapacity() { return connPerRoute.getMaxForRoute(route) - numEntries; } /** * Obtains the number of entries. * This includes not only the free entries, but also those that * have been created and are currently issued to an application. * * @return the number of entries for the route of this pool */ public final int getEntryCount() { return numEntries; } /** * Obtains a free entry from this pool, if one is available. * * @return an available pool entry, or <code>null</code> if there is none */ public BasicPoolEntry allocEntry(final Object state) { if (!freeEntries.isEmpty()) { ListIterator<BasicPoolEntry> it = freeEntries.listIterator(freeEntries.size()); while (it.hasPrevious()) { BasicPoolEntry entry = it.previous(); if (entry.getState() == null || LangUtils.equals(state, entry.getState())) { it.remove(); return entry; } } } if (getCapacity() == 0 && !freeEntries.isEmpty()) { BasicPoolEntry entry = freeEntries.remove(); entry.shutdownEntry(); OperatedClientConnection conn = entry.getConnection(); try { conn.close(); } catch (IOException ex) { log.debug("I/O error closing connection", ex); } return entry; } return null; } /** * Returns an allocated entry to this pool. * * @param entry the entry obtained from {@link #allocEntry allocEntry} * or presented to {@link #createdEntry createdEntry} */ public void freeEntry(BasicPoolEntry entry) { if (numEntries < 1) { throw new IllegalStateException ("No entry created for this pool. " + route); } if (numEntries <= freeEntries.size()) { throw new IllegalStateException ("No entry allocated from this pool. " + route); } freeEntries.add(entry); } /** * Indicates creation of an entry for this pool. * The entry will <i>not</i> be added to the list of free entries, * it is only recognized as belonging to this pool now. It can then * be passed to {@link #freeEntry freeEntry}. * * @param entry the entry that was created for this pool */ public void createdEntry(BasicPoolEntry entry) { if (!route.equals(entry.getPlannedRoute())) { throw new IllegalArgumentException ("Entry not planned for this pool." + "\npool: " + route + "\nplan: " + entry.getPlannedRoute()); } numEntries++; } /** * Deletes an entry from this pool. * Only entries that are currently free in this pool can be deleted. * Allocated entries can not be deleted. * * @param entry the entry to delete from this pool * * @return <code>true</code> if the entry was found and deleted, or * <code>false</code> if the entry was not found */ public boolean deleteEntry(BasicPoolEntry entry) { final boolean found = freeEntries.remove(entry); if (found) numEntries--; return found; } /** * Forgets about an entry from this pool. * This method is used to indicate that an entry * {@link #allocEntry allocated} * from this pool has been lost and will not be returned. */ public void dropEntry() { if (numEntries < 1) { throw new IllegalStateException ("There is no entry that could be dropped."); } numEntries--; } /** * Adds a waiting thread. * This pool makes no attempt to match waiting threads with pool entries. * It is the caller's responsibility to check that there is no entry * before adding a waiting thread. * * @param wt the waiting thread */ public void queueThread(WaitingThread wt) { if (wt == null) { throw new IllegalArgumentException ("Waiting thread must not be null."); } this.waitingThreads.add(wt); } /** * Checks whether there is a waiting thread in this pool. * * @return <code>true</code> if there is a waiting thread, * <code>false</code> otherwise */ public boolean hasThread() { return !this.waitingThreads.isEmpty(); } /** * Returns the next thread in the queue. * * @return a waiting thread, or <code>null</code> if there is none */ public WaitingThread nextThread() { return this.waitingThreads.peek(); } /** * Removes a waiting thread, if it is queued. * * @param wt the waiting thread */ public void removeThread(WaitingThread wt) { if (wt == null) return; this.waitingThreads.remove(wt); } } // class RouteSpecificPool
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.impl.conn; import java.io.IOException; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.io.EofSensor; import org.apache.ogt.http.io.HttpTransportMetrics; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.CharArrayBuffer; /** * Logs all data read to the wire LOG. * * * @since 4.0 */ @Immutable public class LoggingSessionInputBuffer implements SessionInputBuffer, EofSensor { /** Original session input buffer. */ private final SessionInputBuffer in; private final EofSensor eofSensor; /** The wire log to use for writing. */ private final Wire wire; private final String charset; /** * Create an instance that wraps the specified session input buffer. * @param in The session input buffer. * @param wire The wire log to use. * @param charset protocol charset, <code>ASCII</code> if <code>null</code> */ public LoggingSessionInputBuffer( final SessionInputBuffer in, final Wire wire, final String charset) { super(); this.in = in; this.eofSensor = in instanceof EofSensor ? (EofSensor) in : null; this.wire = wire; this.charset = charset != null ? charset : HTTP.ASCII; } public LoggingSessionInputBuffer(final SessionInputBuffer in, final Wire wire) { this(in, wire, null); } public boolean isDataAvailable(int timeout) throws IOException { return this.in.isDataAvailable(timeout); } public int read(byte[] b, int off, int len) throws IOException { int l = this.in.read(b, off, len); if (this.wire.enabled() && l > 0) { this.wire.input(b, off, l); } return l; } public int read() throws IOException { int l = this.in.read(); if (this.wire.enabled() && l != -1) { this.wire.input(l); } return l; } public int read(byte[] b) throws IOException { int l = this.in.read(b); if (this.wire.enabled() && l > 0) { this.wire.input(b, 0, l); } return l; } public String readLine() throws IOException { String s = this.in.readLine(); if (this.wire.enabled() && s != null) { String tmp = s + "\r\n"; this.wire.input(tmp.getBytes(this.charset)); } return s; } public int readLine(final CharArrayBuffer buffer) throws IOException { int l = this.in.readLine(buffer); if (this.wire.enabled() && l >= 0) { int pos = buffer.length() - l; String s = new String(buffer.buffer(), pos, l); String tmp = s + "\r\n"; this.wire.input(tmp.getBytes(this.charset)); } return l; } public HttpTransportMetrics getMetrics() { return this.in.getMetrics(); } public boolean isEof() { if (this.eofSensor != null) { return this.eofSensor.isEof(); } else { 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.impl.conn; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.ClientConnectionOperator; import org.apache.ogt.http.conn.ConnectTimeoutException; import org.apache.ogt.http.conn.HttpHostConnectException; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.scheme.LayeredSchemeSocketFactory; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.conn.scheme.SchemeSocketFactory; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * Default implementation of a {@link ClientConnectionOperator}. It uses a {@link SchemeRegistry} * to look up {@link SchemeSocketFactory} objects. * <p> * This connection operator is multihome network aware and will attempt to retry failed connects * against all known IP addresses sequentially until the connect is successful or all known * addresses fail to respond. Please note the same * {@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT} value will be used * for each connection attempt, so in the worst case the total elapsed time before timeout * can be <code>CONNECTION_TIMEOUT * n</code> where <code>n</code> is the number of IP addresses * of the given host. One can disable multihome support by overriding * the {@link #resolveHostname(String)} method and returning only one IP address for the given * host name. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ @ThreadSafe public class DefaultClientConnectionOperator implements ClientConnectionOperator { private final Log log = LogFactory.getLog(getClass()); /** The scheme registry for looking up socket factories. */ protected final SchemeRegistry schemeRegistry; // @ThreadSafe /** * Creates a new client connection operator for the given scheme registry. * * @param schemes the scheme registry */ public DefaultClientConnectionOperator(final SchemeRegistry schemes) { if (schemes == null) { throw new IllegalArgumentException("Scheme registry amy not be null"); } this.schemeRegistry = schemes; } public OperatedClientConnection createConnection() { return new DefaultClientConnection(); } public void openConnection( final OperatedClientConnection conn, final HttpHost target, final InetAddress local, final HttpContext context, final HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (conn.isOpen()) { throw new IllegalStateException("Connection must not be open"); } Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); SchemeSocketFactory sf = schm.getSchemeSocketFactory(); InetAddress[] addresses = resolveHostname(target.getHostName()); int port = schm.resolvePort(target.getPort()); for (int i = 0; i < addresses.length; i++) { InetAddress address = addresses[i]; boolean last = i == addresses.length - 1; Socket sock = sf.createSocket(params); conn.opening(sock, target); InetSocketAddress remoteAddress = new InetSocketAddress(address, port); InetSocketAddress localAddress = null; if (local != null) { localAddress = new InetSocketAddress(local, 0); } if (this.log.isDebugEnabled()) { this.log.debug("Connecting to " + remoteAddress); } try { Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params); if (sock != connsock) { sock = connsock; conn.opening(sock, target); } prepareSocket(sock, context, params); conn.openCompleted(sf.isSecure(sock), params); return; } catch (ConnectException ex) { if (last) { throw new HttpHostConnectException(target, ex); } } catch (ConnectTimeoutException ex) { if (last) { throw ex; } } if (this.log.isDebugEnabled()) { this.log.debug("Connect to " + remoteAddress + " timed out. " + "Connection will be retried using another IP address"); } } } public void updateSecureConnection( final OperatedClientConnection conn, final HttpHost target, final HttpContext context, final HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (!conn.isOpen()) { throw new IllegalStateException("Connection must be open"); } final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); if (!(schm.getSchemeSocketFactory() instanceof LayeredSchemeSocketFactory)) { throw new IllegalArgumentException ("Target scheme (" + schm.getName() + ") must have layered socket factory."); } LayeredSchemeSocketFactory lsf = (LayeredSchemeSocketFactory) schm.getSchemeSocketFactory(); Socket sock; try { sock = lsf.createLayeredSocket( conn.getSocket(), target.getHostName(), target.getPort(), true); } catch (ConnectException ex) { throw new HttpHostConnectException(target, ex); } prepareSocket(sock, context, params); conn.update(sock, target, lsf.isSecure(sock), params); } /** * Performs standard initializations on a newly created socket. * * @param sock the socket to prepare * @param context the context for the connection * @param params the parameters from which to prepare the socket * * @throws IOException in case of an IO problem */ protected void prepareSocket( final Socket sock, final HttpContext context, final HttpParams params) throws IOException { sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); int linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { sock.setSoLinger(linger > 0, linger); } } /** * Resolves the given host name to an array of corresponding IP addresses, based on the * configured name service on the system. * * @param host host name to resolve * @return array of IP addresses * @exception UnknownHostException if no IP address for the host could be determined. * * @since 4.1 */ protected InetAddress[] resolveHostname(final String host) throws UnknownHostException { return InetAddress.getAllByName(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.impl.conn; import org.apache.ogt.http.annotation.Immutable; /** * Signals that the connection has been shut down or released back to the * the connection pool * * @since 4.1 */ @Immutable public class ConnectionShutdownException extends IllegalStateException { private static final long serialVersionUID = 5868657401162844497L; /** * Creates a new ConnectionShutdownException with a <tt>null</tt> detail message. */ public ConnectionShutdownException() { 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.impl.conn; import java.io.IOException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.conn.ClientConnectionOperator; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.conn.routing.RouteTracker; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * A pool entry for use by connection manager implementations. * Pool entries work in conjunction with an * {@link AbstractClientConnAdapter adapter}. * The adapter is handed out to applications that obtain a connection. * The pool entry stores the underlying connection and tracks the * {@link HttpRoute route} established. * The adapter delegates methods for establishing the route to * its pool entry. * <p> * If the managed connections is released or revoked, the adapter * gets disconnected, but the pool entry still contains the * underlying connection and the established route. * * @since 4.0 */ @NotThreadSafe public abstract class AbstractPoolEntry { /** The connection operator. */ protected final ClientConnectionOperator connOperator; /** The underlying connection being pooled or used. */ protected final OperatedClientConnection connection; /** The route for which this entry gets allocated. */ //@@@ currently accessed from connection manager(s) as attribute //@@@ avoid that, derived classes should decide whether update is allowed //@@@ SCCM: yes, TSCCM: no protected volatile HttpRoute route; /** Connection state object */ protected volatile Object state; /** The tracked route, or <code>null</code> before tracking starts. */ protected volatile RouteTracker tracker; /** * Creates a new pool entry. * * @param connOperator the Connection Operator for this entry * @param route the planned route for the connection, * or <code>null</code> */ protected AbstractPoolEntry(ClientConnectionOperator connOperator, HttpRoute route) { super(); if (connOperator == null) { throw new IllegalArgumentException("Connection operator may not be null"); } this.connOperator = connOperator; this.connection = connOperator.createConnection(); this.route = route; this.tracker = null; } /** * Returns the state object associated with this pool entry. * * @return The state object */ public Object getState() { return state; } /** * Assigns a state object to this pool entry. * * @param state The state object */ public void setState(final Object state) { this.state = state; } /** * Opens the underlying connection. * * @param route the route along which to open the connection * @param context the context for opening the connection * @param params the parameters for opening the connection * * @throws IOException in case of a problem */ public void open(HttpRoute route, HttpContext context, HttpParams params) throws IOException { if (route == null) { throw new IllegalArgumentException ("Route must not be null."); } if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } if ((this.tracker != null) && this.tracker.isConnected()) { throw new IllegalStateException("Connection already open."); } // - collect the arguments // - call the operator // - update the tracking data // In this order, we can be sure that only a successful // opening of the connection will be tracked. this.tracker = new RouteTracker(route); final HttpHost proxy = route.getProxyHost(); connOperator.openConnection (this.connection, (proxy != null) ? proxy : route.getTargetHost(), route.getLocalAddress(), context, params); RouteTracker localTracker = tracker; // capture volatile // If this tracker was reset while connecting, // fail early. if (localTracker == null) { throw new IOException("Request aborted"); } if (proxy == null) { localTracker.connectTarget(this.connection.isSecure()); } else { localTracker.connectProxy(proxy, this.connection.isSecure()); } } /** * Tracks tunnelling of the connection to the target. * The tunnel has to be established outside by sending a CONNECT * request to the (last) proxy. * * @param secure <code>true</code> if the tunnel should be * considered secure, <code>false</code> otherwise * @param params the parameters for tunnelling the connection * * @throws IOException in case of a problem */ public void tunnelTarget(boolean secure, HttpParams params) throws IOException { if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } if ((this.tracker == null) || !this.tracker.isConnected()) { throw new IllegalStateException("Connection not open."); } if (this.tracker.isTunnelled()) { throw new IllegalStateException ("Connection is already tunnelled."); } this.connection.update(null, tracker.getTargetHost(), secure, params); this.tracker.tunnelTarget(secure); } /** * Tracks tunnelling of the connection to a chained proxy. * The tunnel has to be established outside by sending a CONNECT * request to the previous proxy. * * @param next the proxy to which the tunnel was established. * See {@link org.apache.ogt.http.conn.ManagedClientConnection#tunnelProxy * ManagedClientConnection.tunnelProxy} * for details. * @param secure <code>true</code> if the tunnel should be * considered secure, <code>false</code> otherwise * @param params the parameters for tunnelling the connection * * @throws IOException in case of a problem */ public void tunnelProxy(HttpHost next, boolean secure, HttpParams params) throws IOException { if (next == null) { throw new IllegalArgumentException ("Next proxy must not be null."); } if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } //@@@ check for proxy in planned route? if ((this.tracker == null) || !this.tracker.isConnected()) { throw new IllegalStateException("Connection not open."); } this.connection.update(null, next, secure, params); this.tracker.tunnelProxy(next, secure); } /** * Layers a protocol on top of an established tunnel. * * @param context the context for layering * @param params the parameters for layering * * @throws IOException in case of a problem */ public void layerProtocol(HttpContext context, HttpParams params) throws IOException { //@@@ is context allowed to be null? depends on operator? if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } if ((this.tracker == null) || !this.tracker.isConnected()) { throw new IllegalStateException("Connection not open."); } if (!this.tracker.isTunnelled()) { //@@@ allow this? throw new IllegalStateException ("Protocol layering without a tunnel not supported."); } if (this.tracker.isLayered()) { throw new IllegalStateException ("Multiple protocol layering not supported."); } // - collect the arguments // - call the operator // - update the tracking data // In this order, we can be sure that only a successful // layering on top of the connection will be tracked. final HttpHost target = tracker.getTargetHost(); connOperator.updateSecureConnection(this.connection, target, context, params); this.tracker.layerProtocol(this.connection.isSecure()); } /** * Shuts down the entry. * * If {@link #open(HttpRoute, HttpContext, HttpParams)} is in progress, * this will cause that open to possibly throw an {@link IOException}. */ protected void shutdownEntry() { tracker = null; state = 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.impl.conn; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.net.Socket; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSession; import org.apache.ogt.http.HttpConnectionMetrics; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.ManagedClientConnection; import org.apache.ogt.http.conn.OperatedClientConnection; import org.apache.ogt.http.protocol.HttpContext; /** * Abstract adapter from {@link OperatedClientConnection operated} to * {@link ManagedClientConnection managed} client connections. * Read and write methods are delegated to the wrapped connection. * Operations affecting the connection state have to be implemented * by derived classes. Operations for querying the connection state * are delegated to the wrapped connection if there is one, or * return a default value if there is none. * <p> * This adapter tracks the checkpoints for reusable communication states, * as indicated by {@link #markReusable markReusable} and queried by * {@link #isMarkedReusable isMarkedReusable}. * All send and receive operations will automatically clear the mark. * <p> * Connection release calls are delegated to the connection manager, * if there is one. {@link #abortConnection abortConnection} will * clear the reusability mark first. The connection manager is * expected to tolerate multiple calls to the release method. * * @since 4.0 */ public abstract class AbstractClientConnAdapter implements ManagedClientConnection, HttpContext { /** * The connection manager, if any. * This attribute MUST NOT be final, so the adapter can be detached * from the connection manager without keeping a hard reference there. */ private volatile ClientConnectionManager connManager; /** The wrapped connection. */ private volatile OperatedClientConnection wrappedConnection; /** The reusability marker. */ private volatile boolean markedReusable; /** True if the connection has been shut down or released. */ private volatile boolean released; /** The duration this is valid for while idle (in ms). */ private volatile long duration; /** * Creates a new connection adapter. * The adapter is initially <i>not</i> * {@link #isMarkedReusable marked} as reusable. * * @param mgr the connection manager, or <code>null</code> * @param conn the connection to wrap, or <code>null</code> */ protected AbstractClientConnAdapter(ClientConnectionManager mgr, OperatedClientConnection conn) { super(); connManager = mgr; wrappedConnection = conn; markedReusable = false; released = false; duration = Long.MAX_VALUE; } /** * Detaches this adapter from the wrapped connection. * This adapter becomes useless. */ protected synchronized void detach() { wrappedConnection = null; connManager = null; // base class attribute duration = Long.MAX_VALUE; } protected OperatedClientConnection getWrappedConnection() { return wrappedConnection; } protected ClientConnectionManager getManager() { return connManager; } /** * @deprecated use {@link #assertValid(OperatedClientConnection)} */ @Deprecated protected final void assertNotAborted() throws InterruptedIOException { if (isReleased()) { throw new InterruptedIOException("Connection has been shut down"); } } /** * @since 4.1 * @return value of released flag */ protected boolean isReleased() { return released; } /** * Asserts that there is a valid wrapped connection to delegate to. * * @throws ConnectionShutdownException if there is no wrapped connection * or connection has been aborted */ protected final void assertValid( final OperatedClientConnection wrappedConn) throws ConnectionShutdownException { if (isReleased() || wrappedConn == null) { throw new ConnectionShutdownException(); } } public boolean isOpen() { OperatedClientConnection conn = getWrappedConnection(); if (conn == null) return false; return conn.isOpen(); } public boolean isStale() { if (isReleased()) return true; OperatedClientConnection conn = getWrappedConnection(); if (conn == null) return true; return conn.isStale(); } public void setSocketTimeout(int timeout) { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); conn.setSocketTimeout(timeout); } public int getSocketTimeout() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.getSocketTimeout(); } public HttpConnectionMetrics getMetrics() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.getMetrics(); } public void flush() throws IOException { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); conn.flush(); } public boolean isResponseAvailable(int timeout) throws IOException { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.isResponseAvailable(timeout); } public void receiveResponseEntity(HttpResponse response) throws HttpException, IOException { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); unmarkReusable(); conn.receiveResponseEntity(response); } public HttpResponse receiveResponseHeader() throws HttpException, IOException { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); unmarkReusable(); return conn.receiveResponseHeader(); } public void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); unmarkReusable(); conn.sendRequestEntity(request); } public void sendRequestHeader(HttpRequest request) throws HttpException, IOException { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); unmarkReusable(); conn.sendRequestHeader(request); } public InetAddress getLocalAddress() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.getLocalAddress(); } public int getLocalPort() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.getLocalPort(); } public InetAddress getRemoteAddress() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.getRemoteAddress(); } public int getRemotePort() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.getRemotePort(); } public boolean isSecure() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); return conn.isSecure(); } public SSLSession getSSLSession() { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); if (!isOpen()) return null; SSLSession result = null; Socket sock = conn.getSocket(); if (sock instanceof SSLSocket) { result = ((SSLSocket)sock).getSession(); } return result; } public void markReusable() { markedReusable = true; } public void unmarkReusable() { markedReusable = false; } public boolean isMarkedReusable() { return markedReusable; } public void setIdleDuration(long duration, TimeUnit unit) { if(duration > 0) { this.duration = unit.toMillis(duration); } else { this.duration = -1; } } public synchronized void releaseConnection() { if (released) { return; } released = true; if (connManager != null) { connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS); } } public synchronized void abortConnection() { if (released) { return; } released = true; unmarkReusable(); try { shutdown(); } catch (IOException ignore) { } if (connManager != null) { connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS); } } public synchronized Object getAttribute(final String id) { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); if (conn instanceof HttpContext) { return ((HttpContext) conn).getAttribute(id); } else { return null; } } public synchronized Object removeAttribute(final String id) { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); if (conn instanceof HttpContext) { return ((HttpContext) conn).removeAttribute(id); } else { return null; } } public synchronized void setAttribute(final String id, final Object obj) { OperatedClientConnection conn = getWrappedConnection(); assertValid(conn); if (conn instanceof HttpContext) { ((HttpContext) conn).setAttribute(id, obj); } } }
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.impl.conn; import java.net.InetAddress; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.conn.params.ConnRouteParams; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.conn.routing.HttpRoutePlanner; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.protocol.HttpContext; /** * Default implementation of an {@link HttpRoutePlanner}. This implementation * is based on {@link org.apache.ogt.http.conn.params.ConnRoutePNames parameters}. * It will not make use of any Java system properties, nor of system or * browser proxy settings. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li> * </ul> * * @since 4.0 */ @ThreadSafe public class DefaultHttpRoutePlanner implements HttpRoutePlanner { /** The scheme registry. */ protected final SchemeRegistry schemeRegistry; // class is @ThreadSafe /** * Creates a new default route planner. * * @param schreg the scheme registry */ public DefaultHttpRoutePlanner(SchemeRegistry schreg) { if (schreg == null) { throw new IllegalArgumentException ("SchemeRegistry must not be null."); } schemeRegistry = schreg; } public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (request == null) { throw new IllegalStateException ("Request must not be null."); } // If we have a forced route, we can do without a target. HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) return route; // If we get here, there is no forced route. // So we need a target to compute a route. if (target == null) { throw new IllegalStateException ("Target host must not be null."); } final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams()); final HttpHost proxy = ConnRouteParams.getDefaultProxy(request.getParams()); final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); // as it is typically used for TLS/SSL, we assume that // a layered scheme implies a secure connection final boolean secure = schm.isLayered(); if (proxy == null) { route = new HttpRoute(target, local, secure); } else { route = new HttpRoute(target, local, proxy, secure); } return 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.impl.conn; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayInputStream; import org.apache.ogt.http.annotation.Immutable; import org.apache.commons.logging.Log; /** * Logs data to the wire LOG. * * * @since 4.0 */ @Immutable public class Wire { private final Log log; public Wire(Log log) { this.log = log; } private void wire(String header, InputStream instream) throws IOException { StringBuilder buffer = new StringBuilder(); int ch; while ((ch = instream.read()) != -1) { if (ch == 13) { buffer.append("[\\r]"); } else if (ch == 10) { buffer.append("[\\n]\""); buffer.insert(0, "\""); buffer.insert(0, header); log.debug(buffer.toString()); buffer.setLength(0); } else if ((ch < 32) || (ch > 127)) { buffer.append("[0x"); buffer.append(Integer.toHexString(ch)); buffer.append("]"); } else { buffer.append((char) ch); } } if (buffer.length() > 0) { buffer.append('\"'); buffer.insert(0, '\"'); buffer.insert(0, header); log.debug(buffer.toString()); } } public boolean enabled() { return log.isDebugEnabled(); } public void output(InputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output may not be null"); } wire(">> ", outstream); } public void input(InputStream instream) throws IOException { if (instream == null) { throw new IllegalArgumentException("Input may not be null"); } wire("<< ", instream); } public void output(byte[] b, int off, int len) throws IOException { if (b == null) { throw new IllegalArgumentException("Output may not be null"); } wire(">> ", new ByteArrayInputStream(b, off, len)); } public void input(byte[] b, int off, int len) throws IOException { if (b == null) { throw new IllegalArgumentException("Input may not be null"); } wire("<< ", new ByteArrayInputStream(b, off, len)); } public void output(byte[] b) throws IOException { if (b == null) { throw new IllegalArgumentException("Output may not be null"); } wire(">> ", new ByteArrayInputStream(b)); } public void input(byte[] b) throws IOException { if (b == null) { throw new IllegalArgumentException("Input may not be null"); } wire("<< ", new ByteArrayInputStream(b)); } public void output(int b) throws IOException { output(new byte[] {(byte) b}); } public void input(int b) throws IOException { input(new byte[] {(byte) b}); } @Deprecated public void output(final String s) throws IOException { if (s == null) { throw new IllegalArgumentException("Output may not be null"); } output(s.getBytes()); } @Deprecated public void input(final String s) throws IOException { if (s == null) { throw new IllegalArgumentException("Input may not be null"); } input(s.getBytes()); } }
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.impl.client; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.annotation.Immutable; /** * Signals that the tunnel request was rejected by the proxy host. * * @since 4.0 */ @Immutable public class TunnelRefusedException extends HttpException { private static final long serialVersionUID = -8646722842745617323L; private final HttpResponse response; public TunnelRefusedException(final String message, final HttpResponse response) { super(message); this.response = response; } public HttpResponse getResponse() { return this.response; } }
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.impl.client; import java.util.HashMap; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.auth.AuthScheme; import org.apache.ogt.http.client.AuthCache; /** * Default implementation of {@link AuthCache}. * * @since 4.0 */ @NotThreadSafe public class BasicAuthCache implements AuthCache { private final HashMap<HttpHost, AuthScheme> map; /** * Default constructor. */ public BasicAuthCache() { super(); this.map = new HashMap<HttpHost, AuthScheme>(); } public void put(final HttpHost host, final AuthScheme authScheme) { if (host == null) { throw new IllegalArgumentException("HTTP host may not be null"); } this.map.put(host, authScheme); } public AuthScheme get(final HttpHost host) { if (host == null) { throw new IllegalArgumentException("HTTP host may not be null"); } return this.map.get(host); } public void remove(final HttpHost host) { if (host == null) { throw new IllegalArgumentException("HTTP host may not be null"); } this.map.remove(host); } public void clear() { this.map.clear(); } @Override public String toString() { return this.map.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.impl.client; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.Credentials; import org.apache.ogt.http.client.CredentialsProvider; /** * Default implementation of {@link CredentialsProvider}. * * @since 4.0 */ @ThreadSafe public class BasicCredentialsProvider implements CredentialsProvider { private final ConcurrentHashMap<AuthScope, Credentials> credMap; /** * Default constructor. */ public BasicCredentialsProvider() { super(); this.credMap = new ConcurrentHashMap<AuthScope, Credentials>(); } public void setCredentials( final AuthScope authscope, final Credentials credentials) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } credMap.put(authscope, credentials); } /** * Find matching {@link Credentials credentials} for the given authentication scope. * * @param map the credentials hash map * @param authscope the {@link AuthScope authentication scope} * @return the credentials * */ private static Credentials matchCredentials( final Map<AuthScope, Credentials> map, final AuthScope authscope) { // see if we get a direct hit Credentials creds = map.get(authscope); if (creds == null) { // Nope. // Do a full scan int bestMatchFactor = -1; AuthScope bestMatch = null; for (AuthScope current: map.keySet()) { int factor = authscope.match(current); if (factor > bestMatchFactor) { bestMatchFactor = factor; bestMatch = current; } } if (bestMatch != null) { creds = map.get(bestMatch); } } return creds; } public Credentials getCredentials(final AuthScope authscope) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } return matchCredentials(this.credMap, authscope); } public void clear() { this.credMap.clear(); } @Override public String toString() { return credMap.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.impl.client; import java.net.URI; import java.net.URISyntaxException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.client.CircularRedirectException; import org.apache.ogt.http.client.RedirectHandler; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpHead; import org.apache.ogt.http.client.params.ClientPNames; import org.apache.ogt.http.client.utils.URIUtils; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; /** * Default implementation of {@link RedirectHandler}. * * @since 4.0 * * @deprecated use {@link DefaultRedirectStrategy}. */ @Immutable @Deprecated public class DefaultRedirectHandler implements RedirectHandler { private final Log log = LogFactory.getLog(getClass()); private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations"; public DefaultRedirectHandler() { super(); } public boolean isRedirectRequested( final HttpResponse response, final HttpContext context) { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: HttpRequest request = (HttpRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST); String method = request.getRequestLine().getMethod(); return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } //end of switch } public URI getLocationURI( final HttpResponse response, final HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } //get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } String location = locationHeader.getValue(); if (this.log.isDebugEnabled()) { this.log.debug("Redirect requested to location '" + location + "'"); } URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute( REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost( uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; } }
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.impl.client; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.client.protocol.RequestAcceptEncoding; import org.apache.ogt.http.client.protocol.ResponseContentEncoding; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.BasicHttpProcessor; /** * {@link DefaultHttpClient} sub-class which includes a {@link RequestAcceptEncoding} * for the request and response. * * @since 4.1 */ @ThreadSafe // since DefaultHttpClient is public class ContentEncodingHttpClient extends DefaultHttpClient { /** * Creates a new HTTP client from parameters and a connection manager. * * @param params the parameters * @param conman the connection manager */ public ContentEncodingHttpClient(ClientConnectionManager conman, HttpParams params) { super(conman, params); } /** * @param params */ public ContentEncodingHttpClient(HttpParams params) { this(null, params); } /** * */ public ContentEncodingHttpClient() { this(null); } /** * {@inheritDoc} */ @Override protected BasicHttpProcessor createHttpProcessor() { BasicHttpProcessor result = super.createHttpProcessor(); result.addRequestInterceptor(new RequestAcceptEncoding()); result.addResponseInterceptor(new ResponseContentEncoding()); return result; } }
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.impl.client; import java.security.Principal; import javax.net.ssl.SSLSession; 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.auth.Credentials; import org.apache.ogt.http.client.UserTokenHandler; import org.apache.ogt.http.client.protocol.ClientContext; import org.apache.ogt.http.conn.HttpRoutedConnection; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; /** * Default implementation of {@link UserTokenHandler}. This class will use * an instance of {@link Principal} as a state object for HTTP connections, * if it can be obtained from the given execution context. This helps ensure * persistent connections created with a particular user identity within * a particular security context can be reused by the same user only. * <p> * DefaultUserTokenHandler will use the user principle of connection * based authentication schemes such as NTLM or that of the SSL session * with the client authentication turned on. If both are unavailable, * <code>null</code> token will be returned. * * @since 4.0 */ @Immutable public class DefaultUserTokenHandler implements UserTokenHandler { public Object getUserToken(final HttpContext context) { Principal userPrincipal = null; AuthState targetAuthState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); if (targetAuthState != null) { userPrincipal = getAuthPrincipal(targetAuthState); if (userPrincipal == null) { AuthState proxyAuthState = (AuthState) context.getAttribute( ClientContext.PROXY_AUTH_STATE); userPrincipal = getAuthPrincipal(proxyAuthState); } } if (userPrincipal == null) { HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute( ExecutionContext.HTTP_CONNECTION); if (conn.isOpen()) { SSLSession sslsession = conn.getSSLSession(); if (sslsession != null) { userPrincipal = sslsession.getLocalPrincipal(); } } } return userPrincipal; } private static Principal getAuthPrincipal(final AuthState authState) { AuthScheme scheme = authState.getAuthScheme(); if (scheme != null && scheme.isComplete() && scheme.isConnectionBased()) { Credentials creds = authState.getCredentials(); if (creds != null) { return creds.getUserPrincipal(); } } return 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.impl.client; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ConnectException; import java.net.UnknownHostException; import javax.net.ssl.SSLException; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.client.HttpRequestRetryHandler; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; /** * The default {@link HttpRequestRetryHandler} used by request executors. * * * @since 4.0 */ @Immutable public class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler { /** the number of times a method will be retried */ private final int retryCount; /** Whether or not methods that have successfully sent their request will be retried */ private final boolean requestSentRetryEnabled; /** * Default constructor */ public DefaultHttpRequestRetryHandler(int retryCount, boolean requestSentRetryEnabled) { super(); this.retryCount = retryCount; this.requestSentRetryEnabled = requestSentRetryEnabled; } /** * Default constructor */ public DefaultHttpRequestRetryHandler() { this(3, false); } /** * Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine * if the given method should be retried. */ public boolean retryRequest( final IOException exception, int executionCount, final HttpContext context) { if (exception == null) { throw new IllegalArgumentException("Exception parameter may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } if (executionCount > this.retryCount) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); if (handleAsIdempotent(request)) { // Retry if the request is considered idempotent return true; } Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT); boolean sent = (b != null && b.booleanValue()); if (!sent || this.requestSentRetryEnabled) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent return true; } // otherwise do not retry return false; } /** * @return <code>true</code> if this handler will retry methods that have * successfully sent their request, <code>false</code> otherwise */ public boolean isRequestSentRetryEnabled() { return requestSentRetryEnabled; } /** * @return the maximum number of times a method will be retried */ public int getRetryCount() { return retryCount; } private boolean handleAsIdempotent(final HttpRequest request) { return !(request instanceof HttpEntityEnclosingRequest); } }
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.impl.client; import java.io.IOException; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.annotation.Immutable; import org.apache.ogt.http.client.HttpResponseException; import org.apache.ogt.http.client.ResponseHandler; import org.apache.ogt.http.util.EntityUtils; /** * A {@link ResponseHandler} that returns the response body as a String * for successful (2xx) responses. If the response code was >= 300, the response * body is consumed and an {@link HttpResponseException} is thrown. * * If this is used with * {@link org.apache.ogt.http.client.HttpClient#execute( * org.apache.ogt.http.client.methods.HttpUriRequest, ResponseHandler)}, * HttpClient may handle redirects (3xx responses) internally. * * * @since 4.0 */ @Immutable public class BasicResponseHandler implements ResponseHandler<String> { /** * Returns the response body as a String if the response was successful (a * 2xx status code). If no response body exists, this returns null. If the * response was unsuccessful (>= 300 status code), throws an * {@link HttpResponseException}. */ public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity); } }
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.impl.client; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.annotation.ThreadSafe; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.protocol.RequestAddCookies; import org.apache.ogt.http.client.protocol.RequestAuthCache; import org.apache.ogt.http.client.protocol.RequestClientConnControl; import org.apache.ogt.http.client.protocol.RequestDefaultHeaders; import org.apache.ogt.http.client.protocol.RequestProxyAuthentication; import org.apache.ogt.http.client.protocol.RequestTargetAuthentication; import org.apache.ogt.http.client.protocol.ResponseAuthCache; import org.apache.ogt.http.client.protocol.ResponseProcessCookies; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.params.CoreConnectionPNames; import org.apache.ogt.http.params.CoreProtocolPNames; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; import org.apache.ogt.http.params.SyncBasicHttpParams; import org.apache.ogt.http.protocol.BasicHttpProcessor; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.protocol.RequestContent; import org.apache.ogt.http.protocol.RequestExpectContinue; import org.apache.ogt.http.protocol.RequestTargetHost; import org.apache.ogt.http.protocol.RequestUserAgent; import org.apache.ogt.http.util.VersionInfo; /** * Default implementation of {@link HttpClient} pre-configured for most common use scenarios. * <p> * This class creates the following chain of protocol interceptors per default: * <ul> * <li>{@link RequestDefaultHeaders}</li> * <li>{@link RequestContent}</li> * <li>{@link RequestTargetHost}</li> * <li>{@link RequestClientConnControl}</li> * <li>{@link RequestUserAgent}</li> * <li>{@link RequestExpectContinue}</li> * <li>{@link RequestAddCookies}</li> * <li>{@link ResponseProcessCookies}</li> * <li>{@link RequestTargetAuthentication}</li> * <li>{@link RequestProxyAuthentication}</li> * </ul> * <p> * This class sets up the following parameters if not explicitly set: * <ul> * <li>Version: HttpVersion.HTTP_1_1</li> * <li>ContentCharset: HTTP.DEFAULT_CONTENT_CHARSET</li> * <li>NoTcpDelay: true</li> * <li>SocketBufferSize: 8192</li> * <li>UserAgent: Apache-HttpClient/release (java 1.5)</li> * </ul> * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USER_AGENT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#STALE_CONNECTION_CHECK}</li> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li> * <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li> * <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.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#COOKIE_POLICY}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#HANDLE_AUTHENTICATION}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#HANDLE_REDIRECTS}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#MAX_REDIRECTS}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#ALLOW_CIRCULAR_REDIRECTS}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#VIRTUAL_HOST}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#DEFAULT_HOST}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#DEFAULT_HEADERS}</li> * <li>{@link org.apache.ogt.http.client.params.ClientPNames#CONNECTION_MANAGER_FACTORY_CLASS_NAME}</li> * </ul> * * @since 4.0 */ @ThreadSafe public class DefaultHttpClient extends AbstractHttpClient { /** * Creates a new HTTP client from parameters and a connection manager. * * @param params the parameters * @param conman the connection manager */ public DefaultHttpClient( final ClientConnectionManager conman, final HttpParams params) { super(conman, params); } /** * @since 4.1 */ public DefaultHttpClient( final ClientConnectionManager conman) { super(conman, null); } public DefaultHttpClient(final HttpParams params) { super(null, params); } public DefaultHttpClient() { super(null, null); } /** * Creates the default set of HttpParams by invoking {@link DefaultHttpClient#setDefaultHttpParams(HttpParams)} * * @return a new instance of {@link SyncBasicHttpParams} with the defaults applied to it. */ @Override protected HttpParams createHttpParams() { HttpParams params = new SyncBasicHttpParams(); setDefaultHttpParams(params); return params; } /** * Saves the default set of HttpParams in the provided parameter. * These are: * <ul> * <li>{@link CoreProtocolPNames#PROTOCOL_VERSION}: 1.1</li> * <li>{@link CoreProtocolPNames#HTTP_CONTENT_CHARSET}: ISO-8859-1</li> * <li>{@link CoreConnectionPNames#TCP_NODELAY}: true</li> * <li>{@link CoreConnectionPNames#SOCKET_BUFFER_SIZE}: 8192</li> * <li>{@link CoreProtocolPNames#USER_AGENT}: Apache-HttpClient/<release> (java 1.5)</li> * </ul> */ public static void setDefaultHttpParams(HttpParams params) { HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 8192); // determine the release version from packaged version info final VersionInfo vi = VersionInfo.loadVersionInfo ("org.apache.ogt.http.client", DefaultHttpClient.class.getClassLoader()); final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.5)"); } @Override protected BasicHttpProcessor createHttpProcessor() { BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestDefaultHeaders()); // Required protocol interceptors httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); // Recommended protocol interceptors httpproc.addInterceptor(new RequestClientConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); // HTTP state management interceptors httpproc.addInterceptor(new RequestAddCookies()); httpproc.addInterceptor(new ResponseProcessCookies()); // HTTP authentication interceptors httpproc.addInterceptor(new RequestAuthCache()); httpproc.addInterceptor(new ResponseAuthCache()); httpproc.addInterceptor(new RequestTargetAuthentication()); httpproc.addInterceptor(new RequestProxyAuthentication()); return httpproc; } }
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.impl.client; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.annotation.NotThreadSafe; import org.apache.ogt.http.entity.HttpEntityWrapper; import org.apache.ogt.http.protocol.HTTP; /** * A wrapper class for {@link HttpEntityEnclosingRequest}s that can * be used to change properties of the current request without * modifying the original object. * </p> * This class is also capable of resetting the request headers to * the state of the original request. * * * @since 4.0 */ @NotThreadSafe // e.g. [gs]etEntity() public class EntityEnclosingRequestWrapper extends RequestWrapper implements HttpEntityEnclosingRequest { private HttpEntity entity; private boolean consumed; public EntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request) throws ProtocolException { super(request); setEntity(request.getEntity()); } public HttpEntity getEntity() { return this.entity; } public void setEntity(final HttpEntity entity) { this.entity = entity != null ? new EntityWrapper(entity) : null; this.consumed = false; } public boolean expectContinue() { Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); } @Override public boolean isRepeatable() { return this.entity == null || this.entity.isRepeatable() || !this.consumed; } class EntityWrapper extends HttpEntityWrapper { EntityWrapper(final HttpEntity entity) { super(entity); } @Deprecated @Override public void consumeContent() throws IOException { consumed = true; super.consumeContent(); } @Override public InputStream getContent() throws IOException { consumed = true; return super.getContent(); } @Override public void writeTo(final OutputStream outstream) throws IOException { consumed = true; super.writeTo(outstream); } } }
Java