KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > matuschek > http > HttpDoc


1 package net.matuschek.http;
2
3 import java.net.URL JavaDoc;
4 import java.util.Date JavaDoc;
5 import java.util.Iterator JavaDoc;
6 import java.util.List JavaDoc;
7 import java.util.StringTokenizer JavaDoc;
8 import java.util.Vector JavaDoc;
9 import net.matuschek.util.MD5;
10
11 /*********************************************
12     Copyright (c) 2001 by Daniel Matuschek
13 *******************************************/

14
15 /**
16  * A HTTP document. It consists of the contents and HTTP headers.
17  *
18  * @author Daniel Matuschek (daniel@matuschek.net)
19  * @author ptah
20  * @version $Id: HttpDoc.java,v 1.11 2004/08/09 17:36:49 matuschd Exp $
21  */

22 public class HttpDoc {
23   /** The content */
24   private byte[] content;
25
26   /**
27    * The HTTP header lines
28    *
29    * @link aggregation
30    * @associates <{HttpHeader}>
31    */

32   private Vector JavaDoc<HttpHeader> httpHeader;
33   
34   /** place to store links of the document if necessary */
35   private List JavaDoc links;
36
37   private int httpReturnCode=0;
38   private URL JavaDoc url;
39   
40   /** flag that indicates if this document is retrieved from cache */
41   private boolean cached = false;
42
43   private final static int HTTP_REDIRECTSTART=300;
44   private final static int HTTP_REDIRECTEND=399;
45
46
47
48   /**
49    * Default constructor, initializes a new HttpDoc with
50    * empty headers and no content
51    */

52   public HttpDoc() {
53     httpHeader = new Vector JavaDoc<HttpHeader>();
54   }
55  
56   /**
57    * Gets the content of the document
58    *
59    * @return an array of bytes containing the document content. This
60    * may represent text or binary data
61    */

62   public byte[] getContent() {
63     return content;
64   }
65  
66   /**
67    * Set the content of the document
68    *
69    * @param content
70    */

71   public void setContent(byte[] content) {
72     this.content = content;
73     // existing MD5 keys become invalid
74
removeHeader(HttpHeader.CONTENT_MD5);
75   }
76   
77   public void setHttpCode(String JavaDoc httpCode) {
78     StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(httpCode," ");
79     // an HTTP answer must have at least 2 fields
80
if (st.countTokens() < 2) {
81       return;
82     }
83    
84     st.nextToken();
85     String JavaDoc codeStr = st.nextToken();
86     
87     try {
88       httpReturnCode = Integer.parseInt(codeStr);
89     } catch (NumberFormatException JavaDoc e) {
90       // something is wrong !!!
91
}
92   }
93   
94   public void setHttpCode(int code) {
95     httpReturnCode = code;
96   }
97
98   /**
99    * Get the Http Return-Code
100    *
101    * @return Http Return-Code
102    */

103   public int getHttpCode() {
104       return httpReturnCode;
105   }
106
107   /**
108    * Add another HTTP header
109    *
110    * @param header an HttpHeader object to add to the lis
111    * of headers
112    */

113   public void addHeader(HttpHeader header) {
114     httpHeader.add(header);
115   }
116   
117   /**
118    * Get all HTTP header lines
119    *
120    * @return a Vector of HttpHeader objects
121    */

122   public Vector JavaDoc getHttpHeader() {
123     return httpHeader;
124   }
125
126   /**
127    * Get the HTTP header with the given name
128    * @param headerName
129    *
130    * @return a HttpHeader with the given name or null if not found
131    */

132   public HttpHeader getHttpHeader(String JavaDoc headerName) {
133     for (Iterator JavaDoc iter = httpHeader.iterator(); iter.hasNext();) {
134         HttpHeader header = (HttpHeader) iter.next();
135         if (header.getName().equals(headerName)) {
136             return header;
137         }
138     }
139     return null;
140   }
141   
142   /**
143    * Get the header value with the given name
144    * @param headerName
145    *
146    * @return a HttpHeader.value with the given name or null if not found
147    */

148   public String JavaDoc getHeaderValue(String JavaDoc headerName) {
149     HttpHeader header = getHeader(headerName);
150     return header != null ? header.getValue() : null;
151   }
152
153   /**
154    * Set a HTTP header value with the given name (creates one if not found)
155    * @param headerName
156    * @param headerValue
157    *
158    * @return a HttpHeader.value with the given name or null if not found
159    */

160   public void setHeaderValue(String JavaDoc headerName, String JavaDoc headerValue) {
161       HttpHeader header = getHeader(headerName);
162       if (header == null) {
163           header = new HttpHeader(headerName, headerValue);
164           addHeader(header);
165       } else {
166           header.setValue(headerValue);
167       }
168   }
169
170   /**
171    * Get the content of the Location header. This header will
172    * be used for REDIRECTs.
173    *
174    * @return the value of the HTTP Location header.
175    */

176   public String JavaDoc getLocation() {
177     HttpHeader location= getHeader(HttpHeader.LOCATION);
178     if (location == null) {
179       return "";
180     } else {
181       return location.getValue();
182     }
183   }
184
185   /**
186    * Was it a redirect ?
187    *
188    * @return true if this document is a HTTP REDIRECT
189    */

190   public boolean isRedirect() {
191     if ((httpReturnCode >= HTTP_REDIRECTSTART) &&
192     (httpReturnCode <= HTTP_REDIRECTEND)) {
193       return true;
194     } else {
195       return false;
196     }
197   }
198
199   /**
200    * Was it a "normal" document ?
201    */

202   public boolean isOk() {
203     return (httpReturnCode == HttpConstants.HTTP_OK);
204   }
205
206   /**
207    * Was it not modified ?
208    */

209   public boolean isNotModified() {
210     return (getHttpCode() == HttpConstants.HTTP_NOTMODIFIED);
211   }
212   
213   /**
214    * Was it not found ?
215    */

216   public boolean isNotFound() {
217     return (httpReturnCode == HttpConstants.HTTP_NOTFOUND);
218   }
219
220   /**
221    * did we get "Authorization required"
222    */

223   public boolean isUnauthorized() {
224     return (httpReturnCode == HttpConstants.HTTP_UNAUTHORIZED);
225   }
226
227   /**
228    * Gets the HttpHeader with the given name
229    *
230    * @param headerName
231    */

232   public HttpHeader getHeader(String JavaDoc name) {
233     for (int i=0; i<httpHeader.size(); i++) {
234       HttpHeader h = (HttpHeader)httpHeader.elementAt(i);
235       if (name.equalsIgnoreCase(h.getName())) {
236     return h;
237       }
238     }
239     return null;
240   }
241
242   /**
243    * Removes the HttpHeader with the given name
244    *
245    * @param headerName
246    */

247   public HttpHeader removeHeader(String JavaDoc name) {
248     HttpHeader header = getHeader(name);
249     if (header != null) {
250         httpHeader.remove(header);
251     }
252     return header;
253   }
254   
255   /**
256    * Get all the HTTP headers. This function is useful if you
257    * don't know what headers exists and you want to have ALL
258    * headers
259    *
260    * @return a Vector containing HttpHeader objects
261    */

262   public Vector JavaDoc getHttpHeaders() {
263     return httpHeader;
264   }
265   
266
267   /**
268    * is the content-type text/html ?
269    *
270    * @return true if the HTTP Content-Type header has the
271    * value text/html
272    */

273   public boolean isHTML() {
274     HttpHeader ct = getHeader(HttpHeader.CONTENT_TYPE);
275     if (ct==null) {
276       return false;
277     } else {
278       if (ct.getValue().toLowerCase().startsWith("text/html")) {
279     return true;
280       }
281     }
282     return false;
283   }
284   
285   /**
286    * is this a Javascript document ?
287    *
288    * @return true if the Content-Type is text/x-javascript
289    */

290   public boolean isJavaScript(){
291        HttpHeader ct = getHeader(HttpHeader.CONTENT_TYPE);
292     if (ct==null) {
293       return false;
294     } else {
295       if (ct.getValue().equalsIgnoreCase("text/x-javascript")) {
296     return true;
297       }
298     }
299     return false;
300   }
301
302
303   /**
304    * Convert this object to a String.
305    *
306    * @return a String representation of this HttpDoc. Format
307    * may change, therefore this should be used only for
308    * logging or debugging
309    */

310   public String JavaDoc toString() {
311     StringBuffer JavaDoc res = new StringBuffer JavaDoc();
312   
313     res.append(url.toString()+"\n\n");
314
315     for (int i=0; i<httpHeader.size(); i++) {
316       HttpHeader h = (HttpHeader)httpHeader.elementAt(i);
317       res.append(h.toString());
318       res.append("\n");
319     }
320     res.append("\n");
321     if (content != null) {
322         res.append(new String JavaDoc(content));
323     }
324    
325     return res.toString();
326   }
327   /**
328    * Get the full URL where this document was retrieved from
329    *
330    * @return an URL object containing the location where this
331    * document was retrieved from
332    */

333   public URL JavaDoc getURL() {
334     return url;
335   }
336
337
338   /**
339    * Set the location where this document was retrieved from
340    *
341    * @param url the original location of this document
342    */

343   public void setURL(URL JavaDoc url) {
344     this.url = url;
345   }
346
347   /**
348    * Gets lastModified date as milliseconds.
349    *
350    * @return lastModified as milliseconds or -1 if not specified
351    */

352   public long getLastModifiedAsMilliSeconds() {
353     String JavaDoc value = getHeaderValue(HttpHeader.LAST_MODIFIED);
354     return value != null ? HTTPDateTool.parseDate(value) : -1;
355   }
356     
357   /**
358    * Gets date as milliseconds.
359    *
360    * @return date as milliseconds or -1 if not specified
361    */

362   public long getDateAsMilliSeconds() {
363       String JavaDoc value = getHeaderValue(HttpHeader.DATE);
364       return value != null ? HTTPDateTool.parseDate(value) : -1;
365   }
366
367   /**
368    * Sets lastModified date in milliseconds.
369    *
370    * @param lastModified in milliseconds
371    */

372   public void setLastModified(long d) {
373       String JavaDoc dateString = HTTPDateTool.rfc1123Format.format(new Date JavaDoc(d));
374       setHeaderValue(HttpHeader.LAST_MODIFIED, dateString);
375   }
376     
377   /**
378    * Sets date in milliseconds.
379    *
380    * @param lastModified in milliseconds
381    */

382   public void setDate(long d) {
383       String JavaDoc dateString = HTTPDateTool.rfc1123Format.format(new Date JavaDoc(d));
384       setHeaderValue(HttpHeader.DATE, dateString);
385   }
386   
387   /**
388    * Calculates MD5 key for given content
389    *
390    * @param content
391    * @return MD5 key for content
392    */

393   protected static String JavaDoc getContentMD5(byte[] content) {
394       if ((content == null) || (content.length == 0)) {
395           return "00000000000000000000000000000000";
396       }
397       MD5 md5 = new MD5();
398       md5.Update(content);
399       return md5.asHex();
400   }
401   
402   /**
403    * Gets MD5 key of document content.
404    * A calculated key is stored as a header and reused
405    * in successive calls of this method.
406    *
407    * @return MD5 key
408    */

409   public String JavaDoc getContentMD5() {
410       HttpHeader md5Header = getHeader(HttpHeader.CONTENT_MD5);
411       String JavaDoc md5;
412       if (md5Header != null) {
413           md5 = md5Header.getValue();
414       } else {
415           md5 = getContentMD5(getContent());
416           md5Header = new HttpHeader(HttpHeader.CONTENT_MD5, md5);
417           addHeader(md5Header);
418       }
419       return md5;
420   }
421
422
423     /**
424      * Set flag that indicates if this document is retrieved from cache
425      * @param cached
426      */

427     public void setCached(boolean cached) {
428         this.cached = cached;
429     }
430     
431     /**
432      * Was this document retrieved from cache?
433      * @return cached
434      */

435     public boolean isCached() {
436         return cached;
437     }
438
439     /**
440      * Store calculated links of a HttpDoc.
441      * @param links
442      */

443     public void setLinks(List JavaDoc links) {
444         this.links = links;
445     }
446
447     /**
448      * Gets List of links (if set previously).
449      * @return List
450      */

451     public List JavaDoc getLinks() {
452         return links;
453     }
454   
455 }
456
Popular Tags