KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > myfaces > util > DebugUtils


1 /*
2  * Copyright 2004 The Apache Software Foundation.
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 package org.apache.myfaces.util;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20
21 import javax.faces.FacesException;
22 import javax.faces.component.*;
23 import javax.faces.context.FacesContext;
24 import javax.faces.el.MethodBinding;
25 import javax.faces.el.ValueBinding;
26 import javax.faces.event.FacesListener;
27 import javax.faces.validator.Validator;
28 import java.beans.BeanInfo JavaDoc;
29 import java.beans.IntrospectionException JavaDoc;
30 import java.beans.Introspector JavaDoc;
31 import java.beans.PropertyDescriptor JavaDoc;
32 import java.io.ByteArrayOutputStream JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.io.PrintStream JavaDoc;
35 import java.util.HashSet JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.Map JavaDoc;
38
39
40 /**
41  * Utilities for logging.
42  *
43  * @author Manfred Geiler (latest modification by $Author: matze $)
44  * @version $Revision: 1.17 $ $Date: 2004/10/13 11:51:01 $
45  * $Log: DebugUtils.java,v $
46  * Revision 1.17 2004/10/13 11:51:01 matze
47  * renamed packages to org.apache
48  *
49  * Revision 1.16 2004/08/27 10:44:51 manolito
50  * ignore exception on property read
51  *
52  * Revision 1.15 2004/07/01 22:05:15 mwessendorf
53  * ASF switch
54  *
55  * Revision 1.14 2004/04/06 06:48:23 manolito
56  * IndexedPropertyDescriptor issue
57  *
58  * Revision 1.13 2004/04/05 09:10:34 manolito
59  * no get call for ignore attributes
60  *
61  */

