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