KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tester > TestClient


1 /*
2  * Copyright 1999, 2000 ,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.tester;
18
19
20 import java.io.FileNotFoundException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.OutputStream JavaDoc;
24 import java.io.PrintWriter JavaDoc;
25 import java.net.ConnectException JavaDoc;
26 import java.net.HttpURLConnection JavaDoc;
27 import java.net.Socket JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import org.apache.tools.ant.BuildException;
33 import org.apache.tools.ant.Task;
34
35
36 /**
37  * <p>This class contains a <strong>Task</strong> for Ant that is used to
38  * send HTTP requests to a servlet container, and examine the responses.
39  * It is similar in purpose to the <code>GTest</code> task in Watchdog,
40  * but uses the JDK's HttpURLConnection for underlying connectivity.</p>
41  *
42  * <p>The task is registered with Ant using a <code>taskdef</code> directive:
43  * <pre>
44  * &lt;taskdef name="tester" classname="org.apache.tester.TestClient"&gt;
45  * </pre>
46  * and accepts the following configuration properties:</p>
47  * <ul>
48  * <li><strong>golden</strong> - The server-relative path of the static
49  * resource containing the golden file for this request.</li>
50  * <li><strong>host</strong> - The server name to which this request will be
51  * sent. Defaults to <code>localhost</code> if not specified.</li>
52  * <li><strong>inContent</strong> - The data content that will be submitted
53  * with this request. The test client will transparently add a carriage
54  * return and line feed, and set the content length header, if this is
55  * specified. Otherwise, no content will be included in the request.</li>
56  * <li><strong>inHeaders</strong> - The set of one or more HTTP headers that
57  * will be included on the request.</li>
58  * <li><strong>message</strong> - The HTTP response message that is expected
59  * in the response from the server. No check is made if no message
60  * is specified.</li>
61  * <li><strong>method</strong> - The HTTP request method to be used on this
62  * request. Defaults to <ocde>GET</code> if not specified.</li>
63  * <li><strong>outContent</strong> - The first line of the response data
64  * content that we expect to receive. No check is made if no content is
65  * specified.</li>
66  * <li><strong>outHeaders</strong> - The set of one or more HTTP headers that
67  * are expected in the response (order independent).</li>
68  * <li><strong>port</strong> - The port number to which this request will be
69  * sent. Defaults to <code>8080</code> if not specified.</li>
70  * <li><strong>redirect</strong> - If set to true, follow any redirect that
71  * is returned by the server. (Only works when using HttpURLConnection).
72  * </li>
73  * <li><strong>request</strong> - The request URI to be transmitted for this
74  * request. This value should start with a slash character ("/"), and
75  * be the server-relative URI of the requested resource.</li>
76  * <li><strong>status</strong> - The HTTP status code that is expected in the
77  * response from the server. Defaults to <code>200</code> if not
78  * specified. Set to zero to disable checking the return value.</li>
79  * </ul>
80  *
81  * @author Craig R. McClanahan
82  * @version $Revision: 1.4 $ $Date: 2004/09/25 21:27:31 $
83  */

