01: /*
02: * $Id: CookieHelper.java 10899 2008-02-20 12:37:03Z dirk.olmes $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.transport.http;
12:
13: import java.util.ArrayList;
14: import java.util.List;
15:
16: import org.apache.commons.httpclient.Cookie;
17: import org.apache.commons.httpclient.Header;
18: import org.apache.commons.httpclient.HeaderElement;
19: import org.apache.commons.httpclient.NameValuePair;
20: import org.apache.commons.httpclient.cookie.CookiePolicy;
21: import org.apache.commons.httpclient.cookie.CookieSpec;
22: import org.apache.commons.httpclient.cookie.MalformedCookieException;
23: import org.apache.commons.httpclient.cookie.NetscapeDraftSpec;
24: import org.apache.commons.httpclient.cookie.RFC2109Spec;
25: import org.apache.commons.logging.Log;
26: import org.apache.commons.logging.LogFactory;
27:
28: /**
29: * Helper functions for parsing cookie headers.
30: *
31: */
32: public class CookieHelper {
33:
34: /**
35: * logger used by this class
36: */
37: protected static final Log logger = LogFactory
38: .getLog(CookieHelper.class);
39:
40: /**
41: * Do not instantiate.
42: */
43: private CookieHelper() {
44: // no op
45: }
46:
47: public static CookieSpec getCookieSpec(String spec) {
48: if (spec != null
49: && spec
50: .equalsIgnoreCase(HttpConnector.COOKIE_SPEC_NETSCAPE)) {
51: return new NetscapeDraftSpec();
52: } else {
53: return new RFC2109Spec();
54: }
55: }
56:
57: public static String getCookiePolicy(String spec) {
58: if (spec != null
59: && spec
60: .equalsIgnoreCase(HttpConnector.COOKIE_SPEC_NETSCAPE)) {
61: return CookiePolicy.NETSCAPE;
62: } else {
63: return CookiePolicy.RFC_2109;
64: }
65: }
66:
67: public static Cookie[] parseCookies(Header header, String spec)
68: throws MalformedCookieException {
69: List cookies = new ArrayList();
70: CookieSpec cookieSpec = getCookieSpec(spec);
71: HeaderElement[] headerElements = header.getElements();
72:
73: for (int j = 0; j < headerElements.length; j++) {
74: HeaderElement headerElement = headerElements[j];
75: NameValuePair[] headerElementParameters = headerElement
76: .getParameters();
77: Cookie cookie = new Cookie();
78:
79: for (int k = 0; k < headerElementParameters.length; k++) {
80: NameValuePair nameValuePair = headerElementParameters[k];
81: cookieSpec.parseAttribute(nameValuePair, cookie);
82: }
83:
84: if (cookie.isExpired()) {
85: if (logger.isDebugEnabled()) {
86: logger.debug("Cookie: " + cookie.toString()
87: + " has expired, not adding it.");
88: }
89: } else {
90: cookies.add(cookie);
91: }
92: }
93:
94: return (Cookie[]) cookies.toArray(new Cookie[cookies.size()]);
95: }
96:
97: }
|