KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cactus > internal > util > CookieUtil


1 /*
2  * ========================================================================
3  *
4  * Copyright 2001-2003 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * ========================================================================
19  */

20 package org.apache.cactus.internal.util;
21
22 import java.net.URL JavaDoc;
23 import java.util.Vector JavaDoc;
24
25 import org.apache.cactus.Cookie;
26 import org.apache.cactus.ServletURL;
27 import org.apache.cactus.WebRequest;
28 import org.apache.cactus.internal.client.ClientException;
29 import org.apache.commons.httpclient.Header;
30 import org.apache.commons.httpclient.cookie.CookiePolicy;
31 import org.apache.commons.httpclient.cookie.CookieSpec;
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34
35 /**
36  * Utility methods to manipulate cookies and transform Cactus cookie objects
37  * to HttpClient cookie objects.
38  *
39  * @version $Id: CookieUtil.java,v 1.1 2004/05/22 11:34:48 vmassol Exp $
40  * @since 1.5
41  */

42 public class CookieUtil
43 {
44     /**
45      * The logger
46      */

47     private static final Log LOGGER = LogFactory.getLog(CookieUtil.class);
48
49     /**
50      * Returns the domain that will be used to send the cookies. If a host
51      * was specified using <code>setURL()</code> then the domain will be
52      * this host. Otherwise it will be the real redirector host.
53      *
54      * @param theRequest the request containing all data to pass to the server
55      * redirector.
56      * @param theRealHost the real host to which we are connecting to. We will
57      * use it if no simulation host has been specified.
58      * @return the cookie domain to use
59      */

60     public static String JavaDoc getCookieDomain(WebRequest theRequest,
61         String JavaDoc theRealHost)
62     {
63         String JavaDoc domain;
64         ServletURL url = theRequest.getURL();
65
66         if ((url != null) && (url.getHost() != null))
67         {
68             domain = url.getHost();
69         }
70         else
71         {
72             domain = theRealHost;
73         }
74
75         LOGGER.debug("Cookie validation domain = [" + domain + "]");
76
77         return domain;
78     }
79
80     /**
81      * Returns the port that will be used to send the cookies. If a port
82      * was specified using <code>setURL()</code> then the port sent will be
83      * this port. Otherwise it will be the real redirector port.
84      *
85      * @param theRequest the request containing all data to pass to the server
86      * redirector.
87      * @param theRealPort the real port to which we are connecting to. We will
88      * use it if no simulation port has been specified.
89      * @return the cookie domain to use
90      */

91     public static int getCookiePort(WebRequest theRequest, int theRealPort)
92     {
93         int port;
94         ServletURL url = theRequest.getURL();
95
96         if ((url != null) && (url.getHost() != null))
97         {
98             port = url.getPort();
99         }
100         else
101         {
102             port = theRealPort;
103         }
104
105         LOGGER.debug("Cookie validation port = [" + port + "]");
106
107         return port;
108     }
109
110     /**
111      * Returns the path that will be used to validate if a cookie will be
112      * sent or not. The algorithm is as follows : if the cookie path is not
113      * set (i.e. null) then the cookie is always sent (provided the domain
114      * is right). If the cookie path is set, the cookie is sent only if
115      * the request path starts with the same string as the cookie path. If
116      * <code>setURL()</code> has been called, return the path it has been
117      * set to (context + servletPath + pathInfo). Otherwise return the
118      * real redirector path.
119      *
120      * @param theRequest the request containing all data to pass to the server
121      * redirector.
122      * @param theRealPath the real path to which we are connecting to. We will
123      * use it if no simulation path has been specified.
124      * @return the path to use to decide if a cookie will get sent
125      */

126     public static String JavaDoc getCookiePath(WebRequest theRequest,
127         String JavaDoc theRealPath)
128     {
129         String JavaDoc path;
130         ServletURL url = theRequest.getURL();
131
132         if ((url != null) && (url.getPath() != null))
133         {
134             path = url.getPath();
135         }
136         else
137         {
138             String JavaDoc file = theRealPath;
139
140             if (file != null)
141             {
142                 int q = file.lastIndexOf('?');
143
144                 if (q != -1)
145                 {
146                     path = file.substring(0, q);
147                 }
148                 else
149                 {
150                     path = file;
151                 }
152             }
153             else
154             {
155                 path = null;
156             }
157         }
158
159         LOGGER.debug("Cookie validation path = [" + path + "]");
160
161         return path;
162     }
163
164     /**
165      * Create a Commons-HttpClient cookie from a Cactus cookie, with information
166      * from the web request and the URL.
167      *
168      * @param theRequest The request
169      * @param theUrl The URL
170      * @param theCactusCookie The Cactus Cookie object
171      * @return The HttpClient cookie
172      */

173     public static org.apache.commons.httpclient.Cookie createHttpClientCookie(
174         WebRequest theRequest, URL JavaDoc theUrl, Cookie theCactusCookie)
175     {
176         // If no domain has been specified, use a default one
177
String JavaDoc domain;
178         if (theCactusCookie.getDomain() == null)
179         {
180             domain = CookieUtil.getCookieDomain(theRequest, theUrl.getHost());
181         }
182         else
183         {
184             domain = theCactusCookie.getDomain();
185         }
186
187         // If not path has been specified , use a default one
188
String JavaDoc path;
189         if (theCactusCookie.getPath() == null)
190         {
191             path = CookieUtil.getCookiePath(theRequest, theUrl.getFile());
192         }
193         else
194         {
195             path = theCactusCookie.getPath();
196         }
197
198         // Assemble the HttpClient cookie
199
org.apache.commons.httpclient.Cookie httpclientCookie =
200             new org.apache.commons.httpclient.Cookie(domain,
201                 theCactusCookie.getName(), theCactusCookie.getValue());
202         httpclientCookie.setComment(theCactusCookie.getComment());
203         httpclientCookie.setExpiryDate(
204             theCactusCookie.getExpiryDate());
205         httpclientCookie.setPath(path);
206         httpclientCookie.setSecure(theCactusCookie.isSecure());
207         
208         return httpclientCookie;
209     }
210
211     /**
212      * Transforms an array of Cactus cookies into an array of Commons-HttpClient
213      * cookies, using information from the request and URL.
214      *
215      * @param theRequest The request
216      * @param theUrl The URL
217      * @return The array of HttpClient cookies
218      */

219     public static org.apache.commons.httpclient.Cookie[]
220         createHttpClientCookies(WebRequest theRequest, URL JavaDoc theUrl)
221     {
222         Vector JavaDoc cactusCookies = theRequest.getCookies();
223         
224         // transform the Cactus cookies into HttpClient cookies
225
org.apache.commons.httpclient.Cookie[] httpclientCookies =
226             new org.apache.commons.httpclient.Cookie[cactusCookies.size()];
227
228         for (int i = 0; i < cactusCookies.size(); i++)
229         {
230             Cookie cactusCookie = (Cookie) cactusCookies.elementAt(i);
231             httpclientCookies[i] = CookieUtil.createHttpClientCookie(
232                 theRequest, theUrl, cactusCookie);
233         }
234
235         return httpclientCookies;
236     }
237
238     /**
239      * Create a HttpClient {@link Header} for cookies that matches
240      * the domain and path.
241      *
242      * @param theDomain the cookie domain to match
243      * @param thePath the cookie path to match
244      * @param theCookies the list of potential cookies
245      * @return the HttpClient {@link Header} containing the matching
246      * cookies
247      * @throws ClientException if no cookie was matching the domain
248      * and path
249      */

250     public static Header createCookieHeader(String JavaDoc theDomain, String JavaDoc thePath,
251         org.apache.commons.httpclient.Cookie[] theCookies)
252         throws ClientException
253     {
254         Header cookieHeader = null;
255         
256         // separate domain into host and port
257
int port = 80;
258         String JavaDoc host = theDomain;
259         int portIndex = theDomain.indexOf(":");
260         if (portIndex != -1)
261         {
262             host = host.substring(0, portIndex);
263             port = Integer.parseInt(theDomain.substring(portIndex + 1));
264         }
265
266         CookieSpec matcher = CookiePolicy.getDefaultSpec();
267         org.apache.commons.httpclient.Cookie[] cookies =
268             matcher.match(host, port, thePath, false, theCookies);
269         if ((cookies != null) && (cookies.length > 0))
270         {
271             cookieHeader = matcher.formatCookieHeader(cookies);
272         }
273         
274         if (cookieHeader == null)
275         {
276             throw new ClientException("Failed to create Cookie header for ["
277                 + "domain = [" + theDomain + ", path = [" + thePath
278                 + ", cookies = [" + theCookies + "]]. Turn on HttpClient "
279                 + "logging for more information about the error");
280         }
281         
282         return cookieHeader;
283     }
284
285     /**
286      * @return the cookie string which will be added as a HTTP "Cookie" header
287      * or null if no cookie has been set
288      * @param theRequest the request containing all data to pass to the server
289      * redirector.
290      * @param theUrl the URL to connect to
291      * @throws ClientException if an error occurred when creating the cookie
292      * string
293      */

294     public static String JavaDoc getCookieString(WebRequest theRequest, URL JavaDoc theUrl)
295         throws ClientException
296     {
297         // If no Cookies, then exit
298
Vector JavaDoc cookies = theRequest.getCookies();
299
300         if (!cookies.isEmpty())
301         {
302             // transform the Cactus cookies into HttpClient cookies
303
org.apache.commons.httpclient.Cookie[] httpclientCookies =
304                 CookieUtil.createHttpClientCookies(theRequest, theUrl);
305
306             // and create the cookie header to send
307
Header cookieHeader = createCookieHeader(
308                 CookieUtil.getCookieDomain(theRequest, theUrl.getHost()),
309                 CookieUtil.getCookiePath(theRequest, theUrl.getFile()),
310                 httpclientCookies);
311
312             return cookieHeader.getValue();
313         }
314
315         return null;
316     }
317 }
318
Popular Tags