KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > verifier > ReportHandler


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.tools.verifier;
25
26 import java.io.OutputStream JavaDoc;
27 import java.io.ByteArrayOutputStream JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.FileInputStream JavaDoc;
31 import java.io.OutputStreamWriter JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.io.StringWriter JavaDoc;
35 import java.text.SimpleDateFormat JavaDoc;
36 import java.util.Date JavaDoc;
37 import java.util.Enumeration JavaDoc;
38 import java.util.Vector JavaDoc;
39 import java.util.Locale JavaDoc;
40 import java.util.logging.Level JavaDoc;
41 import java.util.logging.LogRecord JavaDoc;
42 import java.util.logging.Logger JavaDoc;
43
44 import javax.xml.parsers.DocumentBuilder JavaDoc;
45 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
46 import javax.xml.transform.OutputKeys JavaDoc;
47 import javax.xml.transform.Transformer JavaDoc;
48 import javax.xml.transform.TransformerFactory JavaDoc;
49 import javax.xml.transform.dom.DOMSource JavaDoc;
50 import javax.xml.transform.stream.StreamResult JavaDoc;
51 import javax.xml.transform.stream.StreamSource JavaDoc;
52
53 import org.w3c.dom.Document JavaDoc;
54 import org.w3c.dom.Element JavaDoc;
55 import org.w3c.dom.NodeList JavaDoc;
56
57 import com.sun.enterprise.logging.LogDomains;
58 import com.sun.enterprise.server.Constants;
59 import com.sun.enterprise.tools.verifier.util.VerifierConstants;
60 import com.sun.enterprise.tools.verifier.StringManagerHelper;
61
62 /**
63  * This class is responsible for generating the final output report file in xml and txt file.
64  *
65  * @author Sudipto Ghosh
66  */

