KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > xml > driver > TestDiff


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: TestDiff.java,v 1.2 2005/01/26 08:29:24 jkjome Exp $
22  */

23
24 package org.enhydra.xml.driver;
25
26 import java.io.BufferedReader JavaDoc;
27 import java.io.BufferedWriter JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.FileNotFoundException JavaDoc;
30 import java.io.FileReader JavaDoc;
31 import java.io.FileWriter JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.util.ArrayList JavaDoc;
35
36 import org.enhydra.xml.driver.diff.diff;
37
38
39 /**
40  * Object to perform comparisons of test files with expected files.
41  * Also functions to search files. Failures maybe queued to allow
42  * as many files as possible to be diffed.
43  */

44 public class TestDiff {
45     /**
46      * Interface for filtering lines of input.
47      */

48     public interface LineFilter {
49         /** Filter a line */
50         public String JavaDoc filter(String JavaDoc line);
51     }
52
53     /**
54      * Flag indicating that failures should not be thrown immediatly, but
55      * queued for reporting later. Allows batching of updates.
56      */

57     public static final int QUEUE_FAILURES = 0x01;
58
59     /** Should missing or miss-matched expected files be updated? */
60     public static final int UPDATE_EXPECTED = 0x02;
61     
62     /** Don't output diffs or throw exceptions, just return status */
63     public static final int NO_OUTPUT = 0x04;
64     
65     /** Size of buffer to use for I/O */
66     private static final int BUF_SIZE = 2048;
67
68     /** Flag set */
69     private int fFlags;
70
71     /** List of filters to apply */
72     private ArrayList JavaDoc fFilters = new ArrayList JavaDoc();
73
74     /** List of files that didn't match, or null if all have been ok */
75     private ArrayList JavaDoc fFailedFiles;
76
77     /** Writer for messages. */
78     private PrintWriter JavaDoc fMsgWriter;
79
80     /**
81      * Class to filter input. The relies on only readLine() being used.
82      */

83     private class LineFilterReader extends BufferedReader JavaDoc {
84         /** File object */
85         private File JavaDoc fFile;
86
87         /** Constructor */
88         public LineFilterReader(File JavaDoc inFile) throws IOException JavaDoc {
89             super(new FileReader JavaDoc(inFile), BUF_SIZE);
90             fFile = inFile;
91         }
92         
93         /** Get File */
94         public File JavaDoc getFile() {
95             return fFile;
96         }
97
98         /** read a line, filtering it */
99         public String JavaDoc readLine() throws IOException JavaDoc {
100             String JavaDoc line = super.readLine();
101             if (line == null) {
102                 return null;
103             }
104             int numFilters= fFilters.size();
105             for (int idx = 0; idx < numFilters; idx++) {
106                 line = ((LineFilter)fFilters.get(idx)).filter(line);
107             }
108             return line;
109         }
110     }
111
112     /**
113      * Constructor.
114      */

115     public TestDiff(PrintWriter JavaDoc msgWriter,
116                     int flags) {
117         fMsgWriter = msgWriter;
118         fFlags = flags;
119     }
120
121     /** Add a filter */
122     public void addFilter(LineFilter filter) {
123         fFilters.add(filter);
124     }
125
126     /** Copy file lines */
127     private void copyLines(BufferedReader JavaDoc in,
128                            BufferedWriter JavaDoc out) throws IOException JavaDoc {
129         String JavaDoc line;
130         while ((line = in.readLine()) != null) {
131             out.write(line, 0, line.length());
132             out.newLine();
133         }
134     }
135
136     /** Update an expected file, filter file contents */
137     private void updateExpected(File JavaDoc expectedFile,
138                                 File JavaDoc gotFile) {
139         fMsgWriter.println("Update " + expectedFile + " from " + gotFile);
140         try {
141             TestFileOps.ensureFileDir(expectedFile);
142             BufferedWriter JavaDoc out = new BufferedWriter JavaDoc(new FileWriter JavaDoc(expectedFile),
143                                                     BUF_SIZE);
144             try {
145                 BufferedReader JavaDoc in = new LineFilterReader(gotFile);
146                 try {
147                     copyLines(in, out);
148                 } finally {
149                     in.close();
150                 }
151             } finally {
152                 out.close();
153             }
154         } catch (IOException JavaDoc except) {
155             throw new TestError("update of expected file failed", except);
156         }
157     }
158
159     /**
160      * Log a diff error.
161      * @param except maybe null
162      */

163     private void diffError(File JavaDoc expectedFile,
164                            File JavaDoc gotFile,
165                            Throwable JavaDoc except) {
166         if (fFailedFiles == null) {
167             fFailedFiles = new ArrayList JavaDoc();
168         }
169         fFailedFiles.add(gotFile);
170
171         String JavaDoc msg = "diff of \"" + expectedFile + "\" and \""
172             + gotFile + "\" failed";
173         if (except instanceof FileNotFoundException JavaDoc) {
174             // No strack trace if one of the files is missing
175
fMsgWriter.println(msg + ": " + except);
176         } else if (except != null) {
177             fMsgWriter.println(msg);
178             except.printStackTrace();
179         }
180         if ((fFlags & UPDATE_EXPECTED) != 0) {
181             updateExpected(expectedFile, gotFile);
182         }
183         if ((fFlags & QUEUE_FAILURES) == 0) {
184             throw new DiffException(msg, except);
185         }
186     }
187
188     /** Do the work of the diff and reporting */
189     private boolean doDiff(File JavaDoc expectedFile,
190                            BufferedReader JavaDoc expected,
191                            LineFilterReader got) throws IOException JavaDoc {
192         diff differ = new diff();
193         differ.diffBuffer(expected, got);
194         int numHunks = differ.numberOfHunk();
195         if (numHunks > 0) {
196             if ((fFlags & NO_OUTPUT) == 0) {
197                 // output requrested
198
for (int idx = 0; idx < numHunks; idx++) {
199                     fMsgWriter.print(differ.hunkAt(idx).convert());
200                 }
201                 fMsgWriter.println();
202                 diffError(expectedFile, got.getFile(), null);
203             }
204             return false;
205         }
206         return true;
207     }
208
209     /**
210      * Diff an results file against an expected file, log an error
211      * if the files don't match.
212      * @return true if they match, false if they don't
213      */

214     public boolean diff(File JavaDoc expectedFile,
215                         File JavaDoc gotFile) {
216         try {
217             BufferedReader JavaDoc expected
218                 = new BufferedReader JavaDoc(new FileReader JavaDoc(expectedFile), BUF_SIZE);
219             try {
220                 LineFilterReader got = new LineFilterReader(gotFile);
221
222                 try {
223                     return doDiff(expectedFile, expected, got);
224                 } finally {
225                     got.close();
226                 }
227             } finally {
228                 expected.close();
229             }
230         } catch (IOException JavaDoc except) {
231             diffError(expectedFile, gotFile, except);
232             return false;
233         }
234     }
235
236     /**
237      * Generate and throw and exception if diff errors occured. Do
238      * nothing otherwise. This allows expected files to be updated
239      * for several diffs before reporting an error.
240      */

241     public void throwPendingDiffFailures() {
242         if (fFailedFiles != null) {
243             StringBuffer JavaDoc msg = new StringBuffer JavaDoc(512);
244             msg.append("diff with expected files failed, see stderr for details: ");
245             for (int idx = 0; idx < fFailedFiles.size(); idx++) {
246                 if (idx > 0) {
247                     msg.append(", ");
248                 }
249                 msg.append(fFailedFiles.get(idx));
250             }
251             fFailedFiles = null;
252             throw new DiffException(msg.toString());
253         }
254     }
255
256     /**
257      * Search a file for lines contining a string (not a regular expression).
258      */

259     public boolean fgrep(String JavaDoc searchStr,
260                          File JavaDoc fileName) {
261         try {
262             BufferedReader JavaDoc in = new BufferedReader JavaDoc(new FileReader JavaDoc(fileName));
263             try {
264                 String JavaDoc line;
265                 while ((line = in.readLine()) != null) {
266                     if (line.indexOf(searchStr) >= 0) {
267                         break; // found
268
}
269                 }
270                 if (line == null) {
271                     return false;
272                 } else {
273                     return true;
274                 }
275             } finally {
276                 in.close();
277             }
278         } catch (FileNotFoundException JavaDoc except) {
279             throw new DiffException("fgrep failed: " + except);
280         } catch (IOException JavaDoc except) {
281             throw new DiffException("fgrep of \"" + fileName + "\" failed ",
282                                     except);
283         }
284     }
285
286     /**
287      * Generate a test error if a string is not found.
288      */

289     public void fgrepMustFind(String JavaDoc searchStr,
290                               File JavaDoc fileName) {
291         if (!fgrep(searchStr, fileName)) {
292             throw new DiffException("did not find \"" + searchStr + "\" in \""
293                                     + fileName + "\"");
294         }
295     }
296
297     /**
298      * Generate a test error if a string is found.
299      */

300     public void fgrepMustNotFind(String JavaDoc searchStr,
301                                  File JavaDoc fileName) {
302         if (fgrep(searchStr, fileName)) {
303             throw new DiffException("should not have found \"" + searchStr + "\" in \""
304                                     + fileName + "\"");
305         }
306     }
307 }
308
Popular Tags