KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lobobrowser > html > test > SimpleHttpRequest


1 /*
2     GNU LESSER GENERAL PUBLIC LICENSE
3     Copyright (C) 2006 The Lobo Project
4
5     This library is free software; you can redistribute it and/or
6     modify it under the terms of the GNU Lesser General Public
7     License as published by the Free Software Foundation; either
8     version 2.1 of the License, or (at your option) any later version.
9
10     This library is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13     Lesser General Public License for more details.
14
15     You should have received a copy of the GNU Lesser General Public
16     License along with this library; if not, write to the Free Software
17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19     Contact info: xamjadmin@users.sourceforge.net
20 */

21 /*
22  * Created on Nov 19, 2005
23  */

24 package org.lobobrowser.html.test;
25
26 import java.awt.Image JavaDoc;
27 import java.awt.Toolkit JavaDoc;
28 import java.io.ByteArrayInputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.UnsupportedEncodingException JavaDoc;
31 import java.net.HttpURLConnection JavaDoc;
32 import java.net.MalformedURLException JavaDoc;
33 import java.net.URL JavaDoc;
34 import java.net.URLConnection JavaDoc;
35 import java.util.EventObject JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.logging.*;
38
39 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
40
41 import org.lobobrowser.html.*;
42 import org.lobobrowser.util.*;
43 import org.lobobrowser.util.io.IORoutines;
44 import org.w3c.dom.Document JavaDoc;
45
46 /**
47  * The <code>SimpleHttpRequest</code> class implements
48  * the {@link org.lobobrowser.html.HttpRequest} interface.
49  * The <code>HttpRequest</code> implementation provided
50  * by this class is simple, with no caching. It creates
51  * a new thread for each new asynchronous request.
52  * @author J. H. S.
53  */

