KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > http > HttpUtils


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  *
22  * $Id: HttpUtils.java,v 1.3 2005/03/24 10:51:20 slobodan Exp $
23  */

24
25
26
27
28 package com.lutris.http;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.net.URLDecoder JavaDoc;
32 import java.util.Hashtable JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34
35 import com.lutris.appserver.server.httpPresentation.HttpPresentationException;
36 import com.lutris.appserver.server.httpPresentation.HttpPresentationRequest;
37
38 /**
39  * Utility methods useful to for HTTP.
40  */

41 public class HttpUtils {
42     /**
43      * Adds the pair <b>key</b> and <b>value</b> to <b>table</b>.
44      * If <b>key</b> already exists, then <b>value</b> is added
45      * as the end of an array of existing values, and
46      * the new array is assigned as the value for <b>key</b>.
47      * If <b>key</b> does not yet exist, the <b>value</b> is assigned
48      * as the value for <b>key</b>.
49      *
50      * @param table The table to add to.
51      * @param key The key to assign the value to.
52      * @param value The value to assign
53      */

54     private static
55     void AddKey(Hashtable JavaDoc table, String JavaDoc key, String JavaDoc value)
56     {
57     Object JavaDoc obj = table.get(key);
58     if (obj == null) {
59         // First time "key" appears.
60
table.put(key, value);
61     } else {
62         if (obj instanceof String JavaDoc) {
63         // Second time. Entry becomes an array of String.
64
String JavaDoc[] newarray = new String JavaDoc[2];
65         newarray[0] = obj.toString();
66         newarray[1] = value;
67         table.put(key, newarray);
68         newarray = null;
69         } else if (obj instanceof String JavaDoc[]) {
70         // Third and subsequent times.
71
String JavaDoc[] oldarray = (String JavaDoc[]) obj;
72         String JavaDoc[] newarray = new String JavaDoc[oldarray.length +1];
73         for (int i=0; i<oldarray.length; i++) {
74             newarray[i] = oldarray[i];
75         }
76         newarray[oldarray.length] = value;
77         oldarray = null;
78         table.put(key, newarray);
79         newarray = null;
80         } else {
81         // We should never see anything other than String
82
// or String[] in this hash table.
83
throw new Error JavaDoc("Internal Error - "
84             + "Unexpected type in QueryString Hashtable.");
85         }
86     }
87     }
88
89     /**
90      * Trims the left-hand side of a URL until the character '?'
91      * is reached. This is useful for raw URLs that need to be
92      * parsed as query strings.
93      *
94      * @param s The string to trim.
95      * @return The trimmed string.
96      */

97     public static
98     String JavaDoc trimQueryString(String JavaDoc s)
99     {
100     int pos = s.indexOf("?");
101     if (pos >= 0) return s.substring(pos+1);
102     return s;
103     }
104     
105     /**
106      * Decodes a query string in the format specified by the MIME
107      * type <code>"application/x-www-form-urlencoded"</code>. Such a
108      * string consists of encoded key/value pairs in the form
109      * <code>key=value</code>. A hash table is returned with each
110      * value indexed by its corresponding key. If a key appears once
111      * in the query string, then the value will be of type
112      * <code>String</code>. If the key appears more than once, then
113      * the value will be an array of type <code>String</code>.
114      *
115      * @param s The string to parse.
116      * @return A Hashtable containing the values indexed by
117      * their corresponding keys.
118      */

119     public static
120     Hashtable JavaDoc parseQueryString(String JavaDoc s)
121     {
122     String JavaDoc qs = s.replace('?', '&');
123     StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(qs, "&", false);
124     Hashtable JavaDoc table = new Hashtable JavaDoc();
125     String JavaDoc pair, key, value;
126     while (tok.hasMoreTokens()) {
127         pair = tok.nextToken();
128         int i = pair.indexOf("=");
129         if (i >= 0) {
130         key = URLDecoder.decode(pair.substring(0, i));
131         value = URLDecoder.decode(pair.substring(i+1));
132         AddKey(table, key, value);
133         } else {
134         int j = pair.indexOf(",");
135         if (j >= 0) {
136             // Might be an image map coord. pair.
137
String JavaDoc xstr = pair.substring(0, j).trim();
138             xstr = URLDecoder.decode(xstr);
139             String JavaDoc ystr = pair.substring(j+1).trim();
140             ystr = URLDecoder.decode(ystr);
141             try {
142             int xcoord = Integer.parseInt(xstr, 10);
143             int ycoord = Integer.parseInt(ystr, 10);
144             // Yes, we have image map coordinates.
145
AddKey(table, "_imap_x", "" + xcoord);
146             AddKey(table, "_imap_y", "" + ycoord);
147             } catch (Throwable JavaDoc t) {
148             AddKey(table, "_garbage", URLDecoder.decode(pair));
149             }
150         } else {
151             AddKey(table, "_garbage", URLDecoder.decode(pair));
152         }
153         }
154         
155     }
156     return table;
157     }
158     
159     /**
160      * Parses FORM data posted by a client using the HTTP POST method
161      * and the <code>application/x-www-form-urlencoded</code> MIME type.
162      *
163      * @param len The maximum number of bytes to read from the input
164      * stream.
165      * @param in The input stream from which to read the form data.
166      * @return A Hashtable containing the values indexed by
167      * their corresponding keys.
168      * @exception IllegalArgumentException If the query string is
169      * not formatted correctly.
170      * @exception IOException If an I/O error occurs while reading the
171      * input stream.
172      */

173     public static
174     Hashtable JavaDoc parsePostData(int len, InputStream JavaDoc in)
175     throws IllegalArgumentException JavaDoc, IOException JavaDoc
176     {
177     byte[] bytes = new byte[len];
178     int n, count=0;
179     boolean eof=false;
180     while ((count<len)&&((n = in.read(bytes, count, len - count)) >0))
181         count += n;
182     char[] chars = new char[count];
183     // Convert signed bytes directly to ASCII compatibility Unicode
184
// chars using two's complement byte signed-unsigned conversion.
185
for (n=0; n<count; n++) chars[n] = (char)((((int)bytes[n])+0x100)&0xff);
186     bytes = null;
187     return parseQueryString(new String JavaDoc(chars));
188     }
189     
190     /**
191      * Obtains the URL used by the client to make the current request,
192      * without the query parameters. Returns a StringBuffer object that
193      * can be appended to, if the query string must be appended.
194      *
195      * @param req presentation request object from which
196      * to extract the URL.
197      * @return A string buffer object containing the extracted
198      * URL.
199      * @exception HttpPresentationException If an exception is generated
200      * by the <code>req</code> object.
201      */

202     public static
203     StringBuffer JavaDoc getRequestURL(HttpPresentationRequest req)
204     throws HttpPresentationException
205     {
206     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
207     buf.append("http://");
208     buf.append(req.getServerName());
209     int port = req.getServerPort();
210     if (port != 80) buf.append(":" + port);
211     buf.append(req.getRequestURI());
212     return buf;
213     }
214 }
215
216
Popular Tags