View Javadoc

1   /*
2       Copyright 2006 Ernest Micklei @ PhilemonWorks.com
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 com.philemonworks.selfdiagnose.check;
18  
19  import java.io.BufferedInputStream;
20  import java.io.DataInputStream;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.StringWriter;
24  import java.net.URL;
25  
26  import org.xml.sax.Attributes;
27  
28  import com.philemonworks.selfdiagnose.DiagnoseException;
29  import com.philemonworks.selfdiagnose.DiagnoseUtil;
30  import com.philemonworks.selfdiagnose.DiagnosticTask;
31  import com.philemonworks.selfdiagnose.DiagnosticTaskResult;
32  import com.philemonworks.selfdiagnose.ExecutionContext;
33  
34  /**
35   * CheckFileContainsString is a task that scans a file for at least one occurrence of a String. The file must be
36   * character-based and is found as a resource (on the classpath) or a simple file.
37   * <p/>
38   * <pre>
39   &lt;checkfilecontainsstring name="environment.properties" string="smtp.xs4all.nl" /&gt; 
40   &lt;checkfilecontainsstring url="${urlvar}" string="smtp.xs4all.nl" /&gt;
41   * </pre> 
42   * Stores the URL (java.net.URL) of the file into the (optional) specified variable. 
43   * @author emicklei
44   */
45  public class CheckFileContainsString extends DiagnosticTask {
46      private static final long serialVersionUID = 5554946205887093136L;
47      private static final String PARAMETER_STRING = "string";
48  	private static final String PARAMETER_NAME = "name";
49  	private static final String PARAMETER_URL = "url";	
50  	private String url;
51  	private String name;
52  	private String string;
53  
54  	public void initializeFromAttributes(Attributes attributes) {
55  		// variable
56  		super.initializeFromAttributes(attributes);
57  		this.setName(attributes.getValue(PARAMETER_NAME));
58  		this.setString(attributes.getValue(PARAMETER_STRING));
59  		this.setUrl(attributes.getValue(PARAMETER_URL));
60  	}
61  	/**
62  	 * Return the description of this task.
63  	 */	
64  	public String getDescription() {
65  		return "Check that the (sub)string can be found in the contents of this file";
66  	}	
67  	
68  	public String getConfiguration() {
69  		return "[" + string + "] pattern occurs in file [" + name + "]";
70  	}
71  	public void setUp(ExecutionContext ctx) throws DiagnoseException {
72  		super.setUp(ctx);
73  		if (url == null)
74  			DiagnoseUtil.verifyNonEmptyString(PARAMETER_NAME, name, CheckFileContainsString.class);
75  		if (name == null )
76  			DiagnoseUtil.verifyNonEmptyString(PARAMETER_URL, url, CheckFileContainsString.class);		
77  		DiagnoseUtil.verifyNonEmptyString(PARAMETER_STRING, string, CheckFileContainsString.class);
78  	}
79  	/*
80  	 * (non-Javadoc)
81  	 * 
82  	 * @see com.philemonworks.selfdiagnose.DiagnosticTask#run()
83  	 */
84  	public void run(ExecutionContext ctx, DiagnosticTaskResult result) throws DiagnoseException {
85  		DataInputStream dis = null;
86  		URL theUrl = null;
87  		// how to detect absolute file or resource?
88  		try {
89  			theUrl = DiagnoseUtil.retrieveURL(ctx,name,url);
90  			if (theUrl == null) {
91  				String msg = "Unable to find file";
92  				if (name == null) msg += " by url ["+url+"]"; else msg += " on classpath [" + name + "]";
93  				throw new DiagnoseException(msg);
94  			}
95  			ctx.setValue(this.getVariableName(), theUrl);
96  			InputStream is = theUrl.openStream();
97  			dis = new DataInputStream(new BufferedInputStream(is));
98  		} catch (Exception ex){
99  		    try {
100                 dis.close();
101             } catch (IOException e) {
102                 throw new DiagnoseException(e);
103             }
104 			throw new DiagnoseException(ex);
105 		}
106 		char firstChar = string.charAt(0);
107 		boolean found = false;
108 		// initialize buffer
109 		StringWriter buffer = new StringWriter();
110 		buffer.write(firstChar);
111 		try {
112 			while (dis.available() != 0 && !found) {
113 				char scanChar = (char) dis.read();
114 				if (scanChar == firstChar) {
115 					// remember this position for rollback
116 					dis.mark(string.length());
117 					// fetch the word
118 					for (int i = 0; i < string.length() - 1; i++)
119 						buffer.write(dis.read());
120 					// do the string match
121 					if (buffer.toString().equals(string)) {
122 						
123 						result.setPassedMessage("File ["+theUrl+"] contains string ["+string+"]");
124 						return;
125 					}
126 					// no success, re-initialize buffer and reset to marker
127 					buffer = new StringWriter();
128 					buffer.write(firstChar);
129 					dis.reset();
130 				}
131 			}
132 			dis.close();
133 		} catch (IOException ex) {
134 			throw new DiagnoseException(ex);
135 		}
136 		throw new DiagnoseException("No occurrences found of string [" + string + "] of file ["+theUrl+"]");		
137 	}
138 	/**
139 	 * Return the file name.
140 	 * 
141 	 * @return String the name of the file/resource
142 	 */
143 	public String getName() {
144 		return name;
145 	}
146 	/**
147 	 * Return the substring to search.
148 	 * 
149 	 * @return String substring
150 	 */
151 	public String getString() {
152 		return string;
153 	}
154 	/**
155 	 * Set the name of the file.
156 	 * 
157 	 * @param string
158 	 *        the name of the file/resource
159 	 */
160 	public void setName(String newFileName) {
161 		name = newFileName;
162 	}
163 	/**
164 	 * Set the substring to search.
165 	 * 
166 	 * @param string
167 	 */
168 	public void setString(String newString) {
169 		string = newString;
170 	}
171 
172 	public String getUrl() {
173 		return url;
174 	}
175 
176 	public void setUrl(String url) {
177 		this.url = url;
178 	}
179 }