54 public class SimpleHttpRequest implements HttpRequest {
55     private static final Logger logger = Logger.getLogger(SimpleHttpRequest.class.getName());
56     private int readyState;
57     private int status;
58     private String JavaDoc statusText;
59     private byte[] responseBytes;
60     private java.util.Map JavaDoc responseHeadersMap;
61     private String JavaDoc responseHeaders;
62     private final UserAgentContext context;
63     
64     public SimpleHttpRequest(UserAgentContext context) {
65         super();
66         this.context = context;
67     }
68
69     public synchronized int getReadyState() {
70         return this.readyState;
71     }
72
73     public synchronized String JavaDoc getResponseText() {
74         byte[] bytes = this.responseBytes;
75         //TODO: proper charset
76
try {
77             return bytes == null ? null : new String JavaDoc(bytes, "ISO-8859-1");
78         } catch(UnsupportedEncodingException JavaDoc uee) {
79             return null;
80         }
81     }
82
83     public synchronized Document JavaDoc getResponseXML() {
84         byte[] bytes = this.responseBytes;
85         if(bytes == null) {
86             return null;
87         }
88         java.io.InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(bytes);
89         try {
90             return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
91         } catch(Exception JavaDoc err) {
92             logger.log(Level.WARNING, "Unable to parse response as XML.", err);
93             return null;
94         }
95     }
96
97     public synchronized byte[] getResponseBytes() {
98         return this.responseBytes;
99     }
100     
101     /* (non-Javadoc)
102      * @see org.xamjwg.html.HttpRequest#getResponseImage()
103      */

104     public synchronized Image JavaDoc getResponseImage() {
105         byte[] bytes = this.responseBytes;
106         if(bytes == null) {
107             return null;
108         }
109         return Toolkit.getDefaultToolkit().createImage(bytes);
110     }
111
112     public synchronized int getStatus() {
113         return this.status;
114     }
115
116     public synchronized String JavaDoc getStatusText() {
117         return this.statusText;
118     }
119
120     public void abort() {
121         URLConnection JavaDoc c;
122         synchronized(this) {
123             c = this.connection;
124         }
125         if(c instanceof HttpURLConnection JavaDoc) {
126             ((HttpURLConnection JavaDoc) c).disconnect();
127         }
128         else if(c != null) {
129             try {
130                 c.getInputStream().close();
131             } catch(IOException JavaDoc ioe) {
132                 ioe.printStackTrace();
133             }
134         }
135     }
136
137     public synchronized String JavaDoc getAllResponseHeaders() {
138         return this.responseHeaders;
139     }
140
141     public synchronized String JavaDoc getResponseHeader(String JavaDoc headerName) {
142         Map JavaDoc headers = this.responseHeadersMap;
143         return headers == null ? null : (String JavaDoc) headers.get(headerName);
144     }
145
146     public void open(String JavaDoc method, String JavaDoc url) {
147         this.open(method, url, true);
148     }
149
150     public void open(String JavaDoc method, URL JavaDoc url) {
151         this.open(method, url, true, null, null);
152     }
153
154     public void open(String JavaDoc method, URL JavaDoc url, boolean asyncFlag) {
155         this.open(method, url, asyncFlag, null, null);
156     }
157
158     public void open(String JavaDoc method, String JavaDoc url, boolean asyncFlag) {
159         this.open(method, url, asyncFlag, null);
160     }
161
162     public void open(String JavaDoc method, String JavaDoc url, boolean asyncFlag,
163             String JavaDoc userName) {
164         this.open(method, url, asyncFlag, userName, null);
165     }
166
167     public void open(String JavaDoc method, String JavaDoc url, boolean asyncFlag,
168             String JavaDoc userName, String JavaDoc password) {
169         try {
170             URL JavaDoc urlObj = new URL JavaDoc(url);
171             this.open(method, urlObj, asyncFlag, userName, password);
172         } catch(MalformedURLException JavaDoc mfu) {
173             logger.log(Level.WARNING,"Bad request URL:" + url, mfu);
174             this.changeState(HttpRequest.STATE_COMPLETE, 400, "Malformed URI", null);
175         }
176     }
177
178     public void open(final String JavaDoc method, final java.net.URL JavaDoc url, boolean asyncFlag,
179             final String JavaDoc userName, final String JavaDoc password) {
180         if(asyncFlag) {
181             // Should use a thread pool instead
182
new Thread JavaDoc("Request") {
183                 public void run() {
184                     openSync(method, url, userName, password);
185                 }
186             }.start();
187         }
188         else {
189             this.openSync(method, url, userName, password);
190         }
191     }
192
193     private void changeState(int readyState, int status, String JavaDoc statusMessage, byte[] bytes) {
194         synchronized(this) {
195             this.readyState = readyState;
196             this.status = status;
197             this.statusText = statusMessage;
198             this.responseBytes = bytes;
199         }
200         this.readyEvent.fireEvent(null);
201     }
202     
203     private String JavaDoc getAllResponseHeaders(URLConnection JavaDoc c) {
204         int idx = 0;
205         String JavaDoc value;
206         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
207         while((value = c.getHeaderField(idx)) != null) {
208             String JavaDoc key = c.getHeaderFieldKey(idx);
209             buf.append(key); buf.append(": "); buf.append(value);
210             idx++;
211         }
212         return buf.toString();
213     }
214     
215     private java.net.URLConnection JavaDoc connection;
216     
217     protected void openSync(String JavaDoc method, java.net.URL JavaDoc url,
218             String JavaDoc userName, String JavaDoc password) {
219         try {
220             this.abort();
221             URLConnection JavaDoc c = url.openConnection();
222             synchronized(this) {
223                 this.connection = c;
224             }
225             try {
226                 c.setRequestProperty("User-Agent", this.context.getUserAgent());
227                 this.changeState(HttpRequest.STATE_LOADING, 0, "", null);
228                 java.io.InputStream JavaDoc in = c.getInputStream();
229                 int contentLength = c.getContentLength();
230                 byte[] bytes = IORoutines.load(in, contentLength == -1 ? 4096 : contentLength);
231                 int status = 0;
232                 String JavaDoc statusText = "";
233                 if(c instanceof HttpURLConnection JavaDoc) {
234                     HttpURLConnection JavaDoc hc = (HttpURLConnection JavaDoc) c;
235                     status = hc.getResponseCode();
236                     statusText = hc.getResponseMessage();
237                 }
238                 synchronized(this) {
239                     this.responseHeaders = this.getAllResponseHeaders(c);
240                     this.responseHeadersMap = c.getHeaderFields();
241                 }
242                 this.changeState(HttpRequest.STATE_COMPLETE, status, statusText, bytes);
243             } finally {
244                 synchronized(this) {
245                     this.connection = null;
246                 }
247             }
248         } catch(Exception JavaDoc err) {
249             this.changeState(HttpRequest.STATE_COMPLETE, err instanceof java.io.FileNotFoundException JavaDoc ? 404 : 400, err.getMessage(), null);
250             logger.log(Level.WARNING, "Request failed on url=" + url, err);
251         }
252     }
253
254     private final EventDispatch readyEvent = new EventDispatch();
255     
256     public void addReadyStateChangeListener(final ReadyStateChangeListener listener) {
257         readyEvent.addListener(new GenericEventListener() {
258             public void processEvent(EventObject JavaDoc event) {
259                 listener.readyStateChanged();
260             }
261         });
262     }
263 }
264
Popular Tags