1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jelly.tags.junit;
17
18 import java.io.BufferedReader;
19 import java.io.File;
20 import java.io.FileNotFoundException;
21 import java.io.FileReader;
22 import java.io.IOException;
23
24 import org.apache.commons.jelly.MissingAttributeException;
25 import org.apache.commons.jelly.JellyTagException;
26 import org.apache.commons.jelly.XMLOutput;
27
28 /***
29 * Checks that a file exists, and if not, then the test will fail.
30 *
31 * @author <a href="mailto:dion@apache.org">Dion Gillard</a>
32 * @version $Revision: 345902 $
33 */
34 public class AssertFileContainsTag extends AssertTagSupport
35 {
36 /*** the file to check */
37 private File file;
38
39 /*** content to match */
40 private String match;
41
42 /***
43 * Do the tag functionality: check the file exists.
44 * @param output a place to write text output
45 * @throws JellyTagException if the file doesn't exist.
46 */
47 public void doTag(XMLOutput output) throws JellyTagException
48 {
49 if (match == null)
50 {
51 throw new MissingAttributeException("match");
52 }
53 String message = getBodyText();
54 if (message == null || message.length() == 0)
55 {
56 message = "File does not contain '" + match + "'";
57 }
58
59
60 if (file == null)
61 {
62 throw new MissingAttributeException("file");
63 }
64 else
65 {
66 if (file.exists() && file.canRead())
67 {
68 try
69 {
70 BufferedReader br = new BufferedReader(new FileReader(file));
71 String line;
72 boolean found = false;
73 while ((line = br.readLine()) != null)
74 {
75 if (line.indexOf(match) != -1)
76 {
77 found = true;
78 break;
79 }
80 }
81 br.close();
82 assertTrue(message, found);
83 }
84 catch (IOException fnfe)
85 {
86 throw new JellyTagException(fnfe);
87 }
88 }
89 else
90 {
91 try
92 {
93 throw new JellyTagException("File '" + file.getCanonicalPath()
94 + "' can't be read.");
95 }
96 catch (IOException e)
97 {
98 throw new JellyTagException(e);
99 }
100 }
101 }
102 }
103
104 /***
105 * The file to be tested. If this file exists, the test will pass.
106 * @param aFile the file to test.
107 */
108 public void setFile(File aFile)
109 {
110 file = aFile;
111 }
112
113 /***
114 * The content to be checked for. If this text matches some part
115 * of the given file, the test will pass.
116 */
117 public void setMatch(String aString)
118 {
119 match = aString;
120 }
121 }