KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > example > antbook > xdoclet > MethodExTagsHandler


1 package org.example.antbook.xdoclet;
2
3 import java.sql.Timestamp JavaDoc;
4 import java.text.SimpleDateFormat JavaDoc;
5 import java.util.ArrayList JavaDoc;
6 import java.util.Collection JavaDoc;
7 import java.util.Date JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.List JavaDoc;
10 import java.util.Locale JavaDoc;
11 import java.util.MissingResourceException JavaDoc;
12 import java.util.Properties JavaDoc;
13 import java.util.ResourceBundle JavaDoc;
14
15 import xdoclet.XDocletException;
16 import xdoclet.tagshandler.MethodTagsHandler;
17 import xdoclet.util.TypeConversionUtil;
18 import xjavadoc.Type;
19 import xjavadoc.XClass;
20 import xjavadoc.XMember;
21 import xjavadoc.XMethod;
22
23 /**
24  * This class is an extension to xdoclet.tagshandler.MethodTagsHandler with
25  * extra features designed for appgen.
26  *
27  * @author hzhang(mb4henry@yahoo.com.au)
28  * @author Matt Raible
29  * @author David Carter
30  *
31  */

32 public class MethodExTagsHandler extends MethodTagsHandler {
33
34     XClass currentClass = getCurrentClass();
35     private static String JavaDoc datePattern = "yyyy-MM-dd";
36     private static String JavaDoc uiDatePattern = getDatePattern();
37     private static final List JavaDoc numericTypes = new ArrayList JavaDoc();
38     private String JavaDoc rootClassName = "";
39     private String JavaDoc curprefix = "";
40
41     static {
42         numericTypes.add("java.lang.Integer");
43         numericTypes.add("int");
44         numericTypes.add("java.lang.Float");
45         numericTypes.add("float");
46         numericTypes.add("java.lang.Long");
47         numericTypes.add("long");
48         numericTypes.add("java.lang.Double");
49         numericTypes.add("double");
50         numericTypes.add("java.lang.Short");
51         numericTypes.add("short");
52         numericTypes.add("java.lang.Byte");
53         numericTypes.add("byte");
54     }
55
56     /**
57      * Iterates over all methods of current class and evaluates the body of the
58      * tag for each method. <br>
59      * The reason to override this method is to add nested form support when
60      * iterating over all properties.
61      *
62      * @see xdoclet.tagshandler.MethodTagsHandler#forAllMethods(java.lang.String,
63      * java.util.Properties)
64      *
65      * @param template
66      * @param attributes
67      *
68      * @throws XDocletException
69      */

70     public void forAllMethods(String JavaDoc template, Properties JavaDoc attributes) throws XDocletException {
71         XClass currentClass = getCurrentClass();
72
73         if (currentClass == null) {
74             throw new XDocletException("currentClass == null!!!");
75         }
76
77         rootClassName = classNameLower();
78         forAllMembersEx(currentClass, template, attributes, FOR_METHOD, "");
79     }
80
81     /**
82      * Method to print out an ActionForm, setter and parameter value
83      *
84      * @return
85      * @throws XDocletException
86      */

87     public String JavaDoc formSetterWithValue() throws XDocletException {
88         XMethod method = super.getCurrentMethod();
89         XMethod setter = method.getMutator();
90
91         String JavaDoc value = "\"" + randomValueForDbUnit() + "\"";
92         if (setter.getPropertyType().getType().isA("java.util.Date")) {
93             value = "\"" + getDate(new Date JavaDoc(), uiDatePattern) + "\"";
94         }
95
96         rootClassName = classNameLower();
97         return rootClassName + "Form." + curprefix + setter.getName() + "(" + value + ");";
98     }
99
100     /**
101      * Method to print out a class, setter and a parameter value
102      *
103      * @return
104      * @throws XDocletException
105      */

106     public String JavaDoc setterWithValue() throws XDocletException {
107         XMethod method = super.getCurrentMethod();
108         XMethod setter = method.getMutator();
109
110         return classNameLower() + "." + curprefix + setter.getName() + "(" + randomValueForSetter() + ");";
111     }
112
113     /**
114      * Method to print out a random value for use in setting WebTest parameters
115      *
116      * @return
117      * @throws XDocletException
118      */

119     public String JavaDoc randomValueForWebTest() throws XDocletException {
120         XMethod method = super.getCurrentMethod();
121         XMethod setter = method.getMutator();
122
123         String JavaDoc value = randomValueForDbUnit();
124         if (setter.getPropertyType().getType().isA("java.util.Date")) {
125             value = getDate(new Date JavaDoc(), uiDatePattern);
126         }
127
128         return value;
129     }
130
131     /**
132      * A convenient way to get information of an id field. You can get the
133      * property name, property type, setter name, getter name. When using this
134      * method, you can pass in a parameter call "getType". And its value can be
135      * one of
136      * <ul>
137      * <li>propertyName</li>
138      * <li>propertyType</li>
139      * <li>getterName</li>
140      * <li>setterName</li>
141      * </ul>
142      * default will return property name.
143      *
144      * @param attributes
145      * @return required information related to id field in the model class
146      * @throws XDocletException
147      */

148     public String JavaDoc idField(Properties JavaDoc attributes) throws XDocletException {
149         Collection JavaDoc members = null;
150
151         members = currentClass.getMethods(true);
152
153         for (Iterator JavaDoc j = members.iterator(); j.hasNext(); ) {
154             XMember member = (XMember)j.next();
155             setCurrentMethod((XMethod)member);
156             XMethod getter = (XMethod)member;
157
158             if (super.isGetterMethod(getter)) {
159                 Properties JavaDoc pro = new Properties JavaDoc();
160                 pro.setProperty("tagName", "hibernate.id");
161
162                 if (super.hasTag(pro, FOR_METHOD)) {
163                     break;
164                 }
165
166                 setCurrentClass(member.getContainingClass());
167             }
168         }
169         return methodInfo(attributes);
170     }
171
172     /**
173      * Method methodInfo
174      * @param attributes
175      * @return
176      * @throws XDocletException
177      */

178     public String JavaDoc methodInfo(Properties JavaDoc attributes) throws XDocletException {
179         String JavaDoc type = attributes.getProperty("getType");
180         XMethod getter = super.getCurrentMethod();
181         String JavaDoc result = "";
182
183         if ("propertyName".equals(type)) {
184             result = getter.getPropertyName();
185         } else if ("getterName".equals(type)) {
186             result = getter.getName();
187         } else if ("setterName".equals(type)) {
188             result = getter.getMutator().getName();
189         } else if ("propertyType".equals(type)) {
190             result = getter.getPropertyType().getType().getTransformedName();
191         } else if ("columnName".equals(type)) {
192             result = columnName(attributes);
193         } else if ("javaType".equals(type)) {
194             result = getter.getPropertyType().getType().getQualifiedName();
195         } else if ("jdbcType".equals(type)) {
196             result = jdbcType(attributes);
197         } else {
198             result = getter.getPropertyName();
199         }
200
201         return result;
202     }
203
204     /**
205      * Method columnName
206      * @param attributes
207      * @return
208      *
209      * @throws XDocletException
210      */

211     public String JavaDoc columnName(Properties JavaDoc attributes) throws XDocletException {
212         Properties JavaDoc prop = new Properties JavaDoc();
213
214         prop.setProperty("tagName", "hibernate.property");
215         prop.setProperty("paramName", "column");
216
217         String JavaDoc column = methodTagValue(prop);
218
219         if ((column == null) || (column.trim().length() < 1)) {
220             prop.setProperty("tagName", "hibernate.id");
221             column = methodTagValue(prop);
222         }
223
224         return column;
225     }
226
227     /**
228      * Method jdbcType
229      * @param props
230      * @return
231      * @throws XDocletException
232      */

233     public String JavaDoc jdbcType(Properties JavaDoc props) throws XDocletException {
234         String JavaDoc jdbcType = "VARCHAR";
235
236         if (super.getCurrentMethod() != null) {
237             String JavaDoc javaType = super.getCurrentMethod().getPropertyType().getType().getQualifiedName().toLowerCase();
238
239             if (javaType.indexOf("date") > 0) {
240                 jdbcType = "TIMESTAMP";
241             } else if (javaType.indexOf("timestamp") > 0) {
242                 jdbcType = "TIMESTAMP";
243             } else if ((javaType.indexOf("int") > 0) || (javaType.indexOf("long") > 0) || (javaType.indexOf("short") > 0)) {
244                 jdbcType = "INTEGER";
245             } else if (javaType.indexOf("double") > 0) {
246                 jdbcType = "DOUBLE";
247             } else if (javaType.indexOf("float") > 0) {
248                 jdbcType = "FLOAT";
249             }
250         }
251
252         return jdbcType;
253     }
254
255     /**
256      * @see xdoclet.tagshandler.MethodTagsHandler#forAllMembers
257      * @param currentClass
258      * @param template
259      * @param attributes
260      * @param forType
261      * @param prefix
262      * @throws XDocletException
263      */

264     protected void forAllMembersEx(XClass currentClass, String JavaDoc template, Properties JavaDoc attributes, int forType, String JavaDoc prefix)
265     throws XDocletException {
266         boolean superclasses = TypeConversionUtil.stringToBoolean(attributes.getProperty("superclasses"), false);
267         boolean sort = TypeConversionUtil.stringToBoolean(attributes.getProperty("sort"), true);
268         boolean generateChildren = TypeConversionUtil.stringToBoolean(attributes.getProperty("generateChildren"), true);
269         
270         Collection JavaDoc members = null;
271
272         switch (forType) {
273             case FOR_METHOD:
274                 members = currentClass.getMethods(superclasses);
275                 break;
276
277             default:
278                 throw new XDocletException("Bad type: " + forType);
279         }
280
281         if (sort) {
282             // sort fields, but we should make a copy first, because members is
283
// not a new copy, it's shared by all
284
List JavaDoc sortedMembers = new ArrayList JavaDoc(members);
285
286             members = sortedMembers;
287         }
288
289         for (Iterator JavaDoc j = members.iterator(); j.hasNext();) {
290             XMember member = (XMember) j.next();
291
292             switch (forType) {
293                 case FOR_METHOD:
294                     setCurrentMethod((XMethod) member);
295                     break;
296
297                 default:
298                     throw new XDocletException("Bad type: " + forType);
299             }
300
301             XMethod getter = (XMethod) member;
302
303             if (super.isGetterMethod(getter)) {
304                 Properties JavaDoc pro = new Properties JavaDoc();
305
306                 // iterate through sub-components only
307
pro.setProperty("tagName", "hibernate.component");
308
309                 if (super.hasTag(pro, FOR_METHOD) && generateChildren) {
310                     Type type = getter.getReturnType();
311                     String JavaDoc temp = prefix + ("get" + type.getType().getName() + "Form().");
312                     forAllMembersEx(type.getType(), template, attributes, forType, temp);
313                 }
314
315                 setCurrentClass(member.getContainingClass());
316                 curprefix = prefix;
317                 generate(template);
318             }
319         }
320
321         setCurrentClass(currentClass);
322     }
323
324     /**
325      * Method className
326      *
327      * @return
328      */

329     public String JavaDoc className() {
330         return currentClass.getName();
331     }
332
333     /**
334      * Method classNameLower
335      * @return
336      */

337     public String JavaDoc classNameLower() {
338         String JavaDoc name = currentClass.getName();
339         char c = name.charAt(0);
340
341         c = Character.toLowerCase(c);
342
343         return c + name.substring(1);
344     }
345
346     /**
347      * Generates a random value for a field. Return "0" for boolean type. used
348      * to generate random values for sample-data.xml
349      *
350      * @return a random value
351      * @throws XDocletException
352      */

353     public String JavaDoc randomValueForDbUnit() throws XDocletException {
354         Properties JavaDoc pros = new Properties JavaDoc();
355         pros.put("type", "content");
356
357         String JavaDoc mtype = super.methodType(pros);
358
359         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
360
361         if ("java.lang.Integer".equals(mtype) || "int".equals(mtype)) {
362             result.append((int) ((Math.random() * Integer.MAX_VALUE)) );
363         } else if ("java.lang.Float".equals(mtype) || "float".equals(mtype)) {
364             result.append((float) ((Math.random() * Float.MAX_VALUE)));
365         } else if ("java.lang.Long".equals(mtype) || "long".equals(mtype)) {
366             result.append((long) ((Math.random() * Long.MAX_VALUE)));
367         } else if ("java.lang.Double".equals(mtype) || "double".equals(mtype)) {
368             result.append((double) ((Math.random() * Double.MAX_VALUE)));
369         } else if ("java.lang.Short".equals(mtype) || "short".equals(mtype)) {
370             result.append((short) ((Math.random() * Short.MAX_VALUE)));
371         } else if ("java.lang.Byte".equals(mtype) || "byte".equals(mtype)) {
372             result.append((byte) ((Math.random() * Byte.MAX_VALUE)));
373         } else if ("java.lang.Boolean".equals(mtype) || "boolean".equals(mtype)) {
374             result.append("N");
375         } else if ("java.util.Date".equals(mtype) || "java.sql.Date".equals(mtype)) {
376             result.append(getDate(new Date JavaDoc()));
377         } else if ("java.sql.Timestamp".equals(mtype)) {
378             result.append(new Timestamp JavaDoc(new Date JavaDoc().getTime()).toString());
379         } else if ("email".equalsIgnoreCase(super.propertyName())) {
380             result.append(super.propertyName() + (int) ((Math.random() * Integer.MAX_VALUE)) + "@dev.java.net");
381         } else { // default to String for everything else
382
String JavaDoc stringWithQuotes = generateStringValue();
383             result.append(stringWithQuotes.substring(1, stringWithQuotes.length()-1));
384         }
385
386         //System.out.println("propertyType: " + mtype + " | dbUnit value: " + result.toString());
387
return result.toString();
388     }
389
390     /**
391      * Generates a random value for a field. Return "true" for boolean type.
392      * Returned values are used in junit tests to create new values of the
393      * appropriate type for testing.
394      *
395      * @return a random value
396      * @throws XDocletException
397      */

398     public String JavaDoc randomValueForSetter() throws XDocletException {
399         Properties JavaDoc pros = new Properties JavaDoc();
400         pros.put("type", "content");
401
402         String JavaDoc mtype = super.methodType(pros);
403
404         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
405
406         if ("java.lang.Integer".equals(mtype)) {
407             result.append("new Integer(" + (int) ((Math.random() * Integer.MAX_VALUE)) + ")");
408         } else if ("int".equals(mtype)) {
409             result.append("(int) " + (int) ((Math.random() * Integer.MAX_VALUE)));
410         } else if ("java.lang.Float".equals(mtype) ) {
411             result.append("new Float(" + (float) ((Math.random() * Float.MAX_VALUE)) + ")");
412         } else if ("float".equals(mtype)) {
413             result.append("(float) " + (float) ((Math.random() * Float.MAX_VALUE)));
414         } else if ("java.lang.Long".equals(mtype)) {
415             // not sure why, but Long.MAX_VALUE results in too large a number
416
result.append("new Long(" + (long) ((Math.random() * Integer.MAX_VALUE)) + ")");
417         } else if ("long".equals(mtype)) {
418             // not sure why, but Long.MAX_VALUE results in too large a number
419
result.append((long) ((Math.random() * Integer.MAX_VALUE)));
420         } else if ("java.lang.Double".equals(mtype)) {
421             result.append("new Double(" + (double) ((Math.random() * Double.MAX_VALUE)) + ")");
422         } else if ("double".equals(mtype)) {
423             result.append((double) ((Math.random() * Double.MAX_VALUE)));
424         } else if ("java.lang.Short".equals(mtype)) {
425             result.append("new Short(\"" + (short) ((Math.random() * Short.MAX_VALUE)) + "\")");
426         } else if ("short".equals(mtype)) {
427             result.append("(short)" + (short) ((Math.random() * Short.MAX_VALUE)));
428         } else if ("java.lang.Byte".equals(mtype)) {
429             result.append("new Byte(\"" + (byte) ((Math.random() * Byte.MAX_VALUE)) + "\")");
430         } else if ("byte".equals(mtype)) {
431             result.append("(byte) " + (byte) ((Math.random() * Byte.MAX_VALUE)));
432         } else if ("java.lang.Boolean".equals(mtype)) {
433             result.append("new Boolean(\"false\")");
434         } else if ("boolean".equals(mtype)) {
435             result.append("false");
436         } else if ("java.util.Date".equals(mtype)) {
437             result.append("new java.util.Date()");
438         } else if ("java.sql.Date".equals(mtype)) {
439             result.append("new java.sql.Date()");
440         } else if ("java.sql.Timestamp".equals(mtype)) {
441             result.append("java.sql.Timestamp.valueOf(\"" + new Timestamp JavaDoc(new Date JavaDoc().getTime()).toString() + "\")");
442         } else if ("email".equalsIgnoreCase(super.propertyName())) {
443             result.append("\"" + super.propertyName() + (int) ((Math.random() * Integer.MAX_VALUE)) +
444                 "@dev.java.net\"");
445         } else { // default to String for everything else
446
result.append(generateStringValue());
447         }
448
449         //System.out.println("propertyType: " + mtype + " | setter value: " + result.toString());
450
return result.toString();
451     }
452
453
454     private String JavaDoc generateStringValue() throws XDocletException {
455
456         int maxLen = getHibernateLength();
457         if (maxLen == 0) { maxLen = 25; }
458
459         StringBuffer JavaDoc result = new StringBuffer JavaDoc("\"");
460
461         for (int i = 0; (i < maxLen); i++) {
462             int j = 0;
463             if (i % 2 == 0) {
464                 j = (int) ((Math.random() * 26) + 65);
465             } else {
466                 j = (int) ((Math.random() * 26) + 97);
467             }
468             result.append(new Character JavaDoc((char)j).toString());
469         }
470
471         result.append("\"");
472
473         return result.toString();
474     }
475
476     private int getHibernateLength() throws XDocletException {
477
478         Properties JavaDoc props = new Properties JavaDoc();
479
480         props.setProperty("tagName", "hibernate.property");
481         props.setProperty("paramName", "length");
482
483         int length = 0;
484
485         if (super.hasTag(props, FOR_METHOD)) {
486             String JavaDoc tagVal = super.getTagValue(props, FOR_METHOD);
487             //System.out.println("property has hibernate.property length= " + tagVal);
488
length = Integer.valueOf(tagVal).intValue();
489         }
490         return length;
491     }
492
493     /**
494      * copy from org.appfuse.util.DateUtil
495      *
496      * @param aDate
497      * @return
498      */

499     private static final String JavaDoc getDate(Date JavaDoc aDate) {
500         return getDate(aDate, datePattern);
501     }
502
503     private static final String JavaDoc getDate(Date JavaDoc aDate, String JavaDoc pattern) {
504         SimpleDateFormat JavaDoc df = null;
505         String JavaDoc returnValue = "";
506
507         if (aDate != null) {
508             df = new SimpleDateFormat JavaDoc(pattern);
509             returnValue = df.format(aDate);
510         }
511
512         return returnValue;
513     }
514     /**
515      * Return default datePattern (MM/dd/yyyy)
516      * @return a string representing the date pattern on the UI
517      */

518     public static synchronized String JavaDoc getDatePattern() {
519         String JavaDoc result;
520         try {
521             result = ResourceBundle.getBundle("ApplicationResources", Locale.getDefault())
522                 .getString("date.format");
523         } catch (MissingResourceException JavaDoc mse) {
524             result = "MM/dd/yyyy";
525         }
526         return result;
527     }
528
529 }
530
Popular Tags