KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > diagnostics > ObjectAnalyzer


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 /**
25  * WBN -- generic mechanism for simulating toString() and equals()
26  * for any class
27  */

28
29 package com.sun.enterprise.util.diagnostics;
30
31 import java.lang.reflect.*;
32 import java.util.Vector JavaDoc;
33 import com.sun.enterprise.util.diagnostics.Reporter;
34 import com.sun.enterprise.util.StringUtils;
35
36 public class ObjectAnalyzer
37 {
38     /**
39      * @param className
40      * @return */

41     public static String JavaDoc getMethods(String JavaDoc className)
42     {
43         try
44         {
45             Class JavaDoc clazz = Class.forName(className);
46             return getMethods(clazz, false);
47         }
48         catch(Exception JavaDoc e)
49         {
50             return "Error loading class: " + e.getMessage();//NOI18N
51
}
52     }
53
54     ////////////////////////////////////////////////////////////////////////////
55

56     /**
57      * @param obj
58      * @return */

59     public static String JavaDoc getMethods(Object JavaDoc obj)
60     {
61         return getMethods(obj, false);
62     }
63
64     ////////////////////////////////////////////////////////////////////////////
65

66     /**
67      * @param obj
68      * @param settersOnly
69      * @return */

70     public static String JavaDoc getMethods(Object JavaDoc obj, boolean settersOnly)
71     {
72         try
73         {
74             Class JavaDoc clazz = safeGetClass(obj);
75             return getMethods(clazz, settersOnly);
76         }
77         catch(Exception JavaDoc e)
78         {
79             return e.getMessage();
80         }
81     }
82
83     ////////////////////////////////////////////////////////////////////////////
84

85     /**
86      * @param clazz
87      * @param settersOnly
88      * @return */

89     public static String JavaDoc getMethods(Class JavaDoc clazz, boolean settersOnly)
90     {
91         String JavaDoc s = new String JavaDoc();
92
93         Method[] methods = clazz.getMethods();
94
95         for(int i = 0; i < methods.length; i++)
96         {
97             Method m = methods[i];
98             boolean isSetter = m.getName().startsWith("set");//NOI18N
99

100             if(settersOnly && isSetter == false)
101                 continue;
102             
103             s = s + m.toString() + '\n';
104         }
105         return s;
106     }
107
108     ////////////////////////////////////////////////////////////////////////////
109

110     /**
111      * @param obj
112      * @return */

113     public static String JavaDoc getSetters(Object JavaDoc obj)
114     {
115         return getMethods(obj, true);
116     }
117
118     ////////////////////////////////////////////////////////////////////////////
119

120     /**
121      * @param clazz
122      * @return */

123     public static String JavaDoc getSetters(Class JavaDoc clazz)
124     {
125         return getMethods(clazz, true);
126     }
127
128     ////////////////////////////////////////////////////////////////////////////
129

130     /**
131      * @param obj
132      * @return */

133     public static String JavaDoc toString(Object JavaDoc obj)
134     {
135         return toString(obj, false);
136     }
137
138     ////////////////////////////////////////////////////////////////////////////
139

140     /**
141      * @param obj
142      * @return */

143     public static String JavaDoc toStringWithSuper(Object JavaDoc obj)
144     {
145         return toString(obj, true);
146     }
147
148     ////////////////////////////////////////////////////////////////////////////
149

150     /**
151      * @param a
152      * @param b
153      * @return */

154     public static boolean equals(Object JavaDoc a, Object JavaDoc b)
155     {
156         Class JavaDoc cl = a.getClass();
157
158         if (!cl.equals(b.getClass()))
159             return false;
160         
161         Field[] fields = cl.getDeclaredFields();
162         setAccessible(fields);
163         
164         for (int i = 0; i < fields.length; i++)
165         {
166             Field f = fields[i];
167             try
168             {
169                 if (!f.get(a).equals(f.get(b)))
170                     return false;
171             }
172             catch(IllegalAccessException JavaDoc e)
173             {
174                 return false;
175             }
176         }
177         
178         return true;
179     }
180
181     ////////////////////////////////////////////////////////////////////////////
182

183     public static void useShortClassNames()
184     {
185         useShortClassNames_ = true;
186     }
187
188     ////////////////////////////////////////////////////////////////////////////
189

190     public static void useLongClassNames()
191     {
192         useShortClassNames_ = false;
193     }
194
195     ////////////////////////////////////////////////////////////////////////////
196

197     private static String JavaDoc toString(Object JavaDoc obj, boolean doSuperClasses)
198     {
199         try
200         {
201             return getFieldInfo(obj, doSuperClasses).toString();
202         }
203         catch(ObjectAnalyzerException e)
204         {
205             return e.getMessage();
206         }
207     }
208     
209     ////////////////////////////////////////////////////////////////////////////
210

211     private static Class JavaDoc safeGetClass(Object JavaDoc obj) throws ObjectAnalyzerException
212     {
213         if(obj == null)
214             throw new ObjectAnalyzerException(fatal + "null Object parameter");//NOI18N
215

216         if(! (obj instanceof Object JavaDoc))
217             throw new ObjectAnalyzerException(fatal + "Object parameter is not really a java.lang.Object");//NOI18N
218

219         Class JavaDoc cl = obj.getClass();
220
221         if(cl == null)
222             throw new ObjectAnalyzerException(fatal + "getClass() on parameter Object returned null");//NOI18N
223

224         return cl;
225     }
226     
227     ////////////////////////////////////////////////////////////////////////////
228

229     private static Class JavaDoc safeGetSuperclass(Class JavaDoc cl) throws ObjectAnalyzerException
230     {
231         Class JavaDoc sc = cl.getSuperclass();
232
233         if(sc == null)
234             throw new ObjectAnalyzerException("getSuperclass() on parameter Object returned null");//NOI18N
235

236         return sc;
237     }
238     
239     ////////////////////////////////////////////////////////////////////////////
240

241     private static FieldInfoVector getFieldInfo(Object JavaDoc obj, boolean doSuperClasses) throws ObjectAnalyzerException
242     {
243         FieldInfoVector fiv = new FieldInfoVector();
244         Class JavaDoc cl = safeGetClass(obj);
245
246         if(doSuperClasses == false)
247         {
248             getFieldInfo(cl, obj, fiv);
249             return fiv;
250         }
251
252         for(Class JavaDoc theClass = cl; theClass != null && !theClass.equals(Object JavaDoc.class); theClass = safeGetSuperclass(theClass))
253             getFieldInfo(theClass, obj, fiv);
254
255         return fiv;
256     }
257     
258     
259     ////////////////////////////////////////////////////////////////////////////
260

261     private static void getFieldInfo(Class JavaDoc cl, Object JavaDoc obj, FieldInfoVector fiv) throws ObjectAnalyzerException
262     {
263         Field[] fields = null;
264
265         try
266         {
267             fields = cl.getDeclaredFields();
268         }
269         catch(SecurityException JavaDoc e)
270         {
271             throw new ObjectAnalyzerException("got a SecurityException when calling getDeclaredFields() on " + cl.getName());//NOI18N
272
}
273
274         if(fields == null)
275             throw new ObjectAnalyzerException("calling getDeclaredFields() on " + cl.getName() + " returned null");//NOI18N
276

277         setAccessible(fields);
278
279         for(int i = 0; i < fields.length; i++)
280         {
281             Field f = fields[i];
282             String JavaDoc sval;
283             String JavaDoc modifiers = Modifier.toString(f.getModifiers());
284             String JavaDoc className = cl.getName();
285
286             if(useShortClassNames_)
287                 className = StringUtils.toShortClassName(className);
288
289             if(modifiers.length() <= 0)
290                 modifiers = "(package)";//NOI18N
291

292             try
293             {
294                 Object JavaDoc val = f.get(obj);
295                 
296                 if(val == null)
297                     sval = "<null>";//NOI18N
298
else
299                     sval = val.toString();
300             }
301             catch (IllegalAccessException JavaDoc e)
302             {
303                 sval = "<IllegalAccessException>";//NOI18N
304
}
305             
306             fiv.addElement(new FieldInfo(className, f, sval, modifiers));
307         }
308     }
309     
310     ////////////////////////////////////////////////////////////////////////////
311

312     private static void setAccessible(Field[] fields)
313     {
314         if(setAccessibleMethod == null)
315             return; // Must be pre JDK 1.2.x
316

317         try
318         {
319             Boolean JavaDoc b = new Boolean JavaDoc(true);
320             setAccessibleMethod.invoke(null, new Object JavaDoc[] { fields, b } );
321         }
322         catch(Exception JavaDoc e)
323         {
324             Reporter.warn("Got an exception invoking setAccessible: " + e);//NOI18N
325
}
326     }
327
328     ////////////////////////////////////////////////////////////////////////////
329

330     private static void setupSetAccessibleMethod()
331     {
332         // whoa! what's this reflection crap doing here?
333
// AccessibleObject is a JDK 1.2 class that lets you peek at
334
// private variable values. Since we need to support JDK 1.1
335
// for the VCafe plug-in -- it is now called via 100% reflection
336
// techniques...
337

338         setAccessibleMethod = null;
339
340         Class JavaDoc AO;
341
342         try
343         {
344             AO = Class.forName("java.lang.reflect.AccessibleObject");//NOI18N
345
}
346         catch(ClassNotFoundException JavaDoc e)
347         {
348             Reporter.info("Can't find java.lang.reflect.AccessibleObject -- thus I can't show any private or protected variable values. This must be pre JDK 1.2.x");//NOI18N
349
return;
350         }
351
352         Method[] methods = AO.getDeclaredMethods();
353
354         for(int i = 0; i < methods.length; i++)
355         {
356             Method m = methods[i];
357
358             if(m.getName().equals("setAccessible") && m.getParameterTypes().length == 2)//NOI18N
359
{
360                 Reporter.verbose("Found setAccessible: " + m);//NOI18N
361
setAccessibleMethod = m;
362                 break;
363             }
364         }
365     }
366     
367     
368     ////////////////////////////////////////////////////////////////////////////
369

370     private static final String JavaDoc fatal = "Fatal Error in ObjectAnalyzer.toString(): ";//NOI18N
371
private static boolean useShortClassNames_ = true;
372     private static Method setAccessibleMethod;
373
374     static
375     {
376         setupSetAccessibleMethod();
377     }
378     
379     ////////////////////////////////////////////////////////////////////////////
380

381     /**
382      * @param args */

383     public static void main(String JavaDoc[] args)
384     {
385         String JavaDoc s = new String JavaDoc("Hello!");//NOI18N
386

387         System.out.println("Regular: \n" + toString(s) + "\n\n");//NOI18N
388
System.out.println("Super: \n" + toStringWithSuper(s) + "\n\n");//NOI18N
389
}
390       
391 }
392
393 ////////////////////////////////////////////////////////////////////////////
394
////////////////////////////////////////////////////////////////////////////
395