84
85 public class TestClient extends Task {
86
87
88     // ----------------------------------------------------- Instance Variables
89

90
91     /**
92      * The saved golden file we will compare to the response. Each element
93      * contains a line of text without any line delimiters.
94      */

95     protected ArrayList JavaDoc saveGolden = new ArrayList JavaDoc();
96
97
98     /**
99      * The saved headers we received in our response. The key is the header
100      * name (converted to lower case), and the value is an ArrayList of the
101      * string value(s) received for that header.
102      */

103     protected HashMap JavaDoc saveHeaders = new HashMap JavaDoc();
104
105
106     /**
107      * The response file to be compared to the golden file. Each element
108      * contains a line of text without any line delimiters.
109      */

110     protected ArrayList JavaDoc saveResponse = new ArrayList JavaDoc();
111
112
113     // ------------------------------------------------------------- Properties
114

115
116     /**
117      * The debugging detail level for this execution.
118      */

119     protected int debug = 0;
120
121     public int getDebug() {
122         return (this.debug);
123     }
124
125     public void setDebug(int debug) {
126         this.debug = debug;
127     }
128
129
130     /**
131      * The server-relative request URI of the golden file for this request.
132      */

133     protected String JavaDoc golden = null;
134
135     public String JavaDoc getGolden() {
136         return (this.golden);
137     }
138
139     public void setGolden(String JavaDoc golden) {
140         this.golden = golden;
141     }
142
143
144     /**
145      * The host name to which we will connect.
146      */

147     protected String JavaDoc host = "localhost";
148
149     public String JavaDoc getHost() {
150         return (this.host);
151     }
152
153     public void setHost(String JavaDoc host) {
154         this.host = host;
155     }
156
157
158     /**
159      * The first line of the request data that will be included on this
160      * request.
161      */

162     protected String JavaDoc inContent = null;
163
164     public String JavaDoc getInContent() {
165         return (this.inContent);
166     }
167
168     public void setInContent(String JavaDoc inContent) {
169         this.inContent = inContent;
170     }
171
172
173     /**
174      * The HTTP headers to be included on the request. Syntax is
175      * <code>{name}:{value}[##{name}:{value}] ...</code>.
176      */

177     protected String JavaDoc inHeaders = null;
178
179     public String JavaDoc getInHeaders() {
180         return (this.inHeaders);
181     }
182
183     public void setInHeaders(String JavaDoc inHeaders) {
184         this.inHeaders = inHeaders;
185     }
186
187
188     /**
189      * Should we join the session whose session identifier was returned
190      * on the previous request.
191      */

192     protected boolean joinSession = false;
193
194     public boolean getJoinSession() {
195         return (this.joinSession);
196     }
197
198     public void setJoinSession(boolean joinSession) {
199         this.joinSession = true;
200     }
201
202
203     /**
204      * The HTTP response message to be expected in the response.
205      */

206     protected String JavaDoc message = null;
207
208     public String JavaDoc getMessage() {
209         return (this.message);
210     }
211
212     public void setMessage(String JavaDoc message) {
213         this.message = message;
214     }
215
216
217     /**
218      * The HTTP request method that will be used.
219      */

220     protected String JavaDoc method = "GET";
221
222     public String JavaDoc getMethod() {
223         return (this.method);
224     }
225
226     public void setMethod(String JavaDoc method) {
227         this.method = method;
228     }
229
230
231     /**
232      * The first line of the response data content that we expect to receive.
233      */

234     protected String JavaDoc outContent = null;
235
236     public String JavaDoc getOutContent() {
237         return (this.outContent);
238     }
239
240     public void setOutContent(String JavaDoc outContent) {
241         this.outContent = outContent;
242     }
243
244
245     /**
246      * The HTTP headers to be checked on the response. Syntax is
247      * <code>{name}:{value}[##{name}:{value}] ...</code>.
248      */

249     protected String JavaDoc outHeaders = null;
250
251     public String JavaDoc getOutHeaders() {
252         return (this.outHeaders);
253     }
254
255     public void setOutHeaders(String JavaDoc outHeaders) {
256         this.outHeaders = outHeaders;
257     }
258
259
260     /**
261      * The port number to which we will connect.
262      */

263     protected int port = 8080;
264
265     public int getPort() {
266         return (this.port);
267     }
268
269     public void setPort(int port) {
270         this.port = port;
271     }
272
273
274     /**
275      * The protocol and version to include in the request, if executed as
276      * a direct socket connection. Lack of a value here indicates that an
277      * HttpURLConnection should be used instead.
278      */

279     protected String JavaDoc protocol = null;
280
281     public String JavaDoc getProtocol() {
282         return (this.protocol);
283     }
284
285     public void setProtocol(String JavaDoc protocol) {
286         this.protocol = protocol;
287     }
288
289
290     /**
291      * Should we follow redirects returned by the server?
292      */

293     protected boolean redirect = false;
294
295     public boolean getRedirect() {
296         return (this.redirect);
297     }
298
299     public void setRedirect(boolean redirect) {
300         this.redirect = redirect;
301     }
302
303
304     /**
305      * The request URI to be sent to the server. This value is required.
306      */

307     protected String JavaDoc request = null;
308
309     public String JavaDoc getRequest() {
310         return (this.request);
311     }
312
313     public void setRequest(String JavaDoc request) {
314         this.request = request;
315     }
316
317
318     /**
319      * The HTTP status code expected on the response.
320      */

321     protected int status = 200;
322
323     public int getStatus() {
324         return (this.status);
325     }
326
327     public void setStatus(int status) {
328         this.status = status;
329     }
330
331
332     // ------------------------------------------------------- Static Variables
333

334
335     /**
336      * The session identifier returned by the most recent request, or
337      * <code>null</code> if the previous request did not specify a session
338      * identifier.
339      */

340     protected static String JavaDoc sessionId = null;
341
342
343     // --------------------------------------------------------- Public Methods
344

345
346     /**
347      * Execute the test that has been configured by our property settings.
348      *
349      * @exception BuildException if an exception occurs
350      */

351     public void execute() throws BuildException {
352
353         saveHeaders.clear();
354         try {
355             readGolden();
356         } catch (IOException JavaDoc e) {
357             log("FAIL: readGolden(" + golden + ")");
358             e.printStackTrace(System.out);
359         }
360         if ((protocol == null) || (protocol.length() == 0))
361             executeHttp();
362         else
363             executeSocket();
364
365     }
366
367
368     // ------------------------------------------------------ Protected Methods
369

370
371     /**
372      * Execute the test via use of an HttpURLConnection.
373      *
374      * @exception BuildException if an exception occurs
375      */

376     protected void executeHttp() throws BuildException {
377
378         // Construct a summary of the request we will be sending
379
String JavaDoc summary = "[" + method + " " + request + "]";
380         if (debug >= 1)
381             log("RQST: " + summary);
382         boolean success = true;
383         String JavaDoc result = null;
384         Throwable JavaDoc throwable = null;
385         HttpURLConnection JavaDoc conn = null;
386
387         try {
388
389             // Configure an HttpURLConnection for this request
390
URL JavaDoc url = new URL JavaDoc("http", host, port, request);
391             conn = (HttpURLConnection JavaDoc) url.openConnection();
392             conn.setAllowUserInteraction(false);
393             conn.setDoInput(true);
394             if (inContent != null) {
395                 conn.setDoOutput(true);
396                 conn.setRequestProperty("Content-Length",
397                                         "" + inContent.length());
398                 if (debug >= 1)
399                     log("INPH: Content-Length: " +
400                                        inContent.length());
401             } else {
402                 conn.setDoOutput(false);
403             }
404
405             // Send the session id cookie (if any)
406
if (joinSession && (sessionId != null)) {
407                 conn.setRequestProperty("Cookie",
408                                         "JSESSIONID=" + sessionId);
409                 if (debug >= 1)
410                     log("INPH: Cookie: JSESSIONID=" +
411                                        sessionId);
412             }
413
414             if (this.redirect && (debug >= 1))
415                 log("FLAG: setInstanceFollowRedirects(" +
416                                    this.redirect + ")");
417             conn.setInstanceFollowRedirects(this.redirect);
418             conn.setRequestMethod(method);
419             if (inHeaders != null) {
420                 String JavaDoc headers = inHeaders;
421                 while (headers.length() > 0) {
422                     int delimiter = headers.indexOf("##");
423                     String JavaDoc header = null;
424                     if (delimiter < 0) {
425                         header = headers;
426                         headers = "";
427                     } else {
428                         header = headers.substring(0, delimiter);
429                         headers = headers.substring(delimiter + 2);
430                     }
431                     int colon = header.indexOf(":");
432                     if (colon < 0)
433                         break;
434                     String JavaDoc name = header.substring(0, colon).trim();
435                     String JavaDoc value = header.substring(colon + 1).trim();
436                     conn.setRequestProperty(name, value);
437                     if (debug >= 1)
438                         log("INPH: " + name + ": " + value);
439                 }
440             }
441
442             // Connect to the server and send our output if necessary
443
conn.connect();
444             if (inContent != null) {
445                 if (debug >= 1)
446                     log("INPD: " + inContent);
447                 OutputStream JavaDoc os = conn.getOutputStream();
448                 for (int i = 0; i < inContent.length(); i++)
449                     os.write(inContent.charAt(i));
450                 os.close();
451             }
452
453             // Acquire the response data, if there is any
454
String JavaDoc outData = "";
455             String JavaDoc outText = "";
456             boolean eol = false;
457             InputStream JavaDoc is = conn.getInputStream();
458             int lines = 0;
459             while (true) {
460                 String JavaDoc line = read(is);
461                 if (line == null)
462                     break;
463                 if (lines == 0)
464                     outData = line;
465                 else
466                     outText += line + "\r\n";
467                 saveResponse.add(line);
468                 lines++;
469             }
470             is.close();
471
472             // Dump out the response stuff
473
if (debug >= 1)
474                 log("RESP: " + conn.getResponseCode() + " " +
475                                    conn.getResponseMessage());
476             for (int i = 1; i < 1000; i++) {
477                 String JavaDoc name = conn.getHeaderFieldKey(i);
478                 String JavaDoc value = conn.getHeaderField(i);
479                 if ((name == null) || (value == null))
480                     break;
481                 if (debug >= 1)
482                     log("HEAD: " + name + ": " + value);
483                 save(name, value);
484                 if ("Set-Cookie".equals(name))
485                     parseSession(value);
486             }
487             if (debug >= 1) {
488                 log("DATA: " + outData);
489                 if (outText.length() > 2)
490                     log("TEXT: " + outText);
491             }
492
493             // Validate the response against our criteria
494
if (success) {
495                 result = validateStatus(conn.getResponseCode());
496                 if (result != null)
497                     success = false;
498             }
499             if (success) {
500                 result = validateMessage(conn.getResponseMessage());
501                 if (result != null)
502                     success = false;
503             }
504             if (success) {
505                 result = validateHeaders();
506                 if (result != null)
507                     success = false;
508             }
509             if (success) {
510                 result = validateData(outData);
511                 if (result != null)
512                     success = false;
513             }
514             if (success) {
515                 result = validateGolden();
516                 if (result != null)
517                     success = false;
518             }
519
520         } catch (Throwable JavaDoc t) {
521             if (t instanceof FileNotFoundException JavaDoc) {
522                 if (status == 404) {
523                     success = true;
524                     result = "Not Found";
525                     throwable = null;
526                 } else {
527                     success = false;
528                     try {
529                         result = "Status=" + conn.getResponseCode() +
530                             ", Message=" + conn.getResponseMessage();
531                     } catch (IOException JavaDoc e) {
532                         result = e.toString();
533                     }
534                     throwable = null;
535                 }
536             } else if (t instanceof ConnectException JavaDoc) {
537                 success = false;
538                 result = t.getMessage();
539                 throwable = null;
540             } else {
541                 success = false;
542                 result = t.getMessage();
543                 throwable = t;
544             }
545         }
546
547         // Log the results of executing this request
548
if (success)
549             log("OK " + summary);
550         else {
551             log("FAIL " + summary + " " + result);
552             if (throwable != null)
553                 throwable.printStackTrace(System.out);
554         }
555
556     }
557
558
559     /**
560      * Execute the test via use of a socket with direct input/output.
561      *
562      * @exception BuildException if an exception occurs
563      */

564     protected void executeSocket() throws BuildException {
565
566         // Construct a summary of the request we will be sending
567
String JavaDoc command = method + " " + request + " " + protocol;
568         String JavaDoc summary = "[" + command + "]";
569         if (debug >= 1)
570             log("RQST: " + summary);
571         boolean success = true;
572         String JavaDoc result = null;
573         Socket JavaDoc socket = null;
574         OutputStream JavaDoc os = null;
575         PrintWriter JavaDoc pw = null;
576         InputStream JavaDoc is = null;
577         Throwable JavaDoc throwable = null;
578         int outStatus = 0;
579         String JavaDoc outMessage = null;
580
581         try {
582
583             // Open a client socket for this request
584
socket = new Socket JavaDoc(host, port);
585             os = socket.getOutputStream();
586             pw = new PrintWriter JavaDoc(os);
587             is = socket.getInputStream();
588
589             // Send the command and content length header (if any)
590
pw.print(command + "\r\n");
591             if (inContent != null) {
592                 if (debug >= 1)
593                     log("INPH: " + "Content-Length: " +
594                                        inContent.length());
595                 pw.print("Content-Length: " + inContent.length() + "\r\n");
596             }
597
598             // Send the session id cookie (if any)
599
if (joinSession && (sessionId != null)) {
600                 pw.println("Cookie: JSESSIONID=" + sessionId);
601                 if (debug >= 1)
602                     log("INPH: Cookie: JSESSIONID=" +
603                                        sessionId);
604             }
605
606             // Send the specified headers (if any)
607
if (inHeaders != null) {
608                 String JavaDoc headers = inHeaders;
609                 while (headers.length() > 0) {
610                     int delimiter = headers.indexOf("##");
611                     String JavaDoc header = null;
612                     if (delimiter < 0) {
613                         header = headers;
614                         headers = "";
615                     } else {
616                         header = headers.substring(0, delimiter);
617                         headers = headers.substring(delimiter + 2);
618                     }
619                     int colon = header.indexOf(":");
620                     if (colon < 0)
621                         break;
622                     String JavaDoc name = header.substring(0, colon).trim();
623                     String JavaDoc value = header.substring(colon + 1).trim();
624                     if (debug >= 1)
625                         log("INPH: " + name + ": " + value);
626                     pw.print(name + ": " + value + "\r\n");
627                 }
628             }
629             pw.print("\r\n");
630
631             // Send our content (if any)
632
if (inContent != null) {
633                 if (debug >= 1)
634                     log("INPD: " + inContent);
635                 for (int i = 0; i < inContent.length(); i++)
636                     pw.print(inContent.charAt(i));
637             }
638             pw.flush();
639
640             // Read the response status and associated message
641
String JavaDoc line = read(is);
642             if (line == null) {
643                 outStatus = -1;
644                 outMessage = "NO RESPONSE";
645             } else {
646                 line = line.trim();
647                 if (debug >= 1)
648                     System.out.println("RESP: " + line);
649                 int space = line.indexOf(" ");
650                 if (space >= 0) {
651                     line = line.substring(space + 1).trim();
652                     space = line.indexOf(" ");
653                 }
654                 try {
655                     if (space < 0) {
656                         outStatus = Integer.parseInt(line);
657                         outMessage = "";
658                     } else {
659                         outStatus = Integer.parseInt(line.substring(0, space));
660                         outMessage = line.substring(space + 1).trim();
661                     }
662                 } catch (NumberFormatException JavaDoc e) {
663                     outStatus = -1;
664                     outMessage = "NUMBER FORMAT EXCEPTION";
665                 }
666             }
667             if (debug >= 1)
668                 System.out.println("STAT: " + outStatus + " MESG: " +
669                                    outMessage);
670
671             // Read the response headers (if any)
672
String JavaDoc headerName = null;
673             String JavaDoc headerValue = null;
674             while (true) {
675                 line = read(is);
676                 if ((line == null) || (line.length() == 0))
677                     break;
678                 int colon = line.indexOf(":");
679                 if (colon < 0) {
680                     if (debug >= 1)
681                         System.out.println("????: " + line);
682                 } else {
683                     headerName = line.substring(0, colon).trim();
684                     headerValue = line.substring(colon + 1).trim();
685                     if (debug >= 1)
686                         System.out.println("HEAD: " + headerName + ": " +
687                                            headerValue);
688                     save(headerName, headerValue);
689                     if ("Set-Cookie".equals(headerName))
690                         parseSession(headerValue);
691                 }
692             }
693
694             // Acquire the response data (if any)
695
String JavaDoc outData = "";
696             String JavaDoc outText = "";
697             int lines = 0;
698             while (true) {
699                 line = read(is);
700                 if (line == null)
701                     break;
702                 if (lines == 0)
703                     outData = line;
704                 else
705                     outText += line + "\r\n";
706                 saveResponse.add(line);
707                 lines++;
708             }
709             is.close();
710             if (debug >= 1) {
711                 System.out.println("DATA: " + outData);
712                 if (outText.length() > 2)
713                     System.out.println("TEXT: " + outText);
714             }
715
716             // Validate the response against our criteria
717
if (success) {
718                 result = validateStatus(outStatus);
719                 if (result != null)
720                     success = false;
721             }
722             if (success) {
723                 result = validateMessage(message);
724                 if (result != null)
725                     success = false;
726             }
727             if (success) {
728                 result = validateHeaders();
729                 if (result != null)
730                     success = false;
731             }
732             if (success) {
733                 result = validateData(outData);
734                 if (result != null)
735                     success = false;
736             }
737             if (success) {
738                 result = validateGolden();
739                 if (result != null)
740                     success = false;
741             }
742
743         } catch (Throwable JavaDoc t) {
744             success = false;
745             result = "Status=" + outStatus +
746                 ", Message=" + outMessage;
747             throwable = null;
748         } finally {
749             if (pw != null) {
750                 try {
751                     pw.close();
752                 } catch (Throwable JavaDoc w) {
753                     ;
754                 }
755             }
756             if (os != null) {
757                 try {
758                     os.close();
759                 } catch (Throwable JavaDoc w) {
760                     ;
761                 }
762             }
763             if (is != null) {
764                 try {
765                     is.close();
766                 } catch (Throwable JavaDoc w) {
767                     ;
768                 }
769             }
770             if (socket != null) {
771                 try {
772                     socket.close();
773                 } catch (Throwable JavaDoc w) {
774                     ;
775                 }
776             }
777         }
778
779         if (success)
780             System.out.println("OK " + summary);
781         else {
782             System.out.println("FAIL " + summary + " " + result);
783             if (throwable != null)
784                 throwable.printStackTrace(System.out);
785         }
786
787     }
788
789
790     /**
791      * Parse the session identifier from the specified Set-Cookie value.
792      *
793      * @param value The Set-Cookie value to parse
794      */

795     protected void parseSession(String JavaDoc value) {
796
797         if (value == null)
798             return;
799         int equals = value.indexOf("JSESSIONID=");
800         if (equals < 0)
801             return;
802         value = value.substring(equals + "JSESSIONID=".length());
803         int semi = value.indexOf(";");
804         if (semi >= 0)
805             value = value.substring(0, semi);
806
807         if (debug >= 1)
808             System.out.println("SESSION ID: " + value);
809         sessionId = value;
810
811     }
812
813
814     /**
815      * Read and return the next line from the specified input stream, with
816      * no carriage return or line feed delimiters. If
817      * end of file is reached, return <code>null</code> instead.
818      *
819      * @param stream The input stream to read from
820      *
821      * @exception IOException if an input/output error occurs
822      */

823     protected String JavaDoc read(InputStream JavaDoc stream) throws IOException JavaDoc {
824
825         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
826         while (true) {
827             int b = stream.read();
828             if (b < 0) {
829                 if (result.length() == 0)
830                     return (null);
831                 else
832                     break;
833             }
834             char c = (char) b;
835             if (c == '\r')
836                 continue;
837             else if (c == '\n')
838                 break;
839             else
840                 result.append(c);
841         }
842         return (result.toString());
843
844     }
845
846
847     /**
848      * Read and save the contents of the golden file for this test, if any.
849      * Otherwise, the <code>saveGolden</code> list will be empty.
850      *
851      * @exception IOException if an input/output error occurs
852      */

853     protected void readGolden() throws IOException JavaDoc {
854
855         // Was a golden file specified?
856
saveGolden.clear();
857         if (golden == null)
858             return;
859
860         // Create a connection to receive the golden file contents
861
URL JavaDoc url = new URL JavaDoc("http", host, port, golden);
862         HttpURLConnection JavaDoc conn =
863             (HttpURLConnection JavaDoc) url.openConnection();
864         conn.setAllowUserInteraction(false);
865         conn.setDoInput(true);
866         conn.setDoOutput(false);
867         conn.setFollowRedirects(true);
868         conn.setRequestMethod("GET");
869
870         // Connect to the server and retrieve the golden file
871
conn.connect();
872         InputStream JavaDoc is = conn.getInputStream();
873         while (true) {
874             String JavaDoc line = read(is);
875             if (line == null)
876                 break;
877             saveGolden.add(line);
878         }
879         is.close();
880         conn.disconnect();
881
882     }
883
884
885     /**
886      * Save the specified header name and value in our collection.
887      *
888      * @param name Header name to save
889      * @param value Header value to save
890      */

891     protected void save(String JavaDoc name, String JavaDoc value) {
892
893         String JavaDoc key = name.toLowerCase();
894         ArrayList JavaDoc list = (ArrayList JavaDoc) saveHeaders.get(key);
895         if (list == null) {
896             list = new ArrayList JavaDoc();
897             saveHeaders.put(key, list);
898         }
899         list.add(value);
900
901     }
902
903
904     /**
905      * Validate the output data against what we expected. Return
906      * <code>null</code> for no problems, or an error message.
907      *
908      * @param data The output data to be tested
909      */

910     protected String JavaDoc validateData(String JavaDoc data) {
911
912         if (outContent == null)
913             return (null);
914         else if (data.startsWith(outContent))
915             return (null);
916         else
917             return ("Expected data '" + outContent + "', got data '" +
918                     data + "'");
919
920     }
921
922
923     /**
924      * Validate the response against the golden file (if any). Return
925      * <code>null</code> for no problems, or an error message.
926      */

927     protected String JavaDoc validateGolden() {
928
929         if (golden == null)
930             return (null);
931         boolean ok = true;
932         if (saveGolden.size() != saveResponse.size())
933             ok = false;
934         if (ok) {
935             for (int i = 0; i < saveGolden.size(); i++) {
936                 String JavaDoc golden = (String JavaDoc) saveGolden.get(i);
937                 String JavaDoc response = (String JavaDoc) saveResponse.get(i);
938                 if (!golden.equals(response)) {
939                     ok = false;
940                     break;
941                 }
942             }
943         }
944         if (ok)
945             return (null);
946         System.out.println("EXPECTED: ======================================");
947         for (int i = 0; i < saveGolden.size(); i++)
948             System.out.println((String JavaDoc) saveGolden.get(i));
949         System.out.println("================================================");
950         System.out.println("RECEIVED: ======================================");
951         for (int i = 0; i < saveResponse.size(); i++)
952             System.out.println((String JavaDoc) saveResponse.get(i));
953         System.out.println("================================================");
954         return ("Failed Golden File Comparison");
955
956     }
957
958
959     /**
960      * Validate the saved headers against the <code>outHeaders</code>
961      * property, and return an error message if there is anything missing.
962      * If all of the expected headers are present, return <code>null</code>.
963      */

964     protected String JavaDoc validateHeaders() {
965
966         // Do we have any headers to check for?
967
if (outHeaders == null)
968             return (null);
969
970         // Check each specified name:value combination
971
String JavaDoc headers = outHeaders;
972         while (headers.length() > 0) {
973             // Parse the next name:value combination
974
int delimiter = headers.indexOf("##");
975             String JavaDoc header = null;
976             if (delimiter < 0) {
977                 header = headers;
978                 headers = "";
979             } else {
980                 header = headers.substring(0, delimiter);
981                 headers = headers.substring(delimiter + 2);
982             }
983             int colon = header.indexOf(":");
984             String JavaDoc name = header.substring(0, colon).trim();
985             String JavaDoc value = header.substring(colon + 1).trim();
986             // Check for the occurrence of this header
987
ArrayList JavaDoc list = (ArrayList JavaDoc) saveHeaders.get(name.toLowerCase());
988             if (list == null)
989                 return ("Missing header name '" + name + "'");
990             boolean found = false;
991             for (int i = 0; i < list.size(); i++) {
992                 if (value.equals((String JavaDoc) list.get(i))) {
993                     found = true;
994                     break;
995                 }
996             }
997             if (!found)
998                 return ("Missing header name '" + name + "' with value '" +
999                         value + "'");
1000        }
1001
1002        // Everything was found successfully
1003
return (null);
1004
1005    }
1006
1007
1008    /**
1009     * Validate the returned response message against what we expected.
1010     * Return <code>null</code> for no problems, or an error message.
1011     *
1012     * @param message The returned response message
1013     */

1014    protected String JavaDoc validateMessage(String JavaDoc message) {
1015
1016        if (this.message == null)
1017            return (null);
1018        else if (this.message.equals(message))
1019            return (null);
1020        else
1021            return ("Expected message='" + this.message + "', got message='" +
1022                    message + "'");
1023
1024    }
1025
1026
1027    /**
1028     * Validate the returned status code against what we expected. Return
1029     * <code>null</code> for no problems, or an error message.
1030     *
1031     * @param status The returned status code
1032     */

1033    protected String JavaDoc validateStatus(int status) {
1034
1035        if (this.status == 0)
1036            return (null);
1037        if (this.status == status)
1038            return (null);
1039        else
1040            return ("Expected status=" + this.status + ", got status=" +
1041                    status);
1042
1043    }
1044
1045
1046}
1047
Popular Tags