1   /*
2    * $HeadURL: http://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/trunk/src/test/org/apache/commons/httpclient/TestQueryParameters.java $
3    * $Revision: 201850 $
4    * $Date: 2005-06-26 09:36:10 -0400 (Sun, 26 Jun 2005) $
5    * ====================================================================
6    *
7    *  Copyright 1999-2004 The Apache Software Foundation
8    *
9    *  Licensed under the Apache License, Version 2.0 (the "License");
10   *  you may not use this file except in compliance with the License.
11   *  You may obtain a copy of the License at
12   *
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   *
15   *  Unless required by applicable law or agreed to in writing, software
16   *  distributed under the License is distributed on an "AS IS" BASIS,
17   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   *  See the License for the specific language governing permissions and
19   *  limitations under the License.
20   * ====================================================================
21   *
22   * This software consists of voluntary contributions made by many
23   * individuals on behalf of the Apache Software Foundation.  For more
24   * information on the Apache Software Foundation, please see
25   * <http://www.apache.org/>.
26   *
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  
33  import junit.framework.*;
34  import org.apache.commons.httpclient.methods.*;
35  import org.apache.commons.httpclient.server.HttpService;
36  import org.apache.commons.httpclient.server.SimpleRequest;
37  import org.apache.commons.httpclient.server.SimpleResponse;
38  
39  /***
40   * @author Rodney Waldhoff
41   * @version $Id: TestQueryParameters.java 201850 2005-06-26 13:36:10Z olegk $
42   */
43  public class TestQueryParameters extends HttpClientTestBase {
44  
45      public TestQueryParameters(String testName) throws Exception {
46          super(testName);
47      }
48  
49      public static Test suite() {
50          TestSuite suite = new TestSuite(TestQueryParameters.class);
51          return suite;
52      }
53  
54      public static void main(String args[]) {
55          String[] testCaseName = { TestQueryParameters.class.getName() };
56          junit.textui.TestRunner.main(testCaseName);
57      }
58  
59      // ------------------------------------------------------------------ Tests
60  
61      class QueryInfoService implements HttpService {
62  
63          public QueryInfoService() {
64              super();
65          }
66  
67          public boolean process(final SimpleRequest request, final SimpleResponse response)
68              throws IOException
69          {
70              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
71              response.setStatusLine(httpversion, HttpStatus.SC_OK);
72              response.addHeader(new Header("Content-Type", "text/plain"));
73  			
74  			URI uri = new URI(request.getRequestLine().getUri(), true);
75  
76              StringBuffer buffer = new StringBuffer();
77              buffer.append("QueryString=\"");
78              buffer.append(uri.getQuery());
79              buffer.append("\"\r\n");
80              response.setBodyString(buffer.toString());
81              return true;
82          }
83      }
84  	
85      /***
86       * Test that {@link GetMethod#setQueryString(java.lang.String)}
87       * can include a leading question mark.
88       */
89      public void testGetMethodQueryString() throws Exception {
90  		this.server.setHttpService(new QueryInfoService());
91          GetMethod method = new GetMethod("/");
92          method.setQueryString("?hadQuestionMark=true");
93  		try {
94  			this.client.executeMethod(method);
95  	        assertEquals(200, method.getStatusCode());
96  			String response = method.getResponseBodyAsString(); 
97  	        assertTrue(response.indexOf("QueryString=\"hadQuestionMark=true\"") >= 0);
98          } finally {
99  			method.releaseConnection();
100         }
101     }
102 
103     /***
104      * Test that {@link GetMethod#setQueryString(java.lang.String)}
105      * doesn't have to include a leading question mark.
106      */
107     public void testGetMethodQueryString2() throws Exception {
108 		this.server.setHttpService(new QueryInfoService());
109         GetMethod method = new GetMethod("/");
110         method.setQueryString("hadQuestionMark=false");
111 		try {
112 			this.client.executeMethod(method);
113 	        assertEquals(200, method.getStatusCode());
114 			String response = method.getResponseBodyAsString(); 
115 	        assertTrue(response.indexOf("QueryString=\"hadQuestionMark=false\"") >= 0);
116         } finally {
117 			method.releaseConnection();
118         }
119     }
120 
121     /***
122      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
123      * values get added to the query string.
124      */
125     public void testGetMethodParameters() throws Exception {
126 		this.server.setHttpService(new QueryInfoService());
127         GetMethod method = new GetMethod("/");
128         method.setQueryString(new NameValuePair[] { new NameValuePair("param-one","param-value") });
129 		try {
130 			this.client.executeMethod(method);
131 	        assertEquals(200, method.getStatusCode());
132 			String response = method.getResponseBodyAsString(); 
133 	        assertTrue(response.indexOf("QueryString=\"param-one=param-value\"") >= 0);
134         } finally {
135 			method.releaseConnection();
136         }
137     }
138 
139     /***
140      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
141      * works with multiple parameters.
142      */
143     public void testGetMethodMultiParameters() throws Exception {
144 		this.server.setHttpService(new QueryInfoService());
145         GetMethod method = new GetMethod("/");
146         method.setQueryString(new NameValuePair[] {
147                                 new NameValuePair("param-one","param-value"),
148                                 new NameValuePair("param-two","param-value2"),
149                                 new NameValuePair("special-chars",":/?~.")
150                               });
151 		try {
152 			this.client.executeMethod(method);
153 	        assertEquals(200, method.getStatusCode());
154 			String response = method.getResponseBodyAsString();
155 	        assertTrue(response.indexOf("QueryString=\"param-one=param-value&param-two=param-value2&special-chars=:/?~.\"") >= 0);
156         } finally {
157 			method.releaseConnection();
158         }
159     }
160 
161     /***
162      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
163      * works with a parameter name but no value.
164      */
165     public void testGetMethodParameterWithoutValue() throws Exception {
166 		this.server.setHttpService(new QueryInfoService());
167         GetMethod method = new GetMethod("/");
168         method.setQueryString(new NameValuePair[] { new NameValuePair("param-without-value", null) });
169 		try {
170 			this.client.executeMethod(method);
171 	        assertEquals(200, method.getStatusCode());
172 			String response = method.getResponseBodyAsString();
173 	        assertTrue(response.indexOf("QueryString=\"param-without-value=\"") >= 0);
174         } finally {
175 			method.releaseConnection();
176         }
177     }
178 
179     /***
180      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
181      * works with a parameter name that occurs more than once.
182      */
183     public void testGetMethodParameterAppearsTwice() throws Exception {
184 		this.server.setHttpService(new QueryInfoService());
185         GetMethod method = new GetMethod("/");
186         method.setQueryString(new NameValuePair[] {
187                                   new NameValuePair("foo","one"),
188                                   new NameValuePair("foo","two")
189                              });
190 		try {
191 			this.client.executeMethod(method);
192 	        assertEquals(200, method.getStatusCode());
193 			String response = method.getResponseBodyAsString();
194 	        assertTrue(response.indexOf("QueryString=\"foo=one&foo=two\"") >= 0);
195         } finally {
196 			method.releaseConnection();
197         }
198     }
199 
200     public void testGetMethodOverwriteQueryString() throws Exception {
201 		this.server.setHttpService(new QueryInfoService());
202         GetMethod method = new GetMethod("/");
203         method.setQueryString("query=string");
204         method.setQueryString(new NameValuePair[] {
205                                   new NameValuePair("param","eter"),
206                                   new NameValuePair("para","meter")
207                              });
208 		try {
209 			this.client.executeMethod(method);
210 	        assertEquals(200, method.getStatusCode());
211 			String response = method.getResponseBodyAsString();
212 	        assertFalse(response.indexOf("QueryString=\"query=string\"") >= 0);
213 	        assertTrue(response.indexOf("QueryString=\"param=eter&para=meter\"") >= 0);
214         } finally {
215 			method.releaseConnection();
216         }
217     }
218 
219     /***
220      * Test that {@link PostMethod#addParameter(java.lang.String,java.lang.String)}
221      * and {@link PostMethod#setQueryString(java.lang.String)} combine
222      * properly.
223      */
224     public void testPostMethodParameterAndQueryString() throws Exception {
225 		this.server.setHttpService(new QueryInfoService());
226         PostMethod method = new PostMethod("/");
227         method.setQueryString("query=string");
228         method.setRequestBody(new NameValuePair[] { 
229            new NameValuePair("param","eter"),
230            new NameValuePair("para","meter") } );
231 		try {
232 			this.client.executeMethod(method);
233 	        assertEquals(200, method.getStatusCode());
234 			String response = method.getResponseBodyAsString();
235 	        assertTrue(response.indexOf("QueryString=\"query=string\"") >= 0);
236 	        assertFalse(response.indexOf("QueryString=\"param=eter&para=meter\"") >= 0);
237         } finally {
238 			method.releaseConnection();
239         }
240     }
241 }
242