396 class ObjectAnalyzerException extends Exception JavaDoc
397 {
398     ObjectAnalyzerException(String JavaDoc s)
399     {
400         super(s);
401     }
402
403 }
404     
405 ////////////////////////////////////////////////////////////////////////////
406
////////////////////////////////////////////////////////////////////////////
407

408 class FieldInfo
409 {
410     Field field;
411     String JavaDoc value;
412     //Class clazz;
413
String JavaDoc className;
414     String JavaDoc modifiers;
415
416     FieldInfo(String JavaDoc c, Field f, String JavaDoc v, String JavaDoc m)
417     {
418         className = c;
419         field = f;
420         value = v;
421         modifiers = m;
422     }
423 }
424     
425 ////////////////////////////////////////////////////////////////////////////
426
////////////////////////////////////////////////////////////////////////////
427

428 class FieldInfoVector // { extends Vector
429
{
430     Vector JavaDoc v = null;
431     
432     FieldInfoVector()
433     {
434         v = new Vector JavaDoc();
435     }
436     
437     ////////////////////////////////////////////////////////////////////////////
438

439     /**
440      * @param o */

441     public void addElement(Object JavaDoc o) {
442         v.addElement(o);
443     }
444     
445     ////////////////////////////////////////////////////////////////////////////
446

447     /**
448      * @return */

449     public String JavaDoc toString()
450     {
451         int veclen = v.size();
452         StringBuffer JavaDoc s = new StringBuffer JavaDoc();
453
454         setLongestNames();
455
456         //s.append("classNameLength: " + classNameLength + "fieldNameLength: " + fieldNameLength + "modifiersLength: " + modifiersLength + "\n\n");//NOI18N
457

458         s.append(StringUtils.padRight("Class", classNameLength));//NOI18N
459
s.append(StringUtils.padRight("Modifiers", modifiersLength));//NOI18N
460
s.append(StringUtils.padRight("Field", fieldNameLength));//NOI18N
461
s.append("Value");//NOI18N
462
s.append("\n\n");//NOI18N
463

464         for(int i = 0; i < veclen; i++)
465         {
466             FieldInfo fi = fetch(i);
467     
468             s.append(StringUtils.padRight(fi.className, classNameLength));
469             s.append(StringUtils.padRight(fi.modifiers, modifiersLength));
470             s.append(StringUtils.padRight(fi.field.getName(), fieldNameLength));
471             s.append(fi.value);
472             s.append('\n');
473         }
474
475         return s.toString();
476     }
477
478     ////////////////////////////////////////////////////////////////////////////
479

480     private FieldInfo fetch(int i)
481     {
482         return (FieldInfo)v.elementAt(i);
483     }
484     
485     ////////////////////////////////////////////////////////////////////////////
486

487     private void setLongestNames()
488     {
489         int veclen = v.size();
490
491         classNameLength = 5;
492         fieldNameLength = 5;
493         modifiersLength = 5;
494
495         for(int i = 0; i < veclen; i++)
496         {
497             FieldInfo fi = fetch(i);
498
499             int clen = fi.className.length();
500             int flen = fi.field.getName().length();
501             int mlen = fi.modifiers.length();
502             if(clen > classNameLength) classNameLength = clen;
503             if(flen > fieldNameLength) fieldNameLength = flen;
504             if(mlen > modifiersLength) modifiersLength = mlen;
505         }
506
507         classNameLength += 2;
508         fieldNameLength += 2;
509         modifiersLength += 2;
510     }
511
512     ////////////////////////////////////////////////////////////////////////////
513

514     private int classNameLength = 0;
515     private int fieldNameLength = 0;
516     private int modifiersLength = 0;
517 }
518
Popular Tags