67
68 public class ReportHandler {
69
70     private final String JavaDoc TEST = "test"; // NOI18N
71
private final String JavaDoc TEST_NAME = "test-name"; // NOI18N
72
private final String JavaDoc TEST_DESC = "test-description"; // NOI18N
73
private final String JavaDoc TEST_ASSERTION = "test-assertion"; // NOI18N
74
private final String JavaDoc STATIC_VER = "static-verification"; // NOI18N
75
private final String JavaDoc FAILED = "failed"; // NOI18N
76
private final String JavaDoc PASSED = "passed"; // NOI18N
77
private final String JavaDoc NOTAPPLICABLE = "not-applicable"; // NOI18N
78
private final String JavaDoc WARNING = "warning"; // NOI18N
79

80     private final String JavaDoc FAILNUMBER = "failure-number"; // NOI18N
81
private final String JavaDoc WARNINGNUMBER = "warning-number"; // NOI18N
82
private final String JavaDoc ERRORNUMBER = "error-number"; // NOI18N
83
private final String JavaDoc FAILCOUNT = "failure-count"; // NOI18N
84

85     private final String JavaDoc ERROR = "error"; // NOI18N
86
private final String JavaDoc ERROR_NAME = "error-name"; // NOI18N
87
private final String JavaDoc ERROR_DESC = "error-description"; // NOI18N
88
private final String JavaDoc XSL_FILE = "textFormatForVerifierSS"; // NOI18N
89
private String JavaDoc outputFileStr = null;
90
91     private Element JavaDoc rootNode = null;
92     private Document JavaDoc document;
93     private String JavaDoc textResult; // verification result in TEXT form.
94
private ResultManager resultMgr;
95     private FrameworkContext frameworkContext;
96     private Logger JavaDoc logger = LogDomains.getLogger(LogDomains.AVK_VERIFIER_LOGGER);
97
98     /**
99      * Verifier uses this constructor to generate test report.
100      * @param frameworkContext
101      */

102     public ReportHandler(FrameworkContext frameworkContext) {
103         this.frameworkContext = frameworkContext;
104         this.resultMgr = frameworkContext.getResultManager();
105
106         String JavaDoc onlyJarFile = new File JavaDoc(frameworkContext.getJarFileName()).getName();
107         String JavaDoc outputDirName = frameworkContext.getOutputDirName();
108         outputDirName = (outputDirName == null) ?
109                 "" : outputDirName + File.separator;
110         if (frameworkContext.isUseTimeStamp()) {
111             SimpleDateFormat JavaDoc dateFormatter = new SimpleDateFormat JavaDoc(
112                     "yyyyMMddhhmmss"); // NOI18N
113
outputFileStr = outputDirName + onlyJarFile +
114                     dateFormatter.format(new Date JavaDoc());
115         } else
116             outputFileStr = outputDirName + onlyJarFile;
117     }
118
119     /**
120      * This api is called from verfier framework to generate the final report
121      *
122      * @throws IOException
123      */

124     public void generateAllReports() throws IOException JavaDoc {
125         try {
126             createResultsDocument(frameworkContext.getReportLevel());
127             writeToXmlFile();
128             writeToTxtFile();
129             writeToConsole();
130         } catch (IOException JavaDoc e) {
131             throw e;
132         }
133     }
134
135     /**
136      * writes the final output report file to the console.
137      */

138     private void writeToConsole() {
139         if (frameworkContext.isUsingGui())
140             return;
141         if (frameworkContext.isBackend()) {
142             logger.log(Level.SEVERE, textResult);
143         } else {
144             logger.log(Level.INFO, getClass().getName() + ".resultSummary",
145                 new Object JavaDoc[]{new Integer JavaDoc(resultMgr.getFailedCount()),
146                              new Integer JavaDoc(resultMgr.getWarningCount()),
147                              new Integer JavaDoc(resultMgr.getErrorCount())});
148         }
149         if((resultMgr.getFailedCount() + resultMgr.getWarningCount()
150             + resultMgr.getErrorCount()) != 0
151             || frameworkContext.getReportLevel() == VerifierConstants.ALL)
152             logger.log(Level.INFO, getClass().getName() +
153                 ".LookInResultsTestAssertions", // NOI18N
154
new Object JavaDoc[]{outputFileStr + ".txt"}); // NOI18N
155
else
156             logger.log(Level.INFO, getClass().getName() +
157                 ".LookInResultsTestAssertions1"); // NOI18N
158
}
159
160     /**
161      * This api initializes the document object and calls generate apis to add results
162      * to the document. Finally failureCount() api is called to add the error, failure
163      * and warning counts to the document.
164      *
165      * @param reportLevel
166      * @throws IOException
167      */

168     private void createResultsDocument(int reportLevel) throws IOException JavaDoc {
169         createDOMTree();
170         if (reportLevel != VerifierConstants.FAIL)
171             addResultsToDocument(WARNING, resultMgr.getWarningResults());
172         if (reportLevel == VerifierConstants.ALL) {
173             addResultsToDocument(PASSED, resultMgr.getOkayResults());
174             addResultsToDocument(NOTAPPLICABLE, resultMgr.getNaResults());
175         }
176
177         addResultsToDocument(FAILED, resultMgr.getFailedResults());
178         Vector JavaDoc error = resultMgr.getError();
179         if (!error.isEmpty()) {
180             for (int i = 0; i < error.size(); i++) {
181                 LogRecord JavaDoc lr = (LogRecord JavaDoc) error.get(i);
182                 generateErrors(lr);
183             }
184         }
185         failureCount();
186     }
187
188     /**
189      * create the new Document tree with root node <static-verification>
190      *
191      * @throws IOException
192      */

193     private void createDOMTree() throws IOException JavaDoc {
194         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
195         DocumentBuilder JavaDoc builder = null;
196         try {
197             builder = factory.newDocumentBuilder();
198         } catch (Exception JavaDoc e) {
199             IOException JavaDoc ioe = new IOException JavaDoc(e.getMessage());
200             ioe.initCause(e);
201             throw ioe;
202         }
203         document = builder.newDocument();
204         rootNode = document.createElement(STATIC_VER);
205         document.appendChild(rootNode);
206     }
207
208     /**
209      * This api adds each result to the document tree based on the status.
210      *
211      * @param status
212      * @param resultVector
213      */

214     private void addResultsToDocument(String JavaDoc status, Vector JavaDoc resultVector) {
215         for (int i = 0; i < resultVector.size(); i++) {
216             Enumeration JavaDoc en;
217             Result r = (Result) resultVector.get(i);
218             String JavaDoc moduleName = r.getModuleName();
219             if (status == FAILED) {
220                 en = r.getErrorDetails().elements();
221             } else if (status == WARNING) {
222                 en = r.getWarningDetails().elements();
223             } else if (status == PASSED)
224                 en = r.getGoodDetails().elements();
225             else
226                 en = r.getNaDetails().elements();
227             createNode(moduleName, status);
228             addToDocument(moduleName, status, r, en);
229         }
230     }
231
232     /**
233      * This api is used to add the error logs into the document.
234      *
235      * @param record
236      */

237     private void generateErrors(LogRecord JavaDoc record) {
238         Element JavaDoc errorNode = null;
239         //start adding nodes to document
240
//check if the node already exists. If not, add it.
241
NodeList JavaDoc nodeList = document.getElementsByTagName(ERROR);
242         if (nodeList.getLength() == 0) {
243             errorNode = document.createElement(ERROR);
244             rootNode.appendChild(errorNode);
245         } else {
246             errorNode = (Element JavaDoc) nodeList.item(0); //there is only 1 node with tag of errorNode value
247
}
248         Element JavaDoc excepName = getTextNode(ERROR_NAME, record.getMessage());
249         errorNode.appendChild(excepName);
250         if (record.getThrown() != null) {
251             Element JavaDoc excepDescr = getTextNode(ERROR_DESC,
252                     writeStackTraceToFile(record.getThrown()));
253             errorNode.appendChild(excepDescr);
254         }
255     }
256
257     /**
258      * This method is responsible for creating nodes in the DOM tree like
259      * <p>
260      * <ejb>
261      * <failed></failed>
262      * </ejb>
263      * where moduleName is ejb and status is failed.
264      *
265      * @param moduleName
266      * @param status
267      */

268     private void createNode(String JavaDoc moduleName, String JavaDoc status) {
269         NodeList JavaDoc nodeList;
270         Element JavaDoc moduleNode;
271         nodeList = document.getElementsByTagName(moduleName);
272         if (nodeList.getLength() == 0) {
273             moduleNode = document.createElement(moduleName);
274             rootNode.appendChild(moduleNode);
275         } else {
276             moduleNode = (Element JavaDoc) nodeList.item(0); //there is only 1 node with tag of moduleNode value
277
}
278         nodeList = moduleNode.getChildNodes();
279         Element JavaDoc statusNode = null;
280
281         if (nodeList.getLength() == 0) {
282             statusNode = document.createElement(status);
283             moduleNode.appendChild(statusNode);
284         } else {
285             for (int j = 0; j < nodeList.getLength(); j++) {
286                 if (((Element JavaDoc) nodeList.item(j)).getTagName().equals(status)) {
287                     statusNode = (Element JavaDoc) nodeList.item(j);
288                     break;
289                 }
290             }
291             if (statusNode == null) {
292                 statusNode = document.createElement(status);
293                 moduleNode.appendChild(statusNode);
294             }
295         }
296     }
297
298     /**
299      * This method adds the result value to the appropriate location in the DOM
300      * tree.
301      * @param moduleName
302      * @param status
303      * @param r
304      * @param en
305      */

306     private void addToDocument(String JavaDoc moduleName, String JavaDoc status, Result r,
307                                Enumeration JavaDoc en) {
308         if (r == null) return;
309         NodeList JavaDoc nodeList;
310         //this nodeList is the list of nodes below the moduleNode
311
nodeList =
312                 document.getElementsByTagName(moduleName).item(0)
313                 .getChildNodes();
314         Element JavaDoc statusNode = null;
315         for (int j = 0; j < nodeList.getLength(); j++) {
316             if (((Element JavaDoc) nodeList.item(j)).getTagName().equals(status)) {
317                 statusNode = (Element JavaDoc) nodeList.item(j);
318                 break;
319             }
320         }
321         // now get the stuff and write out from result object r
322
Element JavaDoc test = document.createElement(TEST);
323         Element JavaDoc testName = getTextNode(TEST_NAME, r.getTestName());
324         Element JavaDoc testAssertion = getTextNode(TEST_ASSERTION, r.getAssertion());
325         // loop thru Details vector
326
String JavaDoc string = "";
327         while (en.hasMoreElements()) {
328             string = string + (String JavaDoc) en.nextElement() + "\n"; // NOI18N
329
}
330         Element JavaDoc testDescr = getTextNode(TEST_DESC, string);
331         test.appendChild(testName);
332         test.appendChild(testAssertion);
333         test.appendChild(testDescr);
334         statusNode.appendChild(test);
335     }
336
337     /**
338      * Convenience for creating a node <tag>text<tag>.
339      *
340      * @param tag
341      * @param text
342      * @return
343      */

344     private Element JavaDoc getTextNode(String JavaDoc tag, String JavaDoc text) {
345         Element JavaDoc element = document.createElement(tag);
346         element.appendChild(document.createTextNode(text));
347         return element;
348     }
349
350     /**
351      * wites the final result report to the output xml file
352      *
353      * @throws IOException
354      */

355     private void writeToXmlFile() throws IOException JavaDoc {
356         FileOutputStream JavaDoc fos = null;
357         try {
358             File JavaDoc outputFile = extractResultsFileToTmpDir(
359                     outputFileStr + ".xml"); // NOI18N
360
DOMSource JavaDoc domSource = new DOMSource JavaDoc(document);
361             TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
362             Transformer JavaDoc transformer = tfactory.newTransformer();
363             transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
364
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NOI18N
365
String JavaDoc encoding = System.getProperty("file.encoding");
366             transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
367             fos = new FileOutputStream JavaDoc(outputFile);
368             transformer.transform(domSource, new StreamResult JavaDoc(fos));
369         } catch (Exception JavaDoc e) {
370             IOException JavaDoc ioe = new IOException JavaDoc(e.getMessage());
371             ioe.initCause(e);
372             throw ioe;
373         } finally {
374             try {
375                 if(fos != null)
376                     fos.close();
377             } catch (Exception JavaDoc e){}
378         }
379     }
380
381     /**
382      * writes the final result report to output txt file
383      *
384      * @throws IOException
385      */

386     private void writeToTxtFile() throws IOException JavaDoc {
387         File JavaDoc xslFile = getLocalizedXSLFile();
388         
389         Document JavaDoc dynamicDocument = document;
390         ByteArrayOutputStream JavaDoc output = new ByteArrayOutputStream JavaDoc();
391         generateText(dynamicDocument, xslFile, output);
392         textResult = output.toString("UTF-8");
393         
394         // dump to text file.
395
File JavaDoc outputFile = extractResultsFileToTmpDir(outputFileStr + ".txt"); // NOI18N
396
OutputStreamWriter JavaDoc fw = new OutputStreamWriter JavaDoc(
397                                     new FileOutputStream JavaDoc(outputFile));
398         fw.write(textResult);
399         fw.close();
400     }
401
402     private File JavaDoc extractResultsFileToTmpDir(String JavaDoc jarFile) {
403         File JavaDoc tmpJarFile = null;
404         String JavaDoc fullFilename;
405         tmpJarFile = new File JavaDoc(jarFile);
406         fullFilename = tmpJarFile.getAbsolutePath();
407         if (new File JavaDoc(fullFilename).getParent() != null) {
408             (new File JavaDoc(new File JavaDoc(fullFilename).getParent())).mkdirs();
409         }
410         return tmpJarFile;
411     }
412
413     /**
414      * Transforms the xml report to txt report.
415      * @param xmlResult
416      * @param stylesheet
417      * @param summaryFile
418      * @throws IOException
419      */

420     private void generateText(Document JavaDoc xmlResult, File JavaDoc stylesheet,
421                               OutputStream JavaDoc output)
422             throws IOException JavaDoc {
423         // Produce Output:
424
FileOutputStream JavaDoc fos = null;
425         try {
426             StreamSource JavaDoc styleSource;
427             Transformer JavaDoc transformer;
428             TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
429             if (stylesheet != null) {
430                 FileInputStream JavaDoc fis = new FileInputStream JavaDoc(stylesheet);
431                 styleSource = new StreamSource JavaDoc(fis);
432                 transformer = tFactory.newTransformer(styleSource);
433             } else {
434                 transformer = tFactory.newTransformer();
435             }
436             DOMSource JavaDoc source = new DOMSource JavaDoc(xmlResult);
437             StreamResult JavaDoc streamResult = new StreamResult JavaDoc(output);
438             transformer.transform(source, streamResult);
439
440         } catch (Exception JavaDoc e) {
441             IOException JavaDoc ioe = new IOException JavaDoc(e.getMessage());
442             ioe.initCause(e);
443             throw ioe;
444         } finally {
445             try {
446                 if(fos != null)
447                     fos.close();
448             } catch (Exception JavaDoc e) {}
449         }
450     }
451
452     private void failureCount() {
453         int failedCount = resultMgr.getFailedCount();
454         int warningCount = resultMgr.getWarningCount();
455         int errorCount = resultMgr.getErrorCount();
456
457         Element JavaDoc failureNode = null;
458         NodeList JavaDoc nodeList = document.getElementsByTagName(FAILCOUNT);
459         if (nodeList.getLength() == 0) {
460             failureNode = document.createElement(FAILCOUNT);
461             rootNode.appendChild(failureNode);
462         } else {
463             failureNode = (Element JavaDoc) nodeList.item(0);
464         }
465
466         nodeList = failureNode.getChildNodes();//document.getElementsByTagName(FAILED);
467
Element JavaDoc failed_count = null;
468         Element JavaDoc warning_count = null;
469         Element JavaDoc error_count = null;
470
471         if (nodeList.getLength() == 0) {
472             failed_count =
473                     getTextNode(FAILNUMBER,
474                             new Integer JavaDoc(failedCount).toString());
475             failureNode.appendChild(failed_count);
476
477             warning_count =
478                     getTextNode(WARNINGNUMBER,
479                             new Integer JavaDoc((warningCount)).toString());
480             failureNode.appendChild(warning_count);
481
482             error_count =
483                     getTextNode(ERRORNUMBER,
484                             new Integer JavaDoc(errorCount).toString());
485             failureNode.appendChild(error_count);
486         } else {
487             for (int j = 0; j < nodeList.getLength(); j++) {
488                 if (((Element JavaDoc) nodeList.item(j)).getTagName().equals(
489                         FAILNUMBER)) {
490                     failed_count = (Element JavaDoc) nodeList.item(j);
491                     (failed_count.getFirstChild()).setNodeValue(
492                             new Integer JavaDoc(failedCount).toString());
493                 }
494                 if (((Element JavaDoc) nodeList.item(j)).getTagName().equals(
495                         WARNINGNUMBER)) {
496                     warning_count = (Element JavaDoc) nodeList.item(j);
497                     (warning_count.getFirstChild()).setNodeValue(
498                             new Integer JavaDoc(warningCount).toString());
499                 }
500                 if (((Element JavaDoc) nodeList.item(j)).getTagName().equals(
501                         ERRORNUMBER)) {
502                     error_count = (Element JavaDoc) nodeList.item(j);
503                     (error_count.getFirstChild()).setNodeValue(
504                             new Integer JavaDoc(errorCount).toString());
505                 }
506             }
507             if (failed_count == null) {
508                 failed_count =
509                         getTextNode(FAILNUMBER,
510                                 new Integer JavaDoc(failedCount).toString());
511                 failureNode.appendChild(failed_count);
512             }
513             if (warning_count == null) {
514                 warning_count =
515                         getTextNode(WARNINGNUMBER,
516                                 new Integer JavaDoc(warningCount).toString());
517                 failureNode.appendChild(warning_count);
518             }
519             if (error_count == null) {
520                 error_count =
521                         getTextNode(ERRORNUMBER,
522                                 new Integer JavaDoc(errorCount).toString());
523                 failureNode.appendChild(error_count);
524             }
525         }
526     }
527
528     /**
529      * returns the error description for writing to the final report.
530      * @param e
531      * @return
532      */

533     private String JavaDoc writeStackTraceToFile(Throwable JavaDoc e) {
534         StringWriter JavaDoc sw = new StringWriter JavaDoc();
535         e.printStackTrace(new PrintWriter JavaDoc(sw));
536         return sw.toString();
537     }
538     
539     /**
540      * <p>
541      * @return the localized XSL file if it is present in the configuration
542      * directory. If not, return the default one which is english
543      * </p>
544      */

545     private File JavaDoc getLocalizedXSLFile() {
546         String JavaDoc xslHome = System.getProperty(Constants.VERIFIER_XSL);
547         if (xslHome == null) {
548             xslHome = System.getProperty(Constants.INSTALL_ROOT) +
549                     File.separator +
550                     "lib" + // NOI18N
551
File.separator +
552                     "verifier"; // NOI18N
553
}
554         Locale JavaDoc locale = Locale.getDefault();
555         
556         // check first with the language and country
557
String JavaDoc xslFileName = xslHome + File.separator + XSL_FILE + "_" + locale.toString() + ".xsl"; // NOI18N
558
File JavaDoc xslFile = new File JavaDoc(xslFileName);
559         if (xslFile.exists()) {
560             return xslFile;
561         }
562         // check now with the language
563
xslFileName = xslHome + File.separator + XSL_FILE + "_" + locale.getLanguage() + ".xsl"; // NOI18N
564
xslFile = new File JavaDoc(xslFileName);
565         if (xslFile.exists()) {
566             return xslFile;
567         }
568         // just take the english version now...
569
xslFileName = xslHome + File.separator + XSL_FILE + ".xsl"; // NOI18N
570
xslFile = new File JavaDoc(xslFileName);
571         return xslFile;
572     }
573
574 }
575
Popular Tags