KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > http > client > RequestBuilder


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

16 package com.google.gwt.http.client;
17
18 import com.google.gwt.core.client.GWT;
19 import com.google.gwt.core.client.JavaScriptObject;
20 import com.google.gwt.user.client.impl.HTTPRequestImpl;
21
22 import java.util.HashMap JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Set JavaDoc;
26
27 /**
28  * Builder for constructing {@link com.google.gwt.http.client.Request} objects.
29  *
30  * <p>
31  * By default, this builder is restricted to building HTTP GET and POST requests
32  * due to a bug in Safari's implementation of the <code>XmlHttpRequest</code>
33  * object.
34  * </p>
35  *
36  * <p>
37  * Please see <a HREF="http://bugs.webkit.org/show_bug.cgi?id=3812">
38  * http://bugs.webkit.org/show_bug.cgi?id=3812</a> for more details.
39  * </p>
40  *
41  * <h3>Required Module</h3>
42  * Modules that use this class should inherit
43  * <code>com.google.gwt.http.HTTP</code>.
44  *
45  * {@gwt.include com/google/gwt/examples/http/InheritsExample.gwt.xml}
46  *
47  */

48 public class RequestBuilder {
49   /**
50    * HTTP request method constants.
51    */

52   public static final class Method {
53     private final String JavaDoc name;
54
55     private Method(String JavaDoc name) {
56       this.name = name;
57     }
58
59     public String JavaDoc toString() {
60       return name;
61     }
62   }
63
64   /**
65    * Specifies that the HTTP GET method should be used.
66    */

67   public static final Method GET = new Method("GET");
68
69   /**
70    * Specifies that the HTTP POST method should be used.
71    */

72   public static final Method POST = new Method("POST");
73
74   private static final HTTPRequestImpl httpRequest = (HTTPRequestImpl) GWT.create(HTTPRequestImpl.class);
75
76   /*
77    * Map of header name to value that will be added to the JavaScript
78    * XmlHttpRequest object before sending a request.
79    */

80   private Map JavaDoc headers;
81
82   /*
83    * HTTP method to use when opening an JavaScript XmlHttpRequest object
84    */

85   private String JavaDoc httpMethod;
86
87   /*
88    * Password to use when opening an JavaScript XmlHttpRequest object
89    */

90   private String JavaDoc password;
91
92   /*
93    * Timeout in milliseconds before the request timeouts and fails.
94    */

95   private int timeoutMillis;
96
97   /*
98    * URL to use when opening an JavaScript XmlHttpRequest object.
99    */

100   private String JavaDoc url;
101
102   /*
103    * User to use when opening an JavaScript XmlHttpRequest object
104    */

105   private String JavaDoc user;
106
107   /**
108    * Creates a builder using the parameters for configuration.
109    *
110    * @param httpMethod HTTP method to use for the request
111    * @param url URL that has already has already been encoded. Please see
112    * {@link com.google.gwt.http.client.URL#encode(String)} and
113    * {@link com.google.gwt.http.client.URL#encodeComponent(String)} for
114    * how to do this.
115    * @throws IllegalArgumentException if the httpMethod or URL are empty
116    * @throws NullPointerException if the httpMethod or the URL are null
117    */

118   public RequestBuilder(Method httpMethod, String JavaDoc url) {
119     this((httpMethod == null) ? null : httpMethod.toString(), url);
120   }
121
122   /**
123    * Creates a builder using the parameters values for configuration.
124    *
125    * @param httpMethod HTTP method to use for the request
126    * @param url URL that has already has already been URL encoded. Please see
127    * {@link com.google.gwt.http.client.URL#encode(String)} and
128    * {@link com.google.gwt.http.client.URL#encodeComponent(String)} for
129    * how to do this.
130    * @throws IllegalArgumentException if the httpMethod or URL are empty
131    * @throws NullPointerException if the httpMethod or the URL are null
132    *
133    * <p>
134    * <b>WARNING:</b>This method is provided in order to allow the creation of
135    * HTTP request other than GET and POST to be made. If this is done, the
136    * developer must accept that the behavior on Safari is undefined.
137    * </p>
138    */

139   protected RequestBuilder(String JavaDoc httpMethod, String JavaDoc url) {
140
141     StringValidator.throwIfEmptyOrNull("httpMethod", httpMethod);
142     StringValidator.throwIfEmptyOrNull("url", url);
143
144     this.httpMethod = httpMethod;
145     this.url = url;
146   }
147
148   /**
149    * Sends an HTTP request based on the current builder configuration. If no
150    * request headers have been set, the header "Content-Type" will be used with
151    * a value of "text/plain; charset=utf-8".
152    *
153    * @param requestData the data to send as part of the request
154    * @param callback the response handler to be notified when the request fails
155    * or completes
156    * @return a {@link Request} object that can be used to track the request
157    */

158   public Request sendRequest(String JavaDoc requestData, RequestCallback callback)
159       throws RequestException {
160     JavaScriptObject xmlHttpRequest = httpRequest.createXmlHTTPRequest();
161
162     String JavaDoc openError = XMLHTTPRequest.open(xmlHttpRequest, httpMethod, url,
163         true, user, password);
164     if (openError != null) {
165       throw new RequestPermissionException(url);
166     }
167
168     setHeaders(xmlHttpRequest);
169
170     Request request = new Request(xmlHttpRequest, timeoutMillis, callback);
171
172     String JavaDoc sendError = XMLHTTPRequest.send(xmlHttpRequest, request,
173         requestData, callback);
174     if (sendError != null) {
175       throw new RequestException(sendError);
176     }
177
178     return request;
179   }
180
181   /**
182    * Sets a request header with the given name and value. If a header with the
183    * specified name has already been set then the new value overwrites the
184    * current value.
185    *
186    * @param header the name of the header
187    * @param value the value of the header
188    *
189    * @throws NullPointerException if header or value are null
190    * @throws IllegalArgumentException if header or value are the empty string
191    */

192   public void setHeader(String JavaDoc header, String JavaDoc value) {
193     StringValidator.throwIfEmptyOrNull("header", header);
194     StringValidator.throwIfEmptyOrNull("value", value);
195
196     if (headers == null) {
197       headers = new HashMap JavaDoc();
198     }
199
200     headers.put(header, value);
201   }
202
203   /**
204    * Sets the password to use in the request URL. This is ignored if there is no
205    * user specified.
206    *
207    * @param password password to use in the request URL
208    *
209    * @throws IllegalArgumentException if the password is empty
210    * @throws NullPointerException if the password is null
211    */

212   public void setPassword(String JavaDoc password) {
213     StringValidator.throwIfEmptyOrNull("password", password);
214
215     this.password = password;
216   }
217
218   /**
219    * Sets the number of milliseconds to wait for a request to complete. Should
220    * the request timeout, the
221    * {@link com.google.gwt.http.client.RequestCallback#onError(Request, Throwable)}
222    * method will be called on the callback instance given to the
223    * {@link com.google.gwt.http.client.RequestBuilder#sendRequest(String, RequestCallback)}
224    * method. The callback method will receive an instance of the
225    * {@link com.google.gwt.http.client.RequestTimeoutException} class as its
226    * {@link java.lang.Throwable} argument.
227    *
228    * @param timeoutMillis number of milliseconds to wait before canceling the
229    * request, a value of zero disables timeouts
230    *
231    * @throws IllegalArgumentException if the timeout value is negative
232    */

233   public void setTimeoutMillis(int timeoutMillis) {
234     if (timeoutMillis < 0) {
235       throw new IllegalArgumentException JavaDoc("Timeouts cannot be negative");
236     }
237
238     this.timeoutMillis = timeoutMillis;
239   }
240
241   /**
242    * Sets the user name that will be used in the request URL.
243    *
244    * @param user user name to use
245    * @throws IllegalArgumentException if the user is empty
246    * @throws NullPointerException if the user is null
247    */

248   public void setUser(String JavaDoc user) {
249     StringValidator.throwIfEmptyOrNull("user", user);
250
251     this.user = user;
252   }
253
254   /*
255    * Internal method that actually sets our cached headers on the underlying
256    * JavaScript XmlHttpRequest object. If there are no headers set, then we set
257    * the "Content-Type" to "text/plain; charset=utf-8". This is really lining us
258    * up for integration with RPC.
259    */

260   private void setHeaders(JavaScriptObject xmlHttpRequest)
261       throws RequestException {
262     if (headers != null && headers.size() > 0) {
263       Set JavaDoc entrySet = headers.entrySet();
264       Iterator JavaDoc iter = entrySet.iterator();
265       while (iter.hasNext()) {
266         Map.Entry JavaDoc header = (Map.Entry JavaDoc) iter.next();
267         String JavaDoc errorMessage = XMLHTTPRequest.setRequestHeader(xmlHttpRequest,
268             (String JavaDoc) header.getKey(), (String JavaDoc) header.getValue());
269         if (errorMessage != null) {
270           throw new RequestException(errorMessage);
271         }
272       }
273     } else {
274       XMLHTTPRequest.setRequestHeader(xmlHttpRequest, "Content-Type",
275           "text/plain; charset=utf-8");
276     }
277   }
278 }
279
Popular Tags