KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > components > validation > MessageAggregatingErrorHandler


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. 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 package org.apache.servicemix.components.validation;
18
19 import java.io.IOException JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.io.StringWriter JavaDoc;
22
23 import javax.jbi.messaging.MessagingException;
24 import javax.xml.parsers.ParserConfigurationException JavaDoc;
25 import javax.xml.transform.TransformerException JavaDoc;
26 import javax.xml.transform.dom.DOMSource JavaDoc;
27
28 import org.apache.servicemix.jbi.jaxp.SourceTransformer;
29 import org.apache.servicemix.jbi.jaxp.StringSource;
30 import org.xml.sax.ErrorHandler JavaDoc;
31 import org.xml.sax.SAXParseException JavaDoc;
32 import org.xml.sax.SAXException JavaDoc;
33
34 /**
35  * An implementation of {@link ErrorHandler} which aggregates all warnings and
36  * error messages into a StringBuffer.
37  *
38  * @version $Revision: 359186 $
39  */

40 public class MessageAggregatingErrorHandler implements MessageAwareErrorHandler {
41     
42     private static final String JavaDoc openCDATA = "<![CDATA[";
43     private static final String JavaDoc closeCDATA = "]]>";
44     private static final String JavaDoc openError = "<error>";
45     private static final String JavaDoc closeError = "</error>";
46     private static final String JavaDoc openFatalError = "<fatalError>";
47     private static final String JavaDoc closeFatalError = "</fataError>";
48     private static final String JavaDoc openWarning = "<warning>";
49     private static final String JavaDoc closeWarning = "</warning>";
50     
51     private String JavaDoc openRootElement;
52     private String JavaDoc closeRootElement;
53
54     /**
55      * Number of warnings.
56      */

57     private int warningCount;
58     
59     /**
60      * Number of errors.
61      */

62     private int errorCount;
63     
64     /**
65      * Number of fatal errors.
66      */

67     private int fatalErrorCount;
68     
69     /**
70      * The root element name for the fault xml message
71      */

72     private String JavaDoc rootPath;
73     
74     /**
75      * The namespace for the fault xml message
76      */

77     private String JavaDoc namespace;
78     
79     /**
80      * Determines whether or not to include stacktraces in the fault xml message
81      */

82     private boolean includeStackTraces;
83     
84     /**
85      * Variable to hold the warning/error messages from the validator
86      */

87     private StringBuffer JavaDoc messages = new StringBuffer JavaDoc();
88     
89     private SourceTransformer sourceTransformer = new SourceTransformer();
90     
91     /**
92      * Constructor.
93      *
94      * @param rootElement
95      * The root element name of the fault xml message
96      * @param namespace
97      * The namespace for the fault xml message
98      */

99     public MessageAggregatingErrorHandler(String JavaDoc rootPath, String JavaDoc namespace) throws IllegalArgumentException JavaDoc {
100         if (rootPath == null || rootPath.trim().length() == 0) {
101             throw new IllegalArgumentException JavaDoc("rootPath must not be null or an empty string");
102         }
103         this.rootPath = rootPath;
104         this.namespace = namespace;
105         createRootElementTags();
106     }
107
108     /**
109      * Constructor.
110      *
111      * @param rootElement
112      * The root element name of the fault xml message
113      * @param namespace
114      * The namespace for the fault xml message
115      * @param includeStackTraces
116      * Include stracktraces in the final output
117      */

118     public MessageAggregatingErrorHandler(String JavaDoc rootPath, String JavaDoc namespace, boolean includeStackTraces) throws IllegalArgumentException JavaDoc {
119         this(rootPath, namespace);
120         this.includeStackTraces = includeStackTraces;
121     }
122
123     /**
124      * @return Returns the sourceTransformer.
125      */

126     public SourceTransformer getSourceTransformer() {
127         return sourceTransformer;
128     }
129
130     /**
131      * @param sourceTransformer The sourceTransformer to set.
132      */

133     public void setSourceTransformer(SourceTransformer sourceTransformer) {
134         this.sourceTransformer = sourceTransformer;
135     }
136
137     /**
138      * Creates the root element tags for later use down to n depth.
139      * Note: the rootPath here is of the form:
140      *
141      * <code>rootElementName/elementName-1/../elementName-n</code>
142      *
143      * The namespace will be appended to the root element if it is not
144      * null or empty.
145      */

146     private void createRootElementTags() {
147         /*
148          * since the rootPath is constrained to be not null or empty
149          * then we have at least one path element.
150          */

151         String JavaDoc[] pathElements = rootPath.split("/");
152
153         StringBuffer JavaDoc openRootElementSB = new StringBuffer JavaDoc().append("<").append(pathElements[0]);
154         StringBuffer JavaDoc closeRootElementSB = new StringBuffer JavaDoc();
155         
156         if (namespace != null && namespace.trim().length() > 0) {
157             openRootElementSB.append(" xmlns=\"").append(namespace).append("\">");
158         } else {
159             openRootElementSB.append(">");
160         }
161         
162         if (pathElements.length > 0) {
163             for (int i = 1, j = pathElements.length - 1; i < pathElements.length; i++, j--) {
164                 openRootElementSB.append("<").append(pathElements[i]).append(">");
165                 closeRootElementSB.append("</").append(pathElements[j]).append(">");
166             }
167         }
168         
169         // create the closing root element tag
170
closeRootElementSB.append("</").append(pathElements[0]).append(">");
171         
172         openRootElement = openRootElementSB.toString();
173         closeRootElement = closeRootElementSB.toString();
174     }
175     
176     /* (non-Javadoc)
177      * @see org.apache.servicemix.components.validation.MessageAwareErrorHandler#hasErrors()
178      */

179     public boolean hasErrors() {
180         return getErrorCount() > 0 || getFatalErrorCount() > 0;
181     }
182
183     /* (non-Javadoc)
184      * @see org.apache.servicemix.components.validation.MessageAwareErrorHandler#getWarningCount()
185      */

186     public int getWarningCount() {
187         return warningCount;
188     }
189
190     /* (non-Javadoc)
191      * @see org.apache.servicemix.components.validation.MessageAwareErrorHandler#getErrorCount()
192      */

193     public int getErrorCount() {
194         return errorCount;
195     }
196
197     /* (non-Javadoc)
198      * @see org.apache.servicemix.components.validation.MessageAwareErrorHandler#getFatalErrorCount()
199      */

200     public int getFatalErrorCount() {
201         return fatalErrorCount;
202     }
203
204     /* (non-Javadoc)
205      * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
206      */

207     public void warning(SAXParseException JavaDoc e) throws SAXException JavaDoc {
208         ++warningCount;
209
210         // open warning and CDATA tags
211
messages.append(openWarning).append(openCDATA);
212         
213         // append the fatal error message
214
appendErrorMessage(e);
215         
216         // close CDATA and warning tags
217
messages.append(closeCDATA).append(closeWarning);
218     }
219
220     /* (non-Javadoc)
221      * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
222      */

223     public void error(SAXParseException JavaDoc e) throws SAXException JavaDoc {
224         ++errorCount;
225
226         // open fatal error and CDATA tags
227
messages.append(openError).append(openCDATA);
228         
229         // append the error message
230
appendErrorMessage(e);
231         
232         // close CDATA and error tags
233
messages.append(closeCDATA).append(closeError);
234     }
235
236     /* (non-Javadoc)
237      * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
238      */

239     public void fatalError(SAXParseException JavaDoc e) throws SAXException JavaDoc {
240         ++fatalErrorCount;
241         
242         // open fatal error and CDATA tags
243
messages.append(openFatalError).append(openCDATA);
244         
245         // append the fatal error message
246
appendErrorMessage(e);
247         
248         // close CDATA and fatal error tags
249
messages.append(closeCDATA).append(closeFatalError);
250     }
251
252     /**
253      * Append the error message or stacktrace to the messages attribute.
254      *
255      * @param e
256      */

257     private void appendErrorMessage(SAXParseException JavaDoc e) {
258         if (includeStackTraces) {
259             StringWriter JavaDoc sw = new StringWriter JavaDoc();
260             e.printStackTrace(new PrintWriter JavaDoc(sw));
261             messages.append(sw.toString());
262         } else {
263             messages.append(e.getLocalizedMessage());
264         }
265     }
266     
267     /* (non-Javadoc)
268      * @see org.apache.servicemix.components.validation.MessageAwareErrorHandler#capturesMessages()
269      */

270     public boolean capturesMessages() {
271         return true;
272     }
273
274     /* (non-Javadoc)
275      * @see org.apache.servicemix.components.validation.MessageAwareErrorHandler#getMessagesAs(java.lang.Class)
276      */

277     public Object JavaDoc getMessagesAs(Class JavaDoc format) throws MessagingException {
278         if (format == DOMSource JavaDoc.class) {
279             return getDOMSource();
280         } else if (format == StringSource.class) {
281             return getStringSource();
282         } else if (format == String JavaDoc.class) {
283             return getMessagesWithRootElement();
284         }
285         throw new MessagingException("Unsupported message format: " + format.getName());
286     }
287
288     /* (non-Javadoc)
289      * @see org.apache.servicemix.components.validation.MessageAwareErrorHandler#supportsMessageFormat(java.lang.Class)
290      */

291     public boolean supportsMessageFormat(Class JavaDoc format) {
292         if (format == DOMSource JavaDoc.class) {
293             return true;
294         } else if (format == StringSource.class) {
295             return true;
296         } else if (format == String JavaDoc.class) {
297             return true;
298         }
299         return false;
300     }
301     
302     /**
303      * Return the messages encapsulated with the root element.
304      *
305      * @return
306      */

307     private String JavaDoc getMessagesWithRootElement() {
308         return new StringBuffer JavaDoc().append(openRootElement).append(messages).append(closeRootElement).toString();
309     }
310     
311     /**
312      * Get the error messages as a String Source.
313      *
314      * @return
315      */

316     private StringSource getStringSource() {
317         return new StringSource(getMessagesWithRootElement());
318     }
319     
320     /**
321      * Get the error messages as a DOMSource.
322      *
323      * @return
324      * @throws MessagingException
325      */

326     private DOMSource JavaDoc getDOMSource() throws MessagingException {
327         try {
328             return sourceTransformer.toDOMSource(getStringSource());
329         } catch (ParserConfigurationException JavaDoc e) {
330             throw new MessagingException("Failed to create DOMSource for Schema validation messages: " + e, e);
331         } catch (IOException JavaDoc e) {
332             throw new MessagingException("Failed to create DOMSource for Schema validation messages: " + e, e);
333         } catch (SAXException JavaDoc e) {
334             throw new MessagingException("Failed to create DOMSource for Schema validation messages: " + e, e);
335         } catch (TransformerException JavaDoc e) {
336             throw new MessagingException("Failed to create DOMSource for Schema validation messages: " + e, e);
337         }
338     }
339     
340 }
341
Popular Tags