KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cactus > WebResponse


1 /*
2  * ========================================================================
3  *
4  * Copyright 2001-2004 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;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.StringReader JavaDoc;
26
27 import java.net.HttpURLConnection JavaDoc;
28
29 import java.util.Vector JavaDoc;
30
31 import org.apache.cactus.internal.util.CookieUtil;
32 import org.apache.cactus.internal.util.IoUtil;
33 import org.apache.cactus.util.ChainedRuntimeException;
34 import org.apache.commons.httpclient.Header;
35 import org.apache.commons.httpclient.HttpException;
36 import org.apache.commons.httpclient.cookie.CookiePolicy;
37 import org.apache.commons.httpclient.cookie.CookieSpec;
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40
41 /**
42  * Default web response implementation that provides a minimal
43  * API for asserting returned output stream from the server side. For more
44  * complex assertions, use an <code>com.meterware.httpunit.WebResponse</code>
45  * instead as parameter of your <code>endXXX()</code> methods.
46  *
47  * @version $Id: WebResponse.java,v 1.1 2004/05/22 11:34:45 vmassol Exp $
48  */

49 public class WebResponse
50 {
51     /**
52      * The logger
53      */

54     private static final Log LOGGER = LogFactory.getLog(WebResponse.class);
55
56     /**
57      * The connection object that was used to call the URL
58      */

59     private HttpURLConnection JavaDoc connection;
60
61     /**
62      * The request data that were used to open the connection to the server.
63      */

64     private WebRequest request;
65
66     /**
67      * Save the response content for repeatable reads.
68      */

69     private String JavaDoc content;
70
71     /**
72      * @param theRequest the request data that were used to open the
73      * connection to the server.
74      * @param theConnection the original <code>HttpURLConnection</code> used
75      * to call the URL
76      */

77     public WebResponse(WebRequest theRequest, HttpURLConnection JavaDoc theConnection)
78     {
79         this.request = theRequest;
80         this.connection = theConnection;
81     }
82
83     /**
84      * @return the original <code>HttpURLConnection</code> used to call the
85      * URL
86      */

87     public HttpURLConnection JavaDoc getConnection()
88     {
89         return this.connection;
90     }
91
92     /**
93      * @return the request data the were used to open the connection to the
94      * server
95      */

96     public WebRequest getWebRequest()
97     {
98         return this.request;
99     }
100
101     /**
102      * @return the text of the response (excluding headers) as a string.
103      */

104     public String JavaDoc getText()
105     {
106         // Get the text from the save content if content has already been
107
// read.
108
if (this.content == null)
109         {
110             try
111             {
112                 this.content = IoUtil.getText(this.connection.getInputStream());
113             }
114             catch (IOException JavaDoc e)
115             {
116                 throw new ChainedRuntimeException(e);
117             }
118         }
119
120         return this.content;
121     }
122
123     /**
124      * @return the text of the response (excluding headers) as an array of
125      * strings (each string is a separate line from the output stream).
126      */

127     public String JavaDoc[] getTextAsArray()
128     {
129         Vector JavaDoc lines = new Vector JavaDoc();
130
131         try
132         {
133             // Read content first
134
if (this.content == null)
135             {
136                 getText();
137             }
138
139             BufferedReader JavaDoc input = new BufferedReader JavaDoc(
140                 new StringReader JavaDoc(this.content));
141             String JavaDoc str;
142
143             while (null != (str = input.readLine()))
144             {
145                 lines.addElement(str);
146             }
147
148             input.close();
149         }
150         catch (IOException JavaDoc e)
151         {
152             throw new ChainedRuntimeException(e);
153         }
154
155         // Dummy variable to explicitely tell the object type to copy.
156
String JavaDoc[] dummy = new String JavaDoc[lines.size()];
157
158         return (String JavaDoc[]) (lines.toArray(dummy));
159     }
160
161     /**
162      * @return a buffered input stream for reading the response data.
163      **/

164     public InputStream JavaDoc getInputStream()
165     {
166         try
167         {
168             return this.connection.getInputStream();
169         }
170         catch (IOException JavaDoc e)
171         {
172             throw new ChainedRuntimeException(e);
173         }
174     }
175
176     /**
177      * Return the first cookie found that has the specified name or null
178      * if not found.
179      *
180      * @param theName the cookie name to find
181      * @return the cookie or null if not found
182      */

183     public Cookie getCookie(String JavaDoc theName)
184     {
185         Cookie result = null;
186
187         Cookie[] cookies = getCookies();
188
189         for (int i = 0; i < cookies.length; i++)
190         {
191             if (cookies[i].getName().equals(theName))
192             {
193                 result = cookies[i];
194
195                 break;
196             }
197         }
198
199         return result;
200     }
201
202     /**
203      * Return the first cookie found that has the specified name or null
204      * if not found. The name is case-insensitive.
205      *
206      * @param theName the cookie name to find (case-insensitive)
207      * @return the cookie or null if not found
208      * @since 1.5
209      */

210     public Cookie getCookieIgnoreCase(String JavaDoc theName)
211     {
212         Cookie result = null;
213
214         Cookie[] cookies = getCookies();
215
216         for (int i = 0; i < cookies.length; i++)
217         {
218             if (cookies[i].getName().equalsIgnoreCase(theName))
219             {
220                 result = cookies[i];
221
222                 break;
223             }
224         }
225
226         return result;
227     }
228
229     /**
230      * @return the cookies returned by the server
231      */

232     public Cookie[] getCookies()
233     {
234         Cookie[] returnCookies = null;
235
236         // There can be several headers named "Set-Cookie", so loop through
237
// all the headers, looking for cookies
238
String JavaDoc headerName = this.connection.getHeaderFieldKey(0);
239         String JavaDoc headerValue = this.connection.getHeaderField(0);
240
241         Vector JavaDoc cookieVector = new Vector JavaDoc();
242         CookieSpec cookieSpec = CookiePolicy.getDefaultSpec();
243
244         for (int i = 1; (headerName != null) || (headerValue != null); i++)
245         {
246             LOGGER.debug("Header name = [" + headerName + "]");
247             LOGGER.debug("Header value = [" + headerValue + "]");
248
249             if ((headerName != null)
250                 && (headerName.toLowerCase().equals("set-cookie")
251                 || headerName.toLowerCase().equals("set-cookie2")))
252             {
253                 // Parse the cookie definition
254
org.apache.commons.httpclient.Cookie[] cookies;
255                 try
256                 {
257                     cookies = cookieSpec.parse(
258                         CookieUtil.getCookieDomain(getWebRequest(),
259                             getConnection().getURL().getHost()),
260                         CookieUtil.getCookiePort(getWebRequest(),
261                             getConnection().getURL().getPort()),
262                         CookieUtil.getCookiePath(getWebRequest(),
263                             getConnection().getURL().getFile()),
264                         false, new Header(headerName, headerValue));
265                 }
266                 catch (HttpException e)
267                 {
268                     throw new ChainedRuntimeException(
269                         "Error parsing cookies", e);
270                 }
271
272                 // Transform the HttpClient cookies into Cactus cookies and
273
// add them to the cookieVector vector
274
for (int j = 0; j < cookies.length; j++)
275                 {
276                     Cookie cookie = new Cookie(cookies[j].getDomain(),
277                         cookies[j].getName(), cookies[j].getValue());
278
279                     cookie.setComment(cookies[j].getComment());
280                     cookie.setExpiryDate(cookies[j].getExpiryDate());
281                     cookie.setPath(cookies[j].getPath());
282                     cookie.setSecure(cookies[j].getSecure());
283
284                     cookieVector.addElement(cookie);
285                 }
286             }
287
288             headerName = this.connection.getHeaderFieldKey(i);
289             headerValue = this.connection.getHeaderField(i);
290         }
291
292         returnCookies = new Cookie[cookieVector.size()];
293         cookieVector.copyInto(returnCookies);
294
295         return returnCookies;
296     }
297
298     /**
299      * Returns the status code returned by the server.
300      *
301      * @return The status code
302      * @since 1.5
303      */

304     public int getStatusCode()
305     {
306         try
307         {
308             return this.connection.getResponseCode();
309         }
310         catch (IOException JavaDoc e)
311         {
312             throw new ChainedRuntimeException(e);
313         }
314     }
315
316 }
317
Popular Tags