KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > assertions > HTMLAssertion


1 // $Header: /home/cvs/jakarta-jmeter/src/components/org/apache/jmeter/assertions/HTMLAssertion.java,v 1.1.2.1 2004/03/31 21:36:06 sebb Exp $
2
/*
3  * Copyright 2003-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jmeter.assertions;
20
21 import java.io.ByteArrayInputStream JavaDoc;
22 import java.io.ByteArrayOutputStream JavaDoc;
23 import java.io.FileWriter JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.PrintWriter JavaDoc;
26 import java.io.Serializable JavaDoc;
27 import java.io.StringWriter JavaDoc;
28 import java.text.MessageFormat JavaDoc;
29
30 import org.apache.jmeter.samplers.SampleResult;
31 import org.apache.jmeter.testelement.AbstractTestElement;
32 import org.apache.jmeter.testelement.property.BooleanProperty;
33 import org.apache.jmeter.testelement.property.LongProperty;
34 import org.apache.jmeter.testelement.property.StringProperty;
35 import org.apache.jmeter.util.JMeterUtils;
36 import org.apache.jorphan.logging.LoggingManager;
37 import org.apache.log.Logger;
38 import org.w3c.tidy.Node;
39 import org.w3c.tidy.Tidy;
40
41 /**
42  * Assertion to validate the response of a Sample with Tidy.
43  */

