001: /*
002: * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpState.java,v 1.38 2004/12/20 11:50:54 olegk Exp $
003: * $Revision: 561099 $
004: * $Date: 2007-07-30 21:41:17 +0200 (Mon, 30 Jul 2007) $
005: *
006: * ====================================================================
007: *
008: * Licensed to the Apache Software Foundation (ASF) under one or more
009: * contributor license agreements. See the NOTICE file distributed with
010: * this work for additional information regarding copyright ownership.
011: * The ASF licenses this file to You under the Apache License, Version 2.0
012: * (the "License"); you may not use this file except in compliance with
013: * the License. You may obtain a copy of the License at
014: *
015: * http://www.apache.org/licenses/LICENSE-2.0
016: *
017: * Unless required by applicable law or agreed to in writing, software
018: * distributed under the License is distributed on an "AS IS" BASIS,
019: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
020: * See the License for the specific language governing permissions and
021: * limitations under the License.
022: * ====================================================================
023: *
024: * This software consists of voluntary contributions made by many
025: * individuals on behalf of the Apache Software Foundation. For more
026: * information on the Apache Software Foundation, please see
027: * <http://www.apache.org/>.
028: *
029: */
030:
031: package org.apache.commons.httpclient;
032:
033: import java.util.ArrayList;
034: import java.util.Date;
035: import java.util.HashMap;
036: import java.util.Map;
037: import java.util.List;
038: import java.util.Iterator;
039: import org.apache.commons.httpclient.cookie.CookieSpec;
040: import org.apache.commons.httpclient.cookie.CookiePolicy;
041: import org.apache.commons.httpclient.auth.AuthScope;
042: import org.apache.commons.logging.Log;
043: import org.apache.commons.logging.LogFactory;
044:
045: /**
046: * <p>
047: * A container for HTTP attributes that may persist from request
048: * to request, such as {@link Cookie cookies} and authentication
049: * {@link Credentials credentials}.
050: * </p>
051: *
052: * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
053: * @author Rodney Waldhoff
054: * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
055: * @author Sean C. Sullivan
056: * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
057: * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
058: * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
059: * @author <a href="mailto:adrian@intencha.com">Adrian Sutton</a>
060: *
061: * @version $Revision: 561099 $ $Date: 2007-07-30 21:41:17 +0200 (Mon, 30 Jul 2007) $
062: *
063: */
064: public class HttpState {
065:
066: // ----------------------------------------------------- Instance Variables
067:
068: /**
069: * Map of {@link Credentials credentials} by realm that this
070: * HTTP state contains.
071: */
072: protected HashMap credMap = new HashMap();
073:
074: /**
075: * Map of {@link Credentials proxy credentials} by realm that this
076: * HTTP state contains
077: */
078: protected HashMap proxyCred = new HashMap();
079:
080: /**
081: * Array of {@link Cookie cookies} that this HTTP state contains.
082: */
083: protected ArrayList cookies = new ArrayList();
084:
085: private boolean preemptive = false;
086:
087: private int cookiePolicy = -1;
088: // -------------------------------------------------------- Class Variables
089:
090: /**
091: * The boolean system property name to turn on preemptive authentication.
092: * @deprecated This field and feature will be removed following HttpClient 3.0.
093: */
094: public static final String PREEMPTIVE_PROPERTY = "httpclient.authentication.preemptive";
095:
096: /**
097: * The default value for {@link #PREEMPTIVE_PROPERTY}.
098: * @deprecated This field and feature will be removed following HttpClient 3.0.
099: */
100: public static final String PREEMPTIVE_DEFAULT = "false";
101:
102: /** Log object for this class. */
103: private static final Log LOG = LogFactory.getLog(HttpState.class);
104:
105: /**
106: * Default constructor.
107: */
108: public HttpState() {
109: super ();
110: }
111:
112: // ------------------------------------------------------------- Properties
113:
114: /**
115: * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies.
116: * If the given cookie has already expired it will not be added, but existing
117: * values will still be removed.
118: *
119: * @param cookie the {@link Cookie cookie} to be added
120: *
121: * @see #addCookies(Cookie[])
122: *
123: */
124: public synchronized void addCookie(Cookie cookie) {
125: LOG.trace("enter HttpState.addCookie(Cookie)");
126:
127: if (cookie != null) {
128: // first remove any old cookie that is equivalent
129: for (Iterator it = cookies.iterator(); it.hasNext();) {
130: Cookie tmp = (Cookie) it.next();
131: if (cookie.equals(tmp)) {
132: it.remove();
133: break;
134: }
135: }
136: if (!cookie.isExpired()) {
137: cookies.add(cookie);
138: }
139: }
140: }
141:
142: /**
143: * Adds an array of {@link Cookie HTTP cookies}. Cookies are added individually and
144: * in the given array order. If any of the given cookies has already expired it will
145: * not be added, but existing values will still be removed.
146: *
147: * @param cookies the {@link Cookie cookies} to be added
148: *
149: * @see #addCookie(Cookie)
150: *
151: *
152: */
153: public synchronized void addCookies(Cookie[] cookies) {
154: LOG.trace("enter HttpState.addCookies(Cookie[])");
155:
156: if (cookies != null) {
157: for (int i = 0; i < cookies.length; i++) {
158: this .addCookie(cookies[i]);
159: }
160: }
161: }
162:
163: /**
164: * Returns an array of {@link Cookie cookies} that this HTTP
165: * state currently contains.
166: *
167: * @return an array of {@link Cookie cookies}.
168: *
169: * @see #getCookies(String, int, String, boolean)
170: *
171: */
172: public synchronized Cookie[] getCookies() {
173: LOG.trace("enter HttpState.getCookies()");
174: return (Cookie[]) (cookies.toArray(new Cookie[cookies.size()]));
175: }
176:
177: /**
178: * Returns an array of {@link Cookie cookies} in this HTTP
179: * state that match the given request parameters.
180: *
181: * @param domain the request domain
182: * @param port the request port
183: * @param path the request path
184: * @param secure <code>true</code> when using HTTPS
185: *
186: * @return an array of {@link Cookie cookies}.
187: *
188: * @see #getCookies()
189: *
190: * @deprecated use CookieSpec#match(String, int, String, boolean, Cookie)
191: */
192: public synchronized Cookie[] getCookies(String domain, int port,
193: String path, boolean secure) {
194: LOG
195: .trace("enter HttpState.getCookies(String, int, String, boolean)");
196:
197: CookieSpec matcher = CookiePolicy.getDefaultSpec();
198: ArrayList list = new ArrayList(cookies.size());
199: for (int i = 0, m = cookies.size(); i < m; i++) {
200: Cookie cookie = (Cookie) (cookies.get(i));
201: if (matcher.match(domain, port, path, secure, cookie)) {
202: list.add(cookie);
203: }
204: }
205: return (Cookie[]) (list.toArray(new Cookie[list.size()]));
206: }
207:
208: /**
209: * Removes all of {@link Cookie cookies} in this HTTP state
210: * that have expired according to the current system time.
211: *
212: * @see #purgeExpiredCookies(java.util.Date)
213: *
214: */
215: public synchronized boolean purgeExpiredCookies() {
216: LOG.trace("enter HttpState.purgeExpiredCookies()");
217: return purgeExpiredCookies(new Date());
218: }
219:
220: /**
221: * Removes all of {@link Cookie cookies} in this HTTP state
222: * that have expired by the specified {@link java.util.Date date}.
223: *
224: * @param date The {@link java.util.Date date} to compare against.
225: *
226: * @return true if any cookies were purged.
227: *
228: * @see Cookie#isExpired(java.util.Date)
229: *
230: * @see #purgeExpiredCookies()
231: */
232: public synchronized boolean purgeExpiredCookies(Date date) {
233: LOG.trace("enter HttpState.purgeExpiredCookies(Date)");
234: boolean removed = false;
235: Iterator it = cookies.iterator();
236: while (it.hasNext()) {
237: if (((Cookie) (it.next())).isExpired(date)) {
238: it.remove();
239: removed = true;
240: }
241: }
242: return removed;
243: }
244:
245: /**
246: * Returns the current {@link CookiePolicy cookie policy} for this
247: * HTTP state.
248: *
249: * @return The {@link CookiePolicy cookie policy}.
250: *
251: * @deprecated Use
252: * {@link org.apache.commons.httpclient.params.HttpMethodParams#getCookiePolicy()},
253: * {@link HttpMethod#getParams()}.
254: */
255:
256: public int getCookiePolicy() {
257: return this .cookiePolicy;
258: }
259:
260: /**
261: * Defines whether preemptive authentication should be
262: * attempted.
263: *
264: * @param value <tt>true</tt> if preemptive authentication should be
265: * attempted, <tt>false</tt> otherwise.
266: *
267: * @deprecated Use
268: * {@link org.apache.commons.httpclient.params.HttpClientParams#setAuthenticationPreemptive(boolean)},
269: * {@link HttpClient#getParams()}.
270: */
271:
272: public void setAuthenticationPreemptive(boolean value) {
273: this .preemptive = value;
274: }
275:
276: /**
277: * Returns <tt>true</tt> if preemptive authentication should be
278: * attempted, <tt>false</tt> otherwise.
279: *
280: * @return boolean flag.
281: *
282: * @deprecated Use
283: * {@link org.apache.commons.httpclient.params.HttpClientParams#isAuthenticationPreemptive()},
284: * {@link HttpClient#getParams()}.
285: */
286:
287: public boolean isAuthenticationPreemptive() {
288: return this .preemptive;
289: }
290:
291: /**
292: * Sets the current {@link CookiePolicy cookie policy} for this HTTP
293: * state to one of the following supported policies:
294: * {@link CookiePolicy#COMPATIBILITY},
295: * {@link CookiePolicy#NETSCAPE_DRAFT} or
296: * {@link CookiePolicy#RFC2109}.
297: *
298: * @param policy new {@link CookiePolicy cookie policy}
299: *
300: * @deprecated
301: * Use {@link org.apache.commons.httpclient.params.HttpMethodParams#setCookiePolicy(String)},
302: * {@link HttpMethod#getParams()}.
303: */
304:
305: public void setCookiePolicy(int policy) {
306: this .cookiePolicy = policy;
307: }
308:
309: /**
310: * Sets the {@link Credentials credentials} for the given authentication
311: * realm on the given host. The <code>null</code> realm signifies default
312: * credentials for the given host, which should be used when no
313: * {@link Credentials credentials} have been explictly supplied for the
314: * challenging realm. The <code>null</code> host signifies default
315: * credentials, which should be used when no {@link Credentials credentials}
316: * have been explictly supplied for the challenging host. Any previous
317: * credentials for the given realm on the given host will be overwritten.
318: *
319: * @param realm the authentication realm
320: * @param host the host the realm belongs to
321: * @param credentials the authentication {@link Credentials credentials}
322: * for the given realm.
323: *
324: * @see #getCredentials(String, String)
325: * @see #setProxyCredentials(String, String, Credentials)
326: *
327: * @deprecated use #setCredentials(AuthScope, Credentials)
328: */
329:
330: public synchronized void setCredentials(String realm, String host,
331: Credentials credentials) {
332: LOG
333: .trace("enter HttpState.setCredentials(String, String, Credentials)");
334: credMap.put(new AuthScope(host, AuthScope.ANY_PORT, realm,
335: AuthScope.ANY_SCHEME), credentials);
336: }
337:
338: /**
339: * Sets the {@link Credentials credentials} for the given authentication
340: * scope. Any previous credentials for the given scope will be overwritten.
341: *
342: * @param authscope the {@link AuthScope authentication scope}
343: * @param credentials the authentication {@link Credentials credentials}
344: * for the given scope.
345: *
346: * @see #getCredentials(AuthScope)
347: * @see #setProxyCredentials(AuthScope, Credentials)
348: *
349: * @since 3.0
350: */
351: public synchronized void setCredentials(final AuthScope authscope,
352: final Credentials credentials) {
353: if (authscope == null) {
354: throw new IllegalArgumentException(
355: "Authentication scope may not be null");
356: }
357: LOG
358: .trace("enter HttpState.setCredentials(AuthScope, Credentials)");
359: credMap.put(authscope, credentials);
360: }
361:
362: /**
363: * Find matching {@link Credentials credentials} for the given authentication scope.
364: *
365: * @param map the credentials hash map
366: * @param token the {@link AuthScope authentication scope}
367: * @return the credentials
368: *
369: */
370: private static Credentials matchCredentials(final HashMap map,
371: final AuthScope authscope) {
372: // see if we get a direct hit
373: Credentials creds = (Credentials) map.get(authscope);
374: if (creds == null) {
375: // Nope.
376: // Do a full scan
377: int bestMatchFactor = -1;
378: AuthScope bestMatch = null;
379: Iterator items = map.keySet().iterator();
380: while (items.hasNext()) {
381: AuthScope current = (AuthScope) items.next();
382: int factor = authscope.match(current);
383: if (factor > bestMatchFactor) {
384: bestMatchFactor = factor;
385: bestMatch = current;
386: }
387: }
388: if (bestMatch != null) {
389: creds = (Credentials) map.get(bestMatch);
390: }
391: }
392: return creds;
393: }
394:
395: /**
396: * Get the {@link Credentials credentials} for the given authentication scope on the
397: * given host.
398: *
399: * If the <i>realm</i> exists on <i>host</i>, return the coresponding credentials.
400: * If the <i>host</i> exists with a <tt>null</tt> <i>realm</i>, return the corresponding
401: * credentials.
402: * If the <i>realm</i> exists with a <tt>null</tt> <i>host</i>, return the
403: * corresponding credentials. If the <i>realm</i> does not exist, return
404: * the default Credentials. If there are no default credentials, return
405: * <code>null</code>.
406: *
407: * @param realm the authentication realm
408: * @param host the host the realm is on
409: * @return the credentials
410: *
411: * @see #setCredentials(String, String, Credentials)
412: *
413: * @deprecated use #getCredentials(AuthScope)
414: */
415:
416: public synchronized Credentials getCredentials(String realm,
417: String host) {
418: LOG.trace("enter HttpState.getCredentials(String, String");
419: return matchCredentials(this .credMap, new AuthScope(host,
420: AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME));
421: }
422:
423: /**
424: * Get the {@link Credentials credentials} for the given authentication scope.
425: *
426: * @param authscope the {@link AuthScope authentication scope}
427: * @return the credentials
428: *
429: * @see #setCredentials(AuthScope, Credentials)
430: *
431: * @since 3.0
432: */
433: public synchronized Credentials getCredentials(
434: final AuthScope authscope) {
435: if (authscope == null) {
436: throw new IllegalArgumentException(
437: "Authentication scope may not be null");
438: }
439: LOG.trace("enter HttpState.getCredentials(AuthScope)");
440: return matchCredentials(this .credMap, authscope);
441: }
442:
443: /**
444: * Sets the {@link Credentials credentials} for the given proxy authentication
445: * realm on the given proxy host. The <code>null</code> proxy realm signifies
446: * default credentials for the given proxy host, which should be used when no
447: * {@link Credentials credentials} have been explictly supplied for the
448: * challenging proxy realm. The <code>null</code> proxy host signifies default
449: * credentials, which should be used when no {@link Credentials credentials}
450: * have been explictly supplied for the challenging proxy host. Any previous
451: * credentials for the given proxy realm on the given proxy host will be
452: * overwritten.
453: *
454: * @param realm the authentication realm
455: * @param proxyHost the proxy host
456: * @param credentials the authentication credentials for the given realm
457: *
458: * @see #getProxyCredentials(AuthScope)
459: * @see #setCredentials(AuthScope, Credentials)
460: *
461: * @deprecated use #setProxyCredentials(AuthScope, Credentials)
462: */
463: public synchronized void setProxyCredentials(String realm,
464: String proxyHost, Credentials credentials) {
465: LOG
466: .trace("enter HttpState.setProxyCredentials(String, String, Credentials");
467: proxyCred.put(new AuthScope(proxyHost, AuthScope.ANY_PORT,
468: realm, AuthScope.ANY_SCHEME), credentials);
469: }
470:
471: /**
472: * Sets the {@link Credentials proxy credentials} for the given authentication
473: * realm. Any previous credentials for the given realm will be overwritten.
474: *
475: * @param authscope the {@link AuthScope authentication scope}
476: * @param credentials the authentication {@link Credentials credentials}
477: * for the given realm.
478: *
479: * @see #getProxyCredentials(AuthScope)
480: * @see #setCredentials(AuthScope, Credentials)
481: *
482: * @since 3.0
483: */
484: public synchronized void setProxyCredentials(
485: final AuthScope authscope, final Credentials credentials) {
486: if (authscope == null) {
487: throw new IllegalArgumentException(
488: "Authentication scope may not be null");
489: }
490: LOG
491: .trace("enter HttpState.setProxyCredentials(AuthScope, Credentials)");
492: proxyCred.put(authscope, credentials);
493: }
494:
495: /**
496: * Get the {@link Credentials credentials} for the proxy host with the given
497: * authentication scope.
498: *
499: * If the <i>realm</i> exists on <i>host</i>, return the coresponding credentials.
500: * If the <i>host</i> exists with a <tt>null</tt> <i>realm</i>, return the corresponding
501: * credentials.
502: * If the <i>realm</i> exists with a <tt>null</tt> <i>host</i>, return the
503: * corresponding credentials. If the <i>realm</i> does not exist, return
504: * the default Credentials. If there are no default credentials, return
505: * <code>null</code>.
506: *
507: * @param realm the authentication realm
508: * @param proxyHost the proxy host the realm is on
509: * @return the credentials
510: * @see #setProxyCredentials(String, String, Credentials)
511: *
512: * @deprecated use #getProxyCredentials(AuthScope)
513: */
514: public synchronized Credentials getProxyCredentials(String realm,
515: String proxyHost) {
516: LOG.trace("enter HttpState.getCredentials(String, String");
517: return matchCredentials(this .proxyCred, new AuthScope(
518: proxyHost, AuthScope.ANY_PORT, realm,
519: AuthScope.ANY_SCHEME));
520: }
521:
522: /**
523: * Get the {@link Credentials proxy credentials} for the given authentication scope.
524: *
525: * @param authscope the {@link AuthScope authentication scope}
526: * @return the credentials
527: *
528: * @see #setProxyCredentials(AuthScope, Credentials)
529: *
530: * @since 3.0
531: */
532: public synchronized Credentials getProxyCredentials(
533: final AuthScope authscope) {
534: if (authscope == null) {
535: throw new IllegalArgumentException(
536: "Authentication scope may not be null");
537: }
538: LOG.trace("enter HttpState.getProxyCredentials(AuthScope)");
539: return matchCredentials(this .proxyCred, authscope);
540: }
541:
542: /**
543: * Returns a string representation of this HTTP state.
544: *
545: * @return The string representation of the HTTP state.
546: *
547: * @see java.lang.Object#toString()
548: */
549: public synchronized String toString() {
550: StringBuffer sbResult = new StringBuffer();
551:
552: sbResult.append("[");
553: sbResult.append(getCredentialsStringRepresentation(proxyCred));
554: sbResult.append(" | ");
555: sbResult.append(getCredentialsStringRepresentation(credMap));
556: sbResult.append(" | ");
557: sbResult.append(getCookiesStringRepresentation(cookies));
558: sbResult.append("]");
559:
560: String strResult = sbResult.toString();
561:
562: return strResult;
563: }
564:
565: /**
566: * Returns a string representation of the credentials.
567: * @param credMap The credentials.
568: * @return The string representation.
569: */
570: private static String getCredentialsStringRepresentation(
571: final Map credMap) {
572: StringBuffer sbResult = new StringBuffer();
573: Iterator iter = credMap.keySet().iterator();
574: while (iter.hasNext()) {
575: Object key = iter.next();
576: Credentials cred = (Credentials) credMap.get(key);
577: if (sbResult.length() > 0) {
578: sbResult.append(", ");
579: }
580: sbResult.append(key);
581: sbResult.append("#");
582: sbResult.append(cred.toString());
583: }
584: return sbResult.toString();
585: }
586:
587: /**
588: * Returns a string representation of the cookies.
589: * @param cookies The cookies
590: * @return The string representation.
591: */
592: private static String getCookiesStringRepresentation(
593: final List cookies) {
594: StringBuffer sbResult = new StringBuffer();
595: Iterator iter = cookies.iterator();
596: while (iter.hasNext()) {
597: Cookie ck = (Cookie) iter.next();
598: if (sbResult.length() > 0) {
599: sbResult.append("#");
600: }
601: sbResult.append(ck.toExternalForm());
602: }
603: return sbResult.toString();
604: }
605:
606: /**
607: * Clears all credentials.
608: */
609: public void clearCredentials() {
610: this .credMap.clear();
611: }
612:
613: /**
614: * Clears all proxy credentials.
615: */
616: public void clearProxyCredentials() {
617: this .proxyCred.clear();
618: }
619:
620: /**
621: * Clears all cookies.
622: */
623: public synchronized void clearCookies() {
624: this .cookies.clear();
625: }
626:
627: /**
628: * Clears the state information (all cookies, credentials and proxy credentials).
629: */
630: public void clear() {
631: clearCookies();
632: clearCredentials();
633: clearProxyCredentials();
634: }
635: }
|