Save This Page
Home » glassfish-v2ur2-b04-src » javax » servlet » http » [javadoc | source]
    1   
    2   
    3   /*
    4    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
    5    * 
    6    * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
    7    * 
    8    * Portions Copyright Apache Software Foundation.
    9    * 
   10    * The contents of this file are subject to the terms of either the GNU
   11    * General Public License Version 2 only ("GPL") or the Common Development
   12    * and Distribution License("CDDL") (collectively, the "License").  You
   13    * may not use this file except in compliance with the License. You can obtain
   14    * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
   15    * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
   16    * language governing permissions and limitations under the License.
   17    * 
   18    * When distributing the software, include this License Header Notice in each
   19    * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
   20    * Sun designates this particular file as subject to the "Classpath" exception
   21    * as provided by Sun in the GPL Version 2 section of the License file that
   22    * accompanied this code.  If applicable, add the following below the License
   23    * Header, with the fields enclosed by brackets [] replaced by your own
   24    * identifying information: "Portions Copyrighted [year]
   25    * [name of copyright owner]"
   26    * 
   27    * Contributor(s):
   28    * 
   29    * If you wish your version of this file to be governed by only the CDDL or
   30    * only the GPL Version 2, indicate your decision by adding "[Contributor]
   31    * elects to include this software in this distribution under the [CDDL or GPL
   32    * Version 2] license."  If you don't indicate a single choice of license, a
   33    * recipient has the option to distribute your version of this file under
   34    * either the CDDL, the GPL Version 2 or to extend the choice of license to
   35    * its licensees as provided above.  However, if you add GPL Version 2 code
   36    * and therefore, elected the GPL Version 2 license, then the option applies
   37    * only if the new code is made subject to such option by the copyright
   38    * holder.
   39    */
   40   
   41   
   42   package javax.servlet.http;
   43   
   44   import javax.servlet.ServletInputStream;
   45   import java.util.Hashtable;
   46   import java.util.ResourceBundle;
   47   import java.util.StringTokenizer;
   48   import java.io.IOException;
   49   
   50   /**
   51    * @deprecated		As of Java(tm) Servlet API 2.3. 
   52    *			These methods were only useful
   53    *			with the default encoding and have been moved
   54    *			to the request interfaces.
   55    *
   56   */
   57   
   58   
   59   public class HttpUtils {
   60   
   61       private static final String LSTRING_FILE =
   62   	"javax.servlet.http.LocalStrings";
   63       private static ResourceBundle lStrings =
   64   	ResourceBundle.getBundle(LSTRING_FILE);
   65           
   66       
   67       
   68       /**
   69        * Constructs an empty <code>HttpUtils</code> object.
   70        *
   71        */
   72   
   73       public HttpUtils() {}
   74       
   75       
   76       
   77       
   78   
   79       /**
   80        *
   81        * Parses a query string passed from the client to the
   82        * server and builds a <code>HashTable</code> object
   83        * with key-value pairs. 
   84        * The query string should be in the form of a string
   85        * packaged by the GET or POST method, that is, it
   86        * should have key-value pairs in the form <i>key=value</i>,
   87        * with each pair separated from the next by a &amp; character.
   88        *
   89        * <p>A key can appear more than once in the query string
   90        * with different values. However, the key appears only once in 
   91        * the hashtable, with its value being
   92        * an array of strings containing the multiple values sent
   93        * by the query string.
   94        * 
   95        * <p>The keys and values in the hashtable are stored in their
   96        * decoded form, so
   97        * any + characters are converted to spaces, and characters
   98        * sent in hexadecimal notation (like <i>%xx</i>) are
   99        * converted to ASCII characters.
  100        *
  101        * @param s		a string containing the query to be parsed
  102        *
  103        * @return		a <code>HashTable</code> object built
  104        * 			from the parsed key-value pairs
  105        *
  106        * @exception IllegalArgumentException	if the query string 
  107        *						is invalid
  108        *
  109        */
  110   
  111       static public Hashtable parseQueryString(String s) {
  112   
  113   	String valArray[] = null;
  114   	
  115   	if (s == null) {
  116   	    throw new IllegalArgumentException();
  117   	}
  118   	Hashtable ht = new Hashtable();
  119   	StringBuffer sb = new StringBuffer();
  120   	StringTokenizer st = new StringTokenizer(s, "&");
  121   	while (st.hasMoreTokens()) {
  122   	    String pair = (String)st.nextToken();
  123   	    int pos = pair.indexOf('=');
  124   	    if (pos == -1) {
  125   		// XXX
  126   		// should give more detail about the illegal argument
  127   		throw new IllegalArgumentException();
  128   	    }
  129   	    String key = parseName(pair.substring(0, pos), sb);
  130   	    String val = parseName(pair.substring(pos+1, pair.length()), sb);
  131   	    if (ht.containsKey(key)) {
  132   		String oldVals[] = (String []) ht.get(key);
  133   		valArray = new String[oldVals.length + 1];
  134   		for (int i = 0; i < oldVals.length; i++) 
  135   		    valArray[i] = oldVals[i];
  136   		valArray[oldVals.length] = val;
  137   	    } else {
  138   		valArray = new String[1];
  139   		valArray[0] = val;
  140   	    }
  141   	    ht.put(key, valArray);
  142   	}
  143   	return ht;
  144       }
  145   
  146   
  147   
  148   
  149       /**
  150        *
  151        * Parses data from an HTML form that the client sends to 
  152        * the server using the HTTP POST method and the 
  153        * <i>application/x-www-form-urlencoded</i> MIME type.
  154        *
  155        * <p>The data sent by the POST method contains key-value
  156        * pairs. A key can appear more than once in the POST data
  157        * with different values. However, the key appears only once in 
  158        * the hashtable, with its value being
  159        * an array of strings containing the multiple values sent
  160        * by the POST method.
  161        *
  162        * <p>The keys and values in the hashtable are stored in their
  163        * decoded form, so
  164        * any + characters are converted to spaces, and characters
  165        * sent in hexadecimal notation (like <i>%xx</i>) are
  166        * converted to ASCII characters.
  167        *
  168        *
  169        *
  170        * @param len	an integer specifying the length,
  171        *			in characters, of the 
  172        *			<code>ServletInputStream</code>
  173        *			object that is also passed to this
  174        *			method
  175        *
  176        * @param in	the <code>ServletInputStream</code>
  177        *			object that contains the data sent
  178        *			from the client
  179        * 
  180        * @return		a <code>HashTable</code> object built
  181        *			from the parsed key-value pairs
  182        *
  183        *
  184        * @exception IllegalArgumentException	if the data
  185        *			sent by the POST method is invalid
  186        *
  187        */
  188        
  189   
  190       static public Hashtable parsePostData(int len, 
  191   					  ServletInputStream in)
  192       {
  193   	// XXX
  194   	// should a length of 0 be an IllegalArgumentException
  195   	
  196   	if (len <=0)
  197   	    return new Hashtable(); // cheap hack to return an empty hash
  198   
  199   	if (in == null) {
  200   	    throw new IllegalArgumentException();
  201   	}
  202   	
  203   	//
  204   	// Make sure we read the entire POSTed body.
  205   	//
  206           byte[] postedBytes = new byte [len];
  207           try {
  208               int offset = 0;
  209          
  210   	    do {
  211   		int inputLen = in.read (postedBytes, offset, len - offset);
  212   		if (inputLen <= 0) {
  213   		    String msg = lStrings.getString("err.io.short_read");
  214   		    throw new IllegalArgumentException (msg);
  215   		}
  216   		offset += inputLen;
  217   	    } while ((len - offset) > 0);
  218   
  219   	} catch (IOException e) {
  220   	    throw new IllegalArgumentException(e.getMessage());
  221   	}
  222   
  223           // XXX we shouldn't assume that the only kind of POST body
  224           // is FORM data encoded using ASCII or ISO Latin/1 ... or
  225           // that the body should always be treated as FORM data.
  226           //
  227   
  228           try {
  229               String postedBody = new String(postedBytes, 0, len, "8859_1");
  230               return parseQueryString(postedBody);
  231           } catch (java.io.UnsupportedEncodingException e) {
  232               // XXX function should accept an encoding parameter & throw this
  233               // exception.  Otherwise throw something expected.
  234               throw new IllegalArgumentException(e.getMessage());
  235           }
  236       }
  237   
  238   
  239   
  240   
  241       /*
  242        * Parse a name in the query string.
  243        */
  244   
  245       static private String parseName(String s, StringBuffer sb) {
  246   	sb.setLength(0);
  247   	for (int i = 0; i < s.length(); i++) {
  248   	    char c = s.charAt(i); 
  249   	    switch (c) {
  250   	    case '+':
  251   		sb.append(' ');
  252   		break;
  253   	    case '%':
  254   		try {
  255   		    sb.append((char) Integer.parseInt(s.substring(i+1, i+3), 
  256   						      16));
  257   		    i += 2;
  258   		} catch (NumberFormatException e) {
  259   		    // XXX
  260   		    // need to be more specific about illegal arg
  261   		    throw new IllegalArgumentException();
  262   		} catch (StringIndexOutOfBoundsException e) {
  263   		    String rest  = s.substring(i);
  264   		    sb.append(rest);
  265   		    if (rest.length()==2)
  266   			i++;
  267   		}
  268   		
  269   		break;
  270   	    default:
  271   		sb.append(c);
  272   		break;
  273   	    }
  274   	}
  275   	return sb.toString();
  276       }
  277   
  278   
  279   
  280   
  281       /**
  282        *
  283        * Reconstructs the URL the client used to make the request,
  284        * using information in the <code>HttpServletRequest</code> object.
  285        * The returned URL contains a protocol, server name, port
  286        * number, and server path, but it does not include query
  287        * string parameters.
  288        * 
  289        * <p>Because this method returns a <code>StringBuffer</code>,
  290        * not a string, you can modify the URL easily, for example,
  291        * to append query parameters.
  292        *
  293        * <p>This method is useful for creating redirect messages
  294        * and for reporting errors.
  295        *
  296        * @param req	a <code>HttpServletRequest</code> object
  297        *			containing the client's request
  298        * 
  299        * @return		a <code>StringBuffer</code> object containing
  300        *			the reconstructed URL
  301        *
  302        */
  303   
  304       public static StringBuffer getRequestURL (HttpServletRequest req) {
  305   	StringBuffer url = new StringBuffer ();
  306   	String scheme = req.getScheme ();
  307   	int port = req.getServerPort ();
  308   	String urlPath = req.getRequestURI();
  309   	
  310   	//String		servletPath = req.getServletPath ();
  311   	//String		pathInfo = req.getPathInfo ();
  312   
  313   	url.append (scheme);		// http, https
  314   	url.append ("://");
  315   	url.append (req.getServerName ());
  316   	if ((scheme.equals ("http") && port != 80)
  317   		|| (scheme.equals ("https") && port != 443)) {
  318   	    url.append (':');
  319   	    url.append (req.getServerPort ());
  320   	}
  321   	//if (servletPath != null)
  322   	//    url.append (servletPath);
  323   	//if (pathInfo != null)
  324   	//    url.append (pathInfo);
  325   	url.append(urlPath);
  326   	return url;
  327       }
  328   }
  329   
  330   
  331   

Save This Page
Home » glassfish-v2ur2-b04-src » javax » servlet » http » [javadoc | source]