44 public class HTMLAssertion extends AbstractTestElement implements Serializable JavaDoc, Assertion {
45
46   //constants
47
public static final String JavaDoc DEFAULT_DOCTYPE = "omit";
48   public static final String JavaDoc DOCTYPE_KEY = "html_assertion_doctype";
49   public static final String JavaDoc ERRORS_ONLY_KEY = "html_assertion_errorsonly";
50   public static final String JavaDoc ERROR_THRESHOLD_KEY = "html_assertion_error_threshold";
51   public static final String JavaDoc WARNING_THRESHOLD_KEY = "html_assertion_warning_threshold";
52   public static final String JavaDoc FORMAT_KEY = "html_assertion_format";
53   public static final String JavaDoc FILENAME_KEY = "html_assertion_filename";
54
55   //class attributes
56
transient private static Logger log = LoggingManager.getLoggerForClass();
57
58   /**
59    *
60    */

61   public HTMLAssertion() {
62     log.debug("HTMLAssertion(): called");
63   }
64
65   /**
66    * Returns the result of the Assertion. If so an AssertionResult
67    * containing a FailureMessage will be returned. Otherwise the returned
68    * AssertionResult will reflect the success of the Sample.
69    */

70   public AssertionResult getResult(SampleResult inResponse) {
71     log.debug("HTMLAssertions.getResult() called");
72
73     // no error as default
74
AssertionResult result = new AssertionResult();
75
76     if (inResponse.getResponseData() == null) {
77       return setResultForNull(result);
78     }
79
80     result.setFailure(false);
81
82     // create parser
83
Tidy tidy = null;
84     try {
85       log.debug("HTMLAssertions.getResult(): Setup tidy ...");
86       log.debug("doctype: " + getDoctype());
87       log.debug("errors only: " + isErrorsOnly());
88       log.debug("error threshold: " + getErrorThreshold());
89       log.debug("warning threshold: " + getWarningThreshold());
90       log.debug("html mode: " + isHTML());
91       log.debug("xhtml mode: " + isXHTML());
92       log.debug("xml mode: " + isXML());
93       tidy = new Tidy();
94       tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
95       tidy.setQuiet(false);
96       tidy.setShowWarnings(true);
97       tidy.setOnlyErrors(isErrorsOnly());
98       tidy.setDocType(getDoctype());
99       if (isXHTML()) {
100         tidy.setXHTML(true);
101       } else if (isXML()) {
102         tidy.setXmlTags(true);
103       }
104       log.debug("err file: " + getFilename());
105       tidy.setErrfile(getFilename());
106
107       if (log.isDebugEnabled()) {
108         log.debug("getParser : tidy parser created - " + tidy);
109       }
110       log.debug("HTMLAssertions.getResult(): Tidy instance created!");
111
112     } catch (Exception JavaDoc e) {
113       log.error("Unable to instantiate tidy parser", e);
114       result.setFailure(true);
115       result.setFailureMessage("Unable to instantiate tidy parser");
116       // return with an error
117
return result;
118     }
119
120     /* Run tidy.
121      */

122     try {
123       log.debug("HTMLAssertions.getResult(): start parsing with tidy ...");
124
125       StringWriter JavaDoc errbuf = new StringWriter JavaDoc();
126       tidy.setErrout(new PrintWriter JavaDoc(errbuf));
127       //Node node = tidy.parseDOM(new ByteArrayInputStream(response.getResponseData()), null);
128
ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
129       log.debug("Start : parse");
130       Node node = tidy.parse(new ByteArrayInputStream JavaDoc(inResponse.getResponseData()), os);
131       if (log.isDebugEnabled()) {
132         log.debug("node : " + node);
133       }
134       log.debug("End : parse");
135       log.debug("HTMLAssertions.getResult(): parsing with tidy done!");
136       log.debug("Output: " + os.toString());
137
138       //write output to file
139
writeOutput(errbuf.toString());
140
141       //evaluate result
142
if ((tidy.getParseErrors() > getErrorThreshold()) || (!isErrorsOnly() && (tidy.getParseWarnings() > getWarningThreshold()))) {
143         log.debug("HTMLAssertions.getResult(): errors/warnings detected:");
144         log.debug(errbuf.toString());
145         result.setFailure(true);
146         result.setFailureMessage(MessageFormat.format("Tidy Parser errors: " + tidy.getParseErrors() + " (allowed " + getErrorThreshold() + ") " + "Tidy Parser warnings: " + tidy.getParseWarnings() + " (allowed " + getWarningThreshold() + ")", new Object JavaDoc[0]));
147         //return with an error
148

149       } else if ((tidy.getParseErrors() > 0) || (tidy.getParseWarnings() > 0)) {
150         //return with no error
151
log.debug("HTMLAssertions.getResult(): there were errors/warnings but threshold to high");
152         result.setFailure(false);
153       } else {
154         //return with no error
155
log.debug("HTMLAssertions.getResult(): no errors/warnings detected:");
156         result.setFailure(false);
157       }
158
159     } catch (Exception JavaDoc e) {
160       //return with an error
161
log.warn("Cannot parse result content", e);
162       result.setFailure(true);
163       result.setFailureMessage(e.getMessage());
164     }
165     return result;
166   }
167
168   /**
169    * Writes the output of tidy to file.
170    * @param inOutput
171    */

172   private void writeOutput(String JavaDoc inOutput) {
173     String JavaDoc lFilename = getFilename();
174
175     //check if filename defined
176
if ((lFilename != null) && (!"".equals(lFilename.trim()))) {
177       FileWriter JavaDoc lOutputWriter = null;
178       try {
179
180         //open file
181
lOutputWriter = new FileWriter JavaDoc(lFilename, false);
182
183         //write to file
184
lOutputWriter.write(inOutput);
185         
186         //flush
187
lOutputWriter.flush();
188         
189         log.debug("writeOutput() -> output successfully written to file " + lFilename);
190         
191       } catch (IOException JavaDoc ex) {
192         log.warn("writeOutput() -> could not write output to file " + lFilename, ex);
193       } finally {
194         //close file
195
if (lOutputWriter != null) {
196           try {
197             lOutputWriter.close();
198           } catch (Exception JavaDoc e) {
199           }
200         }
201       }
202     }
203   }
204
205   /**
206    * @param inResult
207    * @return result
208    */

209   protected AssertionResult setResultForNull(AssertionResult inResult) {
210     inResult.setError(false);
211     inResult.setFailure(true);
212     inResult.setFailureMessage("Response was null");
213     return inResult;
214   }
215
216   /**
217    * Gets the doctype
218    * @return the documemt type
219    */

220   public String JavaDoc getDoctype() {
221     return getPropertyAsString(DOCTYPE_KEY);
222   }
223
224   /**
225    * Check if errors will be reported only
226    * @return boolean - report errors only?
227    */

228   public boolean isErrorsOnly() {
229     return getPropertyAsBoolean(ERRORS_ONLY_KEY);
230   }
231
232   /**
233    * Gets the threshold setting for errors
234    * @return long error threshold
235    */

236   public long getErrorThreshold() {
237     return getPropertyAsLong(ERROR_THRESHOLD_KEY);
238   }
239
240   /**
241    * Gets the threshold setting for warnings
242    * @return long warning threshold
243    */

244   public long getWarningThreshold() {
245     return getPropertyAsLong(WARNING_THRESHOLD_KEY);
246   }
247
248   /**
249    * Sets the doctype setting
250    * @param inDoctype
251    */

252   public void setDoctype(String JavaDoc inDoctype) {
253     if ((inDoctype == null) || (inDoctype.trim().equals(""))) {
254       setProperty(new StringProperty(DOCTYPE_KEY, DEFAULT_DOCTYPE));
255     } else {
256       setProperty(new StringProperty(DOCTYPE_KEY, inDoctype));
257     }
258   }
259
260   /**
261    * Sets if errors shoud be tracked only
262    * @param inErrorsOnly
263    */

264   public void setErrorsOnly(boolean inErrorsOnly) {
265     setProperty(new BooleanProperty(ERRORS_ONLY_KEY, inErrorsOnly));
266   }
267
268   /**
269    * Sets the threshold on error level
270    * @param inErrorThreshold
271    */

272   public void setErrorThreshold(long inErrorThreshold) {
273     if (inErrorThreshold < 0L) {
274       throw new IllegalArgumentException JavaDoc(JMeterUtils.getResString("argument_must_not_be_negative"));
275     }
276     if (inErrorThreshold == Long.MAX_VALUE) {
277       setProperty(new LongProperty(ERROR_THRESHOLD_KEY, 0));
278     } else {
279       setProperty(new LongProperty(ERROR_THRESHOLD_KEY, inErrorThreshold));
280     }
281   }
282
283   /**
284    * Sets the threshold on warning level
285    * @param inWarningThreshold
286    */

287   public void setWarningThreshold(long inWarningThreshold) {
288     if (inWarningThreshold < 0L) {
289       throw new IllegalArgumentException JavaDoc(JMeterUtils.getResString("argument_must_not_be_negative"));
290     }
291     if (inWarningThreshold == Long.MAX_VALUE) {
292       setProperty(new LongProperty(WARNING_THRESHOLD_KEY, 0));
293     } else {
294       setProperty(new LongProperty(WARNING_THRESHOLD_KEY, inWarningThreshold));
295     }
296   }
297
298   /**
299    * Enables html validation mode
300    */

301   public void setHTML() {
302     setProperty(new LongProperty(FORMAT_KEY, 0));
303   }
304
305   /**
306    * Check if html validation mode is set
307    * @return boolean
308    */

309   public boolean isHTML() {
310     return getPropertyAsLong(FORMAT_KEY) == 0;
311   }
312
313   /**
314    * Enables xhtml validation mode
315    */

316   public void setXHTML() {
317     setProperty(new LongProperty(FORMAT_KEY, 1));
318   }
319
320   /**
321    * Check if xhtml validation mode is set
322    * @return boolean
323    */

324   public boolean isXHTML() {
325     return getPropertyAsLong(FORMAT_KEY) == 1;
326   }
327
328   /**
329    * Enables xml validation mode
330    */

331   public void setXML() {
332     setProperty(new LongProperty(FORMAT_KEY, 2));
333   }
334
335   /**
336    * Check if xml validation mode is set
337    * @return boolean
338    */

339   public boolean isXML() {
340     return getPropertyAsLong(FORMAT_KEY) == 2;
341   }
342
343   /**
344    * Sets the name of the file where tidy writes the output to
345    * @return name of file
346    */

347   public String JavaDoc getFilename() {
348     return getPropertyAsString(FILENAME_KEY);
349   }
350
351   /**
352    * Sets the name of the tidy output file
353    * @param inName
354    */

355   public void setFilename(String JavaDoc inName) {
356     setProperty(FILENAME_KEY, inName);
357   }
358 }
359
Popular Tags