• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * $HeadURL: http://svn.apache.org/repos/asf/jakarta/httpcomponents/httpcore/tags/4.0-alpha6/module-main/src/test/java/org/apache/http/protocol/TestHttpServiceAndExecutor.java $
3  * $Revision: 576073 $
4  * $Date: 2007-09-16 03:53:13 -0700 (Sun, 16 Sep 2007) $
5  * ====================================================================
6  * Licensed to the Apache Software Foundation (ASF) under one
7  * or more contributor license agreements.  See the NOTICE file
8  * distributed with this work for additional information
9  * regarding copyright ownership.  The ASF licenses this file
10  * to you under the Apache License, Version 2.0 (the
11  * "License"); you may not use this file except in compliance
12  * with the License.  You may obtain a copy of the License at
13  *
14  *   http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing,
17  * software distributed under the License is distributed on an
18  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19  * KIND, either express or implied.  See the License for the
20  * specific language governing permissions and limitations
21  * under the License.
22  * ====================================================================
23  *
24  * This software consists of voluntary contributions made by many
25  * individuals on behalf of the Apache Software Foundation.  For more
26  * information on the Apache Software Foundation, please see
27  * <http://www.apache.org/>.
28  *
29  */
30 
31 package com.android.unit_tests;
32 
33 import org.apache.http.protocol.HttpExpectationVerifier;
34 import org.apache.http.protocol.HttpRequestHandler;
35 import android.test.PerformanceTestCase;
36 import android.test.suitebuilder.annotation.LargeTest;
37 import android.test.suitebuilder.annotation.MediumTest;
38 
39 import junit.framework.TestCase;
40 
41 import org.apache.http.Header;
42 import org.apache.http.HttpConnectionMetrics;
43 import org.apache.http.HttpEntity;
44 import org.apache.http.HttpEntityEnclosingRequest;
45 import org.apache.http.HttpException;
46 import org.apache.http.HttpHost;
47 import org.apache.http.HttpRequest;
48 import org.apache.http.HttpResponse;
49 import org.apache.http.HttpStatus;
50 import org.apache.http.HttpVersion;
51 import org.apache.http.entity.ByteArrayEntity;
52 import org.apache.http.entity.StringEntity;
53 import org.apache.http.impl.DefaultHttpClientConnection;
54 import org.apache.http.message.BasicHttpEntityEnclosingRequest;
55 import org.apache.http.message.BasicHttpRequest;
56 import org.apache.http.params.CoreProtocolPNames;
57 import org.apache.http.protocol.HttpContext;
58 import org.apache.http.util.EncodingUtils;
59 import org.apache.http.util.EntityUtils;
60 
61 
62 import java.io.IOException;
63 import java.net.Socket;
64 import java.net.URI;
65 import java.util.ArrayList;
66 import java.util.List;
67 import java.util.Random;
68 
69 public class TestHttpService extends TestCase implements PerformanceTestCase {
70 
isPerformanceOnly()71     public boolean isPerformanceOnly() {
72         // TODO Auto-generated method stub
73         return false;
74     }
75 
startPerformance(Intermediates intermediates)76     public int startPerformance(Intermediates intermediates) {
77         // TODO Auto-generated method stub
78         return 0;
79     }
80 
81     private TestHttpServer server;
82     private TestHttpClient client;
83 
setUp()84     protected void setUp() throws Exception {
85         this.server = new TestHttpServer();
86         this.client = new TestHttpClient();
87     }
88 
tearDown()89     protected void tearDown() throws Exception {
90         if (server != null) {
91           this.server.shutdown();
92         }
93     }
94 
95     /**
96      * This test case executes a series of simple GET requests
97      */
98     @LargeTest
testSimpleBasicHttpRequests()99     public void testSimpleBasicHttpRequests() throws Exception {
100 
101         int reqNo = 20;
102 
103         Random rnd = new Random();
104 
105         // Prepare some random data
106         final List testData = new ArrayList(reqNo);
107         for (int i = 0; i < reqNo; i++) {
108             int size = rnd.nextInt(5000);
109             byte[] data = new byte[size];
110             rnd.nextBytes(data);
111             testData.add(data);
112         }
113 
114         // Initialize the server-side request handler
115         this.server.registerHandler("*", new HttpRequestHandler() {
116 
117             public void handle(
118                     final HttpRequest request,
119                     final HttpResponse response,
120                     final HttpContext context) throws HttpException, IOException {
121 
122                 String s = request.getRequestLine().getUri();
123                 if (s.startsWith("/?")) {
124                     s = s.substring(2);
125                 }
126                 int index = Integer.parseInt(s);
127                 byte[] data = (byte []) testData.get(index);
128                 ByteArrayEntity entity = new ByteArrayEntity(data);
129                 response.setEntity(entity);
130             }
131 
132         });
133 
134         this.server.start();
135 
136         DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
137         HttpHost host = new HttpHost("localhost", this.server.getPort());
138 
139         try {
140             for (int r = 0; r < reqNo; r++) {
141                 if (!conn.isOpen()) {
142                     Socket socket = new Socket(host.getHostName(), host.getPort());
143                     conn.bind(socket, this.client.getParams());
144                 }
145 
146                 BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r);
147                 HttpResponse response = this.client.execute(get, host, conn);
148                 byte[] received = EntityUtils.toByteArray(response.getEntity());
149                 byte[] expected = (byte[]) testData.get(r);
150 
151                 assertEquals(expected.length, received.length);
152                 for (int i = 0; i < expected.length; i++) {
153                     assertEquals(expected[i], received[i]);
154                 }
155                 if (!this.client.keepAlive(response)) {
156                     conn.close();
157                 }
158             }
159 
160             //Verify the connection metrics
161             HttpConnectionMetrics cm = conn.getMetrics();
162             assertEquals(reqNo, cm.getRequestCount());
163             assertEquals(reqNo, cm.getResponseCount());
164 
165         } finally {
166             conn.close();
167             this.server.shutdown();
168         }
169     }
170 
171     /**
172      * This test case executes a series of simple POST requests with content length
173      * delimited content.
174      */
175     @LargeTest
testSimpleHttpPostsWithContentLength()176     public void testSimpleHttpPostsWithContentLength() throws Exception {
177 
178         int reqNo = 20;
179 
180         Random rnd = new Random();
181 
182         // Prepare some random data
183         List testData = new ArrayList(reqNo);
184         for (int i = 0; i < reqNo; i++) {
185             int size = rnd.nextInt(5000);
186             byte[] data = new byte[size];
187             rnd.nextBytes(data);
188             testData.add(data);
189         }
190 
191         // Initialize the server-side request handler
192         this.server.registerHandler("*", new HttpRequestHandler() {
193 
194             public void handle(
195                     final HttpRequest request,
196                     final HttpResponse response,
197                     final HttpContext context) throws HttpException, IOException {
198 
199                 if (request instanceof HttpEntityEnclosingRequest) {
200                     HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
201                     byte[] data = EntityUtils.toByteArray(incoming);
202 
203                     ByteArrayEntity outgoing = new ByteArrayEntity(data);
204                     outgoing.setChunked(false);
205                     response.setEntity(outgoing);
206                 } else {
207                     StringEntity outgoing = new StringEntity("No content");
208                     response.setEntity(outgoing);
209                 }
210             }
211 
212         });
213 
214         this.server.start();
215 
216         DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
217         HttpHost host = new HttpHost("localhost", this.server.getPort());
218 
219         try {
220             for (int r = 0; r < reqNo; r++) {
221                 if (!conn.isOpen()) {
222                     Socket socket = new Socket(host.getHostName(), host.getPort());
223                     conn.bind(socket, this.client.getParams());
224                 }
225 
226                 BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
227                 byte[] data = (byte[]) testData.get(r);
228                 ByteArrayEntity outgoing = new ByteArrayEntity(data);
229                 post.setEntity(outgoing);
230 
231                 HttpResponse response = this.client.execute(post, host, conn);
232                 byte[] received = EntityUtils.toByteArray(response.getEntity());
233                 byte[] expected = (byte[]) testData.get(r);
234 
235                 assertEquals(expected.length, received.length);
236                 for (int i = 0; i < expected.length; i++) {
237                     assertEquals(expected[i], received[i]);
238                 }
239                 if (!this.client.keepAlive(response)) {
240                     conn.close();
241                 }
242             }
243             //Verify the connection metrics
244             HttpConnectionMetrics cm = conn.getMetrics();
245             assertEquals(reqNo, cm.getRequestCount());
246             assertEquals(reqNo, cm.getResponseCount());
247 
248         } finally {
249             conn.close();
250             this.server.shutdown();
251         }
252     }
253 
254     /**
255      * This test case executes a series of simple POST requests with chunk
256      * coded content content.
257      */
258     @LargeTest
testSimpleHttpPostsChunked()259     public void testSimpleHttpPostsChunked() throws Exception {
260 
261         int reqNo = 20;
262 
263         Random rnd = new Random();
264 
265         // Prepare some random data
266         List testData = new ArrayList(reqNo);
267         for (int i = 0; i < reqNo; i++) {
268             int size = rnd.nextInt(20000);
269             byte[] data = new byte[size];
270             rnd.nextBytes(data);
271             testData.add(data);
272         }
273 
274         // Initialize the server-side request handler
275         this.server.registerHandler("*", new HttpRequestHandler() {
276 
277             public void handle(
278                     final HttpRequest request,
279                     final HttpResponse response,
280                     final HttpContext context) throws HttpException, IOException {
281 
282                 if (request instanceof HttpEntityEnclosingRequest) {
283                     HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
284                     byte[] data = EntityUtils.toByteArray(incoming);
285 
286                     ByteArrayEntity outgoing = new ByteArrayEntity(data);
287                     outgoing.setChunked(true);
288                     response.setEntity(outgoing);
289                 } else {
290                     StringEntity outgoing = new StringEntity("No content");
291                     response.setEntity(outgoing);
292                 }
293             }
294 
295         });
296 
297         this.server.start();
298 
299         DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
300         HttpHost host = new HttpHost("localhost", this.server.getPort());
301 
302         try {
303             for (int r = 0; r < reqNo; r++) {
304                 if (!conn.isOpen()) {
305                     Socket socket = new Socket(host.getHostName(), host.getPort());
306                     conn.bind(socket, this.client.getParams());
307                 }
308 
309                 BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
310                 byte[] data = (byte[]) testData.get(r);
311                 ByteArrayEntity outgoing = new ByteArrayEntity(data);
312                 outgoing.setChunked(true);
313                 post.setEntity(outgoing);
314 
315                 HttpResponse response = this.client.execute(post, host, conn);
316                 byte[] received = EntityUtils.toByteArray(response.getEntity());
317                 byte[] expected = (byte[]) testData.get(r);
318 
319                 assertEquals(expected.length, received.length);
320                 for (int i = 0; i < expected.length; i++) {
321                     assertEquals(expected[i], received[i]);
322                 }
323                 if (!this.client.keepAlive(response)) {
324                     conn.close();
325                 }
326             }
327             //Verify the connection metrics
328             HttpConnectionMetrics cm = conn.getMetrics();
329             assertEquals(reqNo, cm.getRequestCount());
330             assertEquals(reqNo, cm.getResponseCount());
331         } finally {
332             conn.close();
333             this.server.shutdown();
334         }
335     }
336 
337     /**
338      * This test case executes a series of simple HTTP/1.0 POST requests.
339      */
340     @LargeTest
testSimpleHttpPostsHTTP10()341     public void testSimpleHttpPostsHTTP10() throws Exception {
342 
343         int reqNo = 20;
344 
345         Random rnd = new Random();
346 
347         // Prepare some random data
348         List testData = new ArrayList(reqNo);
349         for (int i = 0; i < reqNo; i++) {
350             int size = rnd.nextInt(5000);
351             byte[] data = new byte[size];
352             rnd.nextBytes(data);
353             testData.add(data);
354         }
355 
356         // Initialize the server-side request handler
357         this.server.registerHandler("*", new HttpRequestHandler() {
358 
359             public void handle(
360                     final HttpRequest request,
361                     final HttpResponse response,
362                     final HttpContext context) throws HttpException, IOException {
363 
364                 if (request instanceof HttpEntityEnclosingRequest) {
365                     HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
366                     byte[] data = EntityUtils.toByteArray(incoming);
367 
368                     ByteArrayEntity outgoing = new ByteArrayEntity(data);
369                     outgoing.setChunked(false);
370                     response.setEntity(outgoing);
371                 } else {
372                     StringEntity outgoing = new StringEntity("No content");
373                     response.setEntity(outgoing);
374                 }
375             }
376 
377         });
378 
379         this.server.start();
380 
381         // Set protocol level to HTTP/1.0
382         this.client.getParams().setParameter(
383                 CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
384 
385         DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
386         HttpHost host = new HttpHost("localhost", this.server.getPort());
387 
388         try {
389             for (int r = 0; r < reqNo; r++) {
390                 if (!conn.isOpen()) {
391                     Socket socket = new Socket(host.getHostName(), host.getPort());
392                     conn.bind(socket, this.client.getParams());
393                 }
394 
395                 BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
396                 byte[] data = (byte[]) testData.get(r);
397                 ByteArrayEntity outgoing = new ByteArrayEntity(data);
398                 post.setEntity(outgoing);
399 
400                 HttpResponse response = this.client.execute(post, host, conn);
401                 assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion());
402                 byte[] received = EntityUtils.toByteArray(response.getEntity());
403                 byte[] expected = (byte[]) testData.get(r);
404 
405                 assertEquals(expected.length, received.length);
406                 for (int i = 0; i < expected.length; i++) {
407                     assertEquals(expected[i], received[i]);
408                 }
409                 if (!this.client.keepAlive(response)) {
410                     conn.close();
411                 }
412             }
413 
414             //Verify the connection metrics
415             HttpConnectionMetrics cm = conn.getMetrics();
416             assertEquals(reqNo, cm.getRequestCount());
417             assertEquals(reqNo, cm.getResponseCount());
418         } finally {
419             conn.close();
420             this.server.shutdown();
421         }
422     }
423 
424     /**
425      * This test case executes a series of simple POST requests using
426      * the 'expect: continue' handshake.
427      */
428     @LargeTest
testHttpPostsWithExpectContinue()429     public void testHttpPostsWithExpectContinue() throws Exception {
430 
431         int reqNo = 20;
432 
433         Random rnd = new Random();
434 
435         // Prepare some random data
436         List testData = new ArrayList(reqNo);
437         for (int i = 0; i < reqNo; i++) {
438             int size = rnd.nextInt(5000);
439             byte[] data = new byte[size];
440             rnd.nextBytes(data);
441             testData.add(data);
442         }
443 
444         // Initialize the server-side request handler
445         this.server.registerHandler("*", new HttpRequestHandler() {
446 
447             public void handle(
448                     final HttpRequest request,
449                     final HttpResponse response,
450                     final HttpContext context) throws HttpException, IOException {
451 
452                 if (request instanceof HttpEntityEnclosingRequest) {
453                     HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
454                     byte[] data = EntityUtils.toByteArray(incoming);
455 
456                     ByteArrayEntity outgoing = new ByteArrayEntity(data);
457                     outgoing.setChunked(true);
458                     response.setEntity(outgoing);
459                 } else {
460                     StringEntity outgoing = new StringEntity("No content");
461                     response.setEntity(outgoing);
462                 }
463             }
464 
465         });
466 
467         this.server.start();
468 
469         // Activate 'expect: continue' handshake
470         this.client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
471 
472         DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
473         HttpHost host = new HttpHost("localhost", this.server.getPort());
474 
475         try {
476             for (int r = 0; r < reqNo; r++) {
477                 if (!conn.isOpen()) {
478                     Socket socket = new Socket(host.getHostName(), host.getPort());
479                     conn.bind(socket, this.client.getParams());
480                 }
481 
482                 BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
483                 byte[] data = (byte[]) testData.get(r);
484                 ByteArrayEntity outgoing = new ByteArrayEntity(data);
485                 outgoing.setChunked(true);
486                 post.setEntity(outgoing);
487 
488                 HttpResponse response = this.client.execute(post, host, conn);
489                 byte[] received = EntityUtils.toByteArray(response.getEntity());
490                 byte[] expected = (byte[]) testData.get(r);
491 
492                 assertEquals(expected.length, received.length);
493                 for (int i = 0; i < expected.length; i++) {
494                     assertEquals(expected[i], received[i]);
495                 }
496                 if (!this.client.keepAlive(response)) {
497                     conn.close();
498                 }
499             }
500 
501             //Verify the connection metrics
502             HttpConnectionMetrics cm = conn.getMetrics();
503             assertEquals(reqNo, cm.getRequestCount());
504             assertEquals(reqNo, cm.getResponseCount());
505         } finally {
506             conn.close();
507             this.server.shutdown();
508         }
509     }
510 
511 
512     /**
513      * This test case executes a series of simple POST requests that do not
514      * meet the target server expectations.
515      */
516     @LargeTest
testHttpPostsWithExpectationVerification()517     public void testHttpPostsWithExpectationVerification() throws Exception {
518 
519         int reqNo = 3;
520 
521         // Initialize the server-side request handler
522         this.server.registerHandler("*", new HttpRequestHandler() {
523 
524             public void handle(
525                     final HttpRequest request,
526                     final HttpResponse response,
527                     final HttpContext context) throws HttpException, IOException {
528 
529                 StringEntity outgoing = new StringEntity("No content");
530                 response.setEntity(outgoing);
531             }
532 
533         });
534 
535         this.server.setExpectationVerifier(new HttpExpectationVerifier() {
536 
537             public void verify(
538                     final HttpRequest request,
539                     final HttpResponse response,
540                     final HttpContext context) throws HttpException {
541                 Header someheader = request.getFirstHeader("Secret");
542                 if (someheader != null) {
543                     int secretNumber;
544                     try {
545                         secretNumber = Integer.parseInt(someheader.getValue());
546                     } catch (NumberFormatException ex) {
547                         response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
548                         return;
549                     }
550                     if (secretNumber < 2) {
551                         response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
552                         ByteArrayEntity outgoing = new ByteArrayEntity(
553                                 EncodingUtils.getAsciiBytes("Wrong secret number"));
554                         response.setEntity(outgoing);
555                     }
556                 }
557             }
558 
559         });
560 
561         this.server.start();
562 
563         // Activate 'expect: continue' handshake
564         this.client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
565 
566         DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
567         HttpHost host = new HttpHost("localhost", this.server.getPort());
568 
569         try {
570             for (int r = 0; r < reqNo; r++) {
571                 if (!conn.isOpen()) {
572                     Socket socket = new Socket(host.getHostName(), host.getPort());
573                     conn.bind(socket, this.client.getParams());
574                 }
575 
576                 BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
577                 post.addHeader("Secret", Integer.toString(r));
578                 ByteArrayEntity outgoing = new ByteArrayEntity(
579                         EncodingUtils.getAsciiBytes("No content"));
580                 post.setEntity(outgoing);
581 
582                 HttpResponse response = this.client.execute(post, host, conn);
583 
584                 HttpEntity entity = response.getEntity();
585                 assertNotNull(entity);
586                 entity.consumeContent();
587 
588                 if (r < 2) {
589                     assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response.getStatusLine().getStatusCode());
590                 } else {
591                     assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
592                 }
593 
594                 if (!this.client.keepAlive(response)) {
595                     conn.close();
596                 }
597             }
598             //Verify the connection metrics
599             HttpConnectionMetrics cm = conn.getMetrics();
600             assertEquals(reqNo, cm.getRequestCount());
601             assertEquals(reqNo, cm.getResponseCount());
602         } finally {
603             conn.close();
604             this.server.shutdown();
605         }
606     }
607 
608 }
609