1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.struts2;
23
24 import java.io.InputStream;
25 import java.net.URL;
26 import java.util.StringTokenizer;
27
28 /***
29 * Utility methods for test classes
30 *
31 */
32 public class TestUtils {
33 /***
34 * normalizes a string so that strings generated on different platforms can be compared. any group of one or more
35 * space, tab, \r, and \n characters are converted to a single space character
36 *
37 * @param obj the object to be normalized. normalize will perform its operation on obj.toString().trim() ;
38 * @param appendSpace
39 * @return the normalized string
40 */
41 public static String normalize(Object obj, boolean appendSpace) {
42 StringTokenizer st =
43 new StringTokenizer(obj.toString().trim(), " \t\r\n");
44 StringBuilder buffer = new StringBuilder(128);
45
46 while(st.hasMoreTokens()) {
47 buffer.append(st.nextToken());
48 }
49
50 return buffer.toString();
51 }
52
53
54 public static String normalize(URL url) throws Exception {
55 return normalize(readContent(url), true);
56 }
57 /***
58 * Attempt to verify the contents of text against the contents of the URL specified. Performs a
59 * trim on both ends
60 *
61 * @param url the HTML snippet that we want to validate against
62 * @throws Exception if the validation failed
63 */
64 public static boolean compare(URL url, String text)
65 throws Exception {
66 /***
67 * compare the trimmed values of each buffer and make sure they're equivalent. however, let's make sure to
68 * normalize the strings first to account for line termination differences between platforms.
69 */
70 String writerString = TestUtils.normalize(text, true);
71 String bufferString = TestUtils.normalize(readContent(url), true);
72
73 return bufferString.equals(writerString);
74 }
75
76
77
78 public static String readContent(URL url)
79 throws Exception {
80 if(url == null) {
81 throw new Exception("unable to verify a null URL");
82 }
83
84 StringBuilder buffer = new StringBuilder(128);
85 InputStream in = url.openStream();
86 byte[] buf = new byte[4096];
87 int nbytes;
88
89 while((nbytes = in.read(buf)) > 0) {
90 buffer.append(new String(buf, 0, nbytes));
91 }
92
93 in.close();
94
95 return buffer.toString();
96 }
97 }