62 public class DebugUtils
63 {
64     private static final Log log = LogFactory.getLog(DebugUtils.class);
65
66     //Attributes that should not be printed
67
private static final HashSet JavaDoc IGNORE_ATTRIBUTES;
68     static
69     {
70         IGNORE_ATTRIBUTES = new HashSet JavaDoc();
71         IGNORE_ATTRIBUTES.add("attributes");
72         IGNORE_ATTRIBUTES.add("children");
73         IGNORE_ATTRIBUTES.add("childCount");
74         IGNORE_ATTRIBUTES.add("class");
75         IGNORE_ATTRIBUTES.add("facets");
76         IGNORE_ATTRIBUTES.add("facetsAndChildren");
77         IGNORE_ATTRIBUTES.add("parent");
78         IGNORE_ATTRIBUTES.add("actionListeners");
79         IGNORE_ATTRIBUTES.add("valueChangeListeners");
80         IGNORE_ATTRIBUTES.add("validators");
81         IGNORE_ATTRIBUTES.add("rowData");
82         IGNORE_ATTRIBUTES.add("javax.faces.webapp.COMPONENT_IDS");
83         IGNORE_ATTRIBUTES.add("javax.faces.webapp.FACET_NAMES");
84         IGNORE_ATTRIBUTES.add("javax.faces.webapp.CURRENT_VIEW_ROOT");
85     }
86
87     private static final String JavaDoc JSF_COMPONENT_PACKAGE = "javax.faces.component.";
88     private static final String JavaDoc MYFACES_COMPONENT_PACKAGE = "org.apache.myfaces.component.";
89
90
91     private DebugUtils()
92     {
93         // hide from public access
94
}
95
96     public static void assertError(boolean condition, Log log_, String JavaDoc msg)
97             throws FacesException
98     {
99         if (!condition)
100         {
101             log_.error(msg);
102             throw new FacesException(msg);
103         }
104     }
105
106     public static void assertFatal(boolean condition, Log log_, String JavaDoc msg)
107         throws FacesException
108     {
109         if (!condition)
110         {
111             log_.fatal(msg);
112             throw new FacesException(msg);
113         }
114     }
115
116
117
118     public static void traceView(String JavaDoc additionalMsg)
119     {
120         if (log.isTraceEnabled())
121         {
122             FacesContext facesContext = FacesContext.getCurrentInstance();
123             if (facesContext == null)
124             {
125                 log.error("Cannot not print view to console (no FacesContext).");
126                 return;
127             }
128             UIViewRoot viewRoot = facesContext.getViewRoot();
129             if (viewRoot == null)
130             {
131                 log.error("Cannot not print view to console (no ViewRoot in FacesContext).");
132                 return;
133             }
134
135             traceView(additionalMsg, viewRoot);
136         }
137     }
138
139     /**
140      * Be careful, when using this version of traceView:
141      * Some component properties (e.g. getRenderer) assume, that there is a
142      * valid viewRoot set in the FacesContext!
143      * @param additionalMsg
144      * @param viewRoot
145      */

146     private static void traceView(String JavaDoc additionalMsg, UIViewRoot viewRoot)
147     {
148         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
149         PrintStream JavaDoc ps = new PrintStream JavaDoc(baos);
150         if (additionalMsg != null)
151         {
152             ps.println(additionalMsg);
153         }
154         ps.println("========================================");
155         printView(viewRoot, ps);
156         ps.println("========================================");
157         ps.close();
158         log.trace(baos.toString());
159     }
160
161     public static void printView(UIViewRoot uiViewRoot, PrintStream JavaDoc stream)
162     {
163         printComponent(uiViewRoot, stream, 0, true, null);
164     }
165
166     public static void printComponent(UIComponent comp, PrintStream JavaDoc stream)
167     {
168         printComponent(comp, stream, 0, false, null);
169     }
170
171     private static void printComponent(UIComponent comp,
172                                        PrintStream JavaDoc stream,
173                                        int indent,
174                                        boolean withChildrenAndFacets,
175                                        String JavaDoc facetName)
176     {
177         printIndent(stream, indent);
178         stream.print('<');
179
180         String JavaDoc compType = comp.getClass().getName();
181         if (compType.startsWith(JSF_COMPONENT_PACKAGE))
182         {
183             compType = compType.substring(JSF_COMPONENT_PACKAGE.length());
184         }
185         else if (compType.startsWith(MYFACES_COMPONENT_PACKAGE))
186         {
187             compType = compType.substring(MYFACES_COMPONENT_PACKAGE.length());
188         }
189         stream.print(compType);
190
191         printAttribute(stream, "id", comp.getId());
192
193         if (facetName != null)
194         {
195             printAttribute(stream, "facetName", facetName);
196         }
197
198         for (Iterator JavaDoc it = comp.getAttributes().entrySet().iterator(); it.hasNext(); )
199         {
200             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)it.next();
201             if (!"id".equals(entry.getKey()))
202             {
203                 printAttribute(stream, (String JavaDoc)entry.getKey(), entry.getValue());
204             }
205         }
206
207         //HACK: comp.getAttributes() only returns attributes, that are NOT backed
208
//by a corresponding component property. So, we must explicitly get the
209
//available properties by Introspection:
210
BeanInfo JavaDoc beanInfo;
211         try
212         {
213             beanInfo = Introspector.getBeanInfo(comp.getClass());
214         }
215         catch (IntrospectionException JavaDoc e)
216         {
217             throw new RuntimeException JavaDoc(e);
218         }
219         
220         PropertyDescriptor JavaDoc propDescriptors[] = beanInfo.getPropertyDescriptors();
221         for (int i = 0; i < propDescriptors.length; i++)
222         {
223             if (propDescriptors[i].getReadMethod() != null)
224             {
225                 String JavaDoc name = propDescriptors[i].getName();
226                 if (!"id".equals(name))
227                 {
228                     ValueBinding vb = comp.getValueBinding(name);
229                     if (vb != null)
230                     {
231                         printAttribute(stream, name, vb.getExpressionString());
232                     }
233                     else
234                     {
235                         if (name.equals("value") && comp instanceof ValueHolder)
236                         {
237                             //-> localValue
238
}
239                         else if (!IGNORE_ATTRIBUTES.contains(name))
240                         {
241                             try
242                             {
243                                 Object JavaDoc value = comp.getAttributes().get(name);
244                                 printAttribute(stream, name, value);
245                             }
246                             catch (Exception JavaDoc e)
247                             {
248                                 log.error(e);
249                                 printAttribute(stream, name, null);
250                             }
251                         }
252                     }
253                 }
254             }
255         }
256
257         boolean mustClose = true;
258         boolean nestedObjects = false;
259
260         if (comp instanceof UICommand)
261         {
262             FacesListener[] listeners = ((UICommand)comp).getActionListeners();
263             if (listeners != null && listeners.length > 0)
264             {
265                 nestedObjects = true;
266                 stream.println('>'); mustClose = false;
267                 for (int i = 0; i < listeners.length; i++)
268                 {
269                     FacesListener listener = listeners[i];
270                     printIndent(stream, indent + 1);
271                     stream.print('<');
272                     stream.print(listener.getClass().getName());
273                     stream.println("/>");
274                 }
275             }
276         }
277
278         if (comp instanceof UIInput)
279         {
280             FacesListener[] listeners = ((UIInput)comp).getValueChangeListeners();
281             if (listeners != null && listeners.length > 0)
282             {
283                 nestedObjects = true;
284                 stream.println('>'); mustClose = false;
285                 for (int i = 0; i < listeners.length; i++)
286                 {
287                     FacesListener listener = listeners[i];
288                     printIndent(stream, indent + 1);
289                     stream.print('<');
290                     stream.print(listener.getClass().getName());
291                     stream.println("/>");
292                 }
293             }
294
295             Validator[] validators = ((UIInput)comp).getValidators();
296             if (validators != null && validators.length > 0)
297             {
298                 nestedObjects = true;
299                 stream.println('>'); mustClose = false;
300                 for (int i = 0; i < validators.length; i++)
301                 {
302                     Validator validator = validators[i];
303                     printIndent(stream, indent + 1);
304                     stream.print('<');
305                     stream.print(validator.getClass().getName());
306                     stream.println("/>");
307                 }
308             }
309         }
310
311         if (withChildrenAndFacets)
312         {
313             int childCount = comp.getChildCount();
314             Map JavaDoc facetsMap = comp.getFacets();
315             if (childCount > 0 || !facetsMap.isEmpty())
316             {
317                 nestedObjects = true;
318                 if (mustClose)
319                 {
320                     stream.println('>');
321                     mustClose = false;
322                 }
323
324                 if (childCount > 0)
325                 {
326                     for (Iterator JavaDoc it = comp.getChildren().iterator(); it.hasNext(); )
327                     {
328                         UIComponent child = (UIComponent)it.next();
329                         printComponent(child, stream, indent + 1, true, null);
330                     }
331                 }
332
333                 for (Iterator JavaDoc it = facetsMap.entrySet().iterator(); it.hasNext(); )
334                 {
335                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc)it.next();
336                     printComponent((UIComponent)entry.getValue(),
337                                    stream, indent + 1, true,
338                                    (String JavaDoc)entry.getKey());
339                 }
340             }
341         }
342
343         if (nestedObjects)
344         {
345             if (mustClose)
346             {
347                 stream.println("/>");
348             }
349             else
350             {
351                 printIndent(stream, indent);
352                 stream.print("</");
353                 stream.print(compType);
354                 stream.println('>');
355             }
356         }
357         else
358         {
359             stream.println("/>");
360         }
361     }
362
363     private static void printAttribute(PrintStream JavaDoc stream,
364                                        String JavaDoc name,
365                                        Object JavaDoc value)
366     {
367         if (IGNORE_ATTRIBUTES.contains(name)) return;
368         if (name.startsWith("javax.faces.webapp.UIComponentTag."))
369         {
370             name = name.substring("javax.faces.webapp.UIComponentTag.".length());
371         }
372         stream.print(' ');
373         stream.print(name.toString());
374         stream.print("=\"");
375         if (value != null)
376         {
377             if (value instanceof UIComponent)
378             {
379                 stream.print("[id:");
380                 stream.print(((UIComponent)value).getId());
381                 stream.print(']');
382             }
383             else if (value instanceof MethodBinding)
384             {
385                 ((MethodBinding)value).getExpressionString();
386             }
387             else
388             {
389                 stream.print(value.toString());
390             }
391         }
392         else
393         {
394             stream.print("NULL");
395         }
396         stream.print('"');
397     }
398
399
400     private static void printIndent(PrintStream JavaDoc stream, int depth)
401     {
402         for (int i = 0; i < depth; i++)
403         {
404             stream.print(" ");
405         }
406     }
407
408     public static String JavaDoc componentAsString(UIComponent comp)
409     {
410         try
411         {
412             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
413             printComponent(comp, new PrintStream JavaDoc(baos));
414             baos.close();
415             return baos.toString();
416         }
417         catch (IOException JavaDoc e)
418         {
419             throw new RuntimeException JavaDoc(e);
420         }
421     }
422 }
423
Popular Tags