KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > plankton > http > HttpServices


1 /*
2  * Copyright (C) 2003 Christian Cryder [christianc@granitepeaks.com]
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * $Id: HttpServices.java,v 1.3 2004/02/01 05:16:28 christianc Exp $
19  */

20 package org.enhydra.barracuda.plankton.http;
21
22 import java.text.*;
23 import java.util.*;
24 import javax.servlet.http.*;
25
26 //saw_121102.2 - created
27
/**
28  * This class provides HTTP-related utility methods.
29  *
30  * @author shawn@shawn-wilson.com
31  */

32 public class HttpServices {
33
34     protected static final DateFormat cookieDF = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss zzz");
35
36     /**
37      * Return a Cookie from a single 'Set-Cookie' header value string from the server.
38      * The value string must conform to either the Version 0 (by Netscape) or Version 1
39      * (by RFC 2109) cookie specification.
40      *
41      * @throws ParseException if the string cannot be parsed into a valid cookie
42      *
43      * @see <a HREF="http://wp.netscape.com/newsref/std/cookie_spec.html">Cookie Specification, Version 0</a>
44      * @see <a HREF="http://rfc-2109.rfc-list.org/">Cookie Specification, Version 1</a>
45      */

46     public static Cookie parseCookie(String JavaDoc str) throws ParseException {
47         Cookie cookie;
48         StringTokenizer st = new StringTokenizer(str, ";");
49         int length = 0; // to keep track of position for ParseExceptions
50

51         String JavaDoc str1 = st.nextToken();
52         length += str1.length();
53         str1 = str1.trim();
54         int index = str1.indexOf('=');
55
56         if(index < 0) throw new ParseException("Missing name=value pair", 0);
57         else if(index == 0) throw new ParseException("Missing name for name=value pair", 0);
58         else if(index == str1.length()) throw new ParseException("Missing value for name=value pair", 0);
59         else cookie = new Cookie(str1.substring(0, index), str1.substring(index+1));
60
61         while(st.hasMoreTokens()) {
62             str1 = st.nextToken();
63             index = str1.indexOf('=');
64
65             if(index < 0) {
66                 if(str1.trim().equalsIgnoreCase("secure")) {
67                     cookie.setSecure(true);
68                 } else {
69                     //throw new ParseException("Unrecognized option: "+str1, length);
70
// for compatibility with future cookie specifications, we will simply
71
// silently ignore any unrecognized fields
72
}
73             } else if(index > 0) {
74                 String JavaDoc key = str1.substring(0, index).trim().toLowerCase();
75                 String JavaDoc val = str1.substring(index+1);
76
77                 if(key.equals("comment")) {
78                     cookie.setComment(val);
79                 } else if(key.equals("domain")) {
80                     cookie.setDomain(val);
81                 } else if(key.equals("max-age")) {
82                     try { cookie.setMaxAge(Integer.parseInt(val)); }
83                     catch(NumberFormatException JavaDoc e) {
84                         ParseException ee = new ParseException("Not an integer for 'max-age' field", length+8);
85                         // dbr_032601
86
// The 1.3 api doesn't support this
87
// ee.initCause(e);
88
throw ee;
89                     }
90                 } else if(key.equals("path")) {
91                     cookie.setPath(val);
92                 } else if(key.equals("version")) {
93                     try { cookie.setVersion(Integer.parseInt(val)); }
94                     catch(NumberFormatException JavaDoc e) {
95                         ParseException ee = new ParseException("Not an integer for 'version' field", length+8);
96                         // dbr_032601
97
// The 1.3 api doesn't support this
98
// ee.initCause(e);
99
throw ee;
100                     }
101                 } else if(key.equals("expires")) {
102                     // provided for Version 0 compatibility
103
try { cookie.setMaxAge( (int)(cookieDF.parse(val).getTime()/1000) ); }
104                     catch(ParseException e) {
105                         ParseException ee = new ParseException("Invalid date format for 'expires' field", length+8);
106                         // dbr_032601
107
// The 1.3 api doesn't support this
108
// ee.initCause(e);
109
throw ee;
110                     }
111                 } else {
112                     //throw new ParseException("Unrecognized option: "+str1, length);
113
// for compatibility with future cookie specifications, we will simply
114
// silently ignore any unrecognized fields
115
}
116             } else {
117                 throw new ParseException("Missing option: "+str1, length);
118             }
119
120             length += 1+str1.length(); // (+1 for the semicolon delimiter)
121
}
122
123         return cookie;
124     }
125
126     /**
127      * Return a formatted cookie string for use in a 'Set-Cookie' header.
128      */

129     public static String JavaDoc formatCookie(Cookie cookie) {
130         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(cookie.getName()+"="+cookie.getValue());
131         if(cookie.getComment() != null) sb.append(";Comment=").append(cookie.getComment());
132         if(cookie.getDomain() != null) sb.append(";Domain=").append(cookie.getDomain());
133         if(cookie.getPath() != null) sb.append(";Path=").append(cookie.getPath());
134         if(cookie.getSecure()) sb.append(";Secure");
135         if(cookie.getVersion() == 0) {
136             if(cookie.getMaxAge() >= 0) sb.append(";Expires=").append(cookieDF.format(new Date(cookie.getMaxAge())));
137         } else {
138             sb.append(";Version=").append(cookie.getVersion());
139             sb.append(";Max-Age=").append(cookie.getMaxAge());
140         }
141
142         return sb.toString();
143     }
144     
145     /**
146      * Convenience method to get a cookie by name from an HttpServletRequest
147      */

148     public static Cookie getCookie(String JavaDoc cookieName, HttpServletRequest req) {
149         if (cookieName==null || req==null) return null;
150         Cookie cookie = null;
151         Cookie[] cookies = req.getCookies();
152         if (cookies!=null) {
153             for (int i=0; i<cookies.length; i++) {
154                 if (cookies[i].getName().equals(cookieName)) {
155                     cookie = cookies[i];
156                     break;
157                 }
158             }
159         }
160         return cookie;
161     }
162     
163 };
164
Popular Tags