KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cactus > internal > client > connector > http > HttpClientConnectionHelper


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.internal.client.connector.http;
21
22 import java.io.IOException JavaDoc;
23
24 import java.net.HttpURLConnection JavaDoc;
25 import java.net.URL JavaDoc;
26
27 import java.util.ArrayList JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.List JavaDoc;
30
31 import org.apache.cactus.WebRequest;
32 import org.apache.cactus.client.authentication.Authentication;
33 import org.apache.cactus.internal.configuration.Configuration;
34 import org.apache.cactus.internal.util.CookieUtil;
35 import org.apache.cactus.internal.util.UrlUtil;
36 import org.apache.commons.httpclient.HostConfiguration;
37 import org.apache.commons.httpclient.HttpClient;
38 import org.apache.commons.httpclient.HttpState;
39 import org.apache.commons.httpclient.HttpMethod;
40 import org.apache.commons.httpclient.NameValuePair;
41 import org.apache.commons.httpclient.methods.GetMethod;
42 import org.apache.commons.httpclient.methods.PostMethod;
43 import org.apache.commons.httpclient.protocol.Protocol;
44
45 /**
46  * Implementation of <code>ConnectionHelper</code> using Jakarta Commons
47  * HttpClient.
48  *
49  * @version $Id: HttpClientConnectionHelper.java,v 1.1 2004/05/22 11:34:46 vmassol Exp $
50  */

51 public class HttpClientConnectionHelper implements ConnectionHelper
52 {
53     /**
54      * The <code>HttpMethod</code> used to connect to the HTTP server. It is
55      * either a <code>GetMethod</code> or a <code>PostMethod</code>.
56      */

57     private HttpMethod method;
58
59     /**
60      * The URL that will be used for the HTTP connection.
61      */

62     private String JavaDoc url;
63
64     /**
65      * @param theURL the URL that will be used for the HTTP connection.
66      */

67     public HttpClientConnectionHelper(String JavaDoc theURL)
68     {
69         this.url = theURL;
70     }
71
72     /**
73      * @see ConnectionHelper#connect(WebRequest, Configuration)
74      */

75     public HttpURLConnection JavaDoc connect(WebRequest theRequest,
76         Configuration theConfiguration) throws Throwable JavaDoc
77     {
78         URL JavaDoc url = new URL JavaDoc(this.url);
79
80         HttpState state = new HttpState();
81
82         // Choose the method that we will use to post data :
83
// - If at least one parameter is to be sent in the request body, then
84
// we are doing a POST.
85
// - If user data has been specified, then we are doing a POST
86
if (theRequest.getParameterNamesPost().hasMoreElements()
87             || (theRequest.getUserData() != null))
88         {
89             this.method = new PostMethod();
90         }
91         else
92         {
93             this.method = new GetMethod();
94         }
95
96         // Add Authentication headers, if necessary. This is the first
97
// step to allow authentication to add extra headers, HTTP parameters,
98
// etc.
99
Authentication authentication = theRequest.getAuthentication();
100
101         if (authentication != null)
102         {
103             authentication.configure(state, this.method, theRequest,
104                 theConfiguration);
105         }
106
107         // Add the parameters that need to be passed as part of the URL
108
url = HttpUtil.addHttpGetParameters(theRequest, url);
109
110         this.method.setFollowRedirects(false);
111         this.method.setPath(UrlUtil.getPath(url));
112         this.method.setQueryString(UrlUtil.getQuery(url));
113
114         // Sets the content type
115
this.method.setRequestHeader("Content-type",
116             theRequest.getContentType());
117
118         // Add the other header fields
119
addHeaders(theRequest);
120
121         // Add the POST parameters if no user data has been specified (user data
122
// overried post parameters)
123
if (theRequest.getUserData() != null)
124         {
125             addUserData(theRequest);
126         }
127         else
128         {
129             addHttpPostParameters(theRequest);
130         }
131
132         // Add the cookies to the state
133
state.addCookies(CookieUtil.createHttpClientCookies(theRequest,
134             url));
135
136         // Open the connection and get the result
137
HttpClient client = new HttpClient();
138         HostConfiguration hostConfiguration = new HostConfiguration();
139         hostConfiguration.setHost(url.getHost(), url.getPort(),
140             Protocol.getProtocol(url.getProtocol()));
141         client.setState(state);
142         client.executeMethod(hostConfiguration, this.method);
143
144         // Wrap the HttpClient method in a java.net.HttpURLConnection object
145
return new org.apache.commons.httpclient.util.HttpURLConnection(
146             this.method, url);
147     }
148     
149     /**
150      * Add the HTTP parameters that need to be passed in the request body.
151      *
152      * @param theRequest the request containing all data to pass to the server
153      * redirector.
154      */

155     private void addHttpPostParameters(WebRequest theRequest)
156     {
157         // If no parameters, then exit
158
if (!theRequest.getParameterNamesPost().hasMoreElements())
159         {
160             return;
161         }
162
163         Enumeration JavaDoc keys = theRequest.getParameterNamesPost();
164         List JavaDoc parameters = new ArrayList JavaDoc();
165         while (keys.hasMoreElements())
166         {
167             String JavaDoc key = (String JavaDoc) keys.nextElement();
168             String JavaDoc[] values = theRequest.getParameterValuesPost(key);
169             for (int i = 0; i < values.length; i++)
170             {
171                 parameters.add(new NameValuePair(key, values[i]));
172             }
173         }
174         ((PostMethod) this.method).setRequestBody(
175             (NameValuePair[]) parameters.toArray(
176                 new NameValuePair[parameters.size()]));
177     }
178
179     /**
180      * Add the Headers to the request.
181      *
182      * @param theRequest the request containing all data to pass to the server
183      * redirector.
184      */

185     private void addHeaders(WebRequest theRequest)
186     {
187         Enumeration JavaDoc keys = theRequest.getHeaderNames();
188
189         while (keys.hasMoreElements())
190         {
191             String JavaDoc key = (String JavaDoc) keys.nextElement();
192             String JavaDoc[] values = theRequest.getHeaderValues(key);
193
194             StringBuffer JavaDoc fullHeaderValue = new StringBuffer JavaDoc(values[0]);
195
196             for (int i = 1; i < values.length; i++)
197             {
198                 fullHeaderValue.append("," + values[i]);
199             }
200
201             this.method.addRequestHeader(key, fullHeaderValue.toString());
202         }
203     }
204
205     /**
206      * Add user data in the request body.
207      *
208      * @param theRequest the request containing all data to pass to the server
209      * redirector.
210      * @exception IOException if we fail to read the user data
211      */

212     private void addUserData(WebRequest theRequest) throws IOException JavaDoc
213     {
214         // If no user data, then exit
215
if (theRequest.getUserData() == null)
216         {
217             return;
218         }
219
220         ((PostMethod) this.method).setRequestBody(theRequest.getUserData());
221     }
222 }
223
Popular Tags