KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > schema2beans > JavaBeansUtil


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.schema2beans;
21
22 import java.io.*;
23 import java.beans.*;
24 import java.lang.reflect.*;
25 import java.util.*;
26 import java.text.*;
27 import org.w3c.dom.*;
28
29 /**
30  * @author Cliff Draper
31  *
32  * This is a utility class with several static methods for working
33  * with generic java beans. There are methods here for writing a java
34  * bean out {link writeBeanProperty}, for reading a java bean
35  * from XML {link readBean}, and for copying one java bean to
36  * another {link copyBean}.
37  */

38 public class JavaBeansUtil {
39     private JavaBeansUtil() {}
40     
41     /**
42      * This is the normal top level method for taking a Java Bean and
43      * dumping it as XML.
44      * @param obj the java bean to write out
45      * @param out the place to write it to
46      * @param propertyName the top level property
47      */

48     public static void writeBeanProperty(Object JavaDoc obj, Writer out, String JavaDoc propertyName) throws IOException, java.beans.IntrospectionException JavaDoc {
49         BeanWriter beanOut = new XmlBeanWriter(out);
50         writeBeanProperty(obj, beanOut, propertyName);
51     }
52
53     /**
54      * If you want to write the java bean out in a different way from
55      * the standard XML writer, use this method.
56      */

57     public static void writeBeanProperty(Object JavaDoc obj, BeanWriter out, String JavaDoc propertyName) throws IOException, java.beans.IntrospectionException JavaDoc {
58         writeBeanProperty(obj, out, new HashMap(), propertyName);
59     }
60
61     /**
62      * BeanWriter is the generic way of writing a java bean out.
63      */

64     public static interface BeanWriter {
65         public void beginPropertyName(String JavaDoc propertyName) throws IOException;
66         public void endPropertyName(String JavaDoc propertyName) throws IOException;
67         public void writeLeafObject(Object JavaDoc obj) throws IOException;
68         public void beginInnerNode() throws IOException;
69         public void endInnerNode() throws IOException;
70     }
71
72     /**
73      * The methods in this class will do proper XML indention for you.
74      */

75     public static abstract class IndentingBeanWriter implements BeanWriter {
76         protected String JavaDoc indentBy;
77         protected String JavaDoc indent;
78         protected int indentLevel = 0;
79         protected List indentions;
80
81         public IndentingBeanWriter() {
82             this("", "\t");
83         }
84         
85         public IndentingBeanWriter(String JavaDoc indentBy) {
86             this("", indentBy);
87         }
88         
89         public IndentingBeanWriter(String JavaDoc indent, String JavaDoc indentBy) {
90             this.indent = indent;
91             this.indentBy = indentBy;
92             this.indentions = new ArrayList();
93             this.indentions.add(indent); // indentLevel 0
94
}
95         
96         public void beginInnerNode() throws IOException {
97             ++indentLevel;
98             int indentionsSize = indentions.size();
99             if (indentionsSize <= indentLevel) {
100                 indent = (String JavaDoc) indentions.get(indentionsSize-1);
101                 do {
102                     indent += indentBy;
103                     indentions.add(indent);
104                     ++indentionsSize;
105                 } while (indentionsSize <= indentLevel);
106             } else {
107                 indent = (String JavaDoc) indentions.get(indentLevel);
108             }
109         }
110
111         public void endInnerNode() throws IOException {
112             --indentLevel;
113             indent = (String JavaDoc) indentions.get(indentLevel);
114         }
115     }
116
117     public static class XmlBeanWriter extends IndentingBeanWriter implements BeanWriter {
118         protected Writer out;
119
120         public XmlBeanWriter(Writer out) {
121             super();
122             this.out = out;
123         }
124         
125         public XmlBeanWriter(Writer out, String JavaDoc indentBy) {
126             super(indentBy);
127             this.out = out;
128         }
129         
130         public XmlBeanWriter(Writer out, String JavaDoc indent, String JavaDoc indentBy) {
131             super(indent, indentBy);
132             this.out = out;
133         }
134         
135         public void beginPropertyName(String JavaDoc propertyName) throws IOException {
136             out.write(indent);
137             out.write("<"+propertyName+">");
138         }
139
140         public void endPropertyName(String JavaDoc propertyName) throws IOException {
141             out.write("</"+propertyName+">\n");
142         }
143
144         public void writeLeafObject(Object JavaDoc obj) throws IOException {
145             XMLUtil.printXML(out, obj.toString(), false);
146         }
147
148         public void beginInnerNode() throws IOException {
149             super.beginInnerNode();
150             out.write("\n");
151         }
152
153         public void endInnerNode() throws IOException {
154             super.endInnerNode();
155             out.write(indent);
156         }
157     }
158     
159     public static class HtmlBeanWriter extends IndentingBeanWriter implements BeanWriter {
160         protected Writer out;
161
162         public HtmlBeanWriter(Writer out) {
163             super();
164             this.out = out;
165         }
166         
167         public HtmlBeanWriter(Writer out, String JavaDoc indentBy) {
168             super(indentBy);
169             this.out = out;
170         }
171         
172         public HtmlBeanWriter(Writer out, String JavaDoc indent, String JavaDoc indentBy) {
173             super(indent, indentBy);
174             this.out = out;
175         }
176         
177         public void beginPropertyName(String JavaDoc propertyName) throws IOException {
178             out.write(indent);
179             out.write("<tr>");
180             out.write("<th>"+propertyName+"</th>");
181         }
182
183         public void endPropertyName(String JavaDoc propertyName) throws IOException {
184             out.write("</tr>");
185             out.write("\n");
186         }
187
188         public void writeLeafObject(Object JavaDoc obj) throws IOException {
189             // leaf - write a table cell
190
out.write("<td>");
191             XMLUtil.printXML(out, obj.toString(), false);
192             out.write("</td>");
193         }
194
195         public void beginInnerNode() throws IOException {
196             super.beginInnerNode();
197             // inner node - write a nested table
198
out.write("<td><table width=\"100%\" border=\"1\">");
199             out.write("\n");
200         }
201
202         public void endInnerNode() throws IOException {
203             super.endInnerNode();
204             out.write(indent);
205             out.write("</table></td>");
206         }
207     }
208     
209     public static void writeBeanProperty(Object JavaDoc obj, BeanWriter out, Map skipChildren, String JavaDoc propertyName) throws IOException, java.beans.IntrospectionException JavaDoc {
210         if (obj == null)
211             return;
212         out.beginPropertyName(propertyName);
213         if (!isJavaBeanType(obj.getClass())) {
214             // leaf
215
out.writeLeafObject(obj);
216         } else {
217             // inner node
218
out.beginInnerNode();
219             writeBean(obj, out, skipChildren);
220             out.endInnerNode();
221         }
222         out.endPropertyName(propertyName);
223     }
224
225     /**
226      * This method is similar to writeBeanProperty except that the
227      * outer property name is not known and not printed.
228      */

229     public static void writeBean(Object JavaDoc obj, Writer out) throws IOException, java.beans.IntrospectionException JavaDoc {
230         BeanWriter beanOut = new XmlBeanWriter(out);
231         writeBean(obj, beanOut);
232     }
233     
234     public static void writeBean(Object JavaDoc obj, BeanWriter out) throws IOException, java.beans.IntrospectionException JavaDoc {
235         writeBean(obj, out, new HashMap());
236     }
237     
238     public static void writeBean(Object JavaDoc obj, BeanWriter out, Map skipChildren) throws IOException, java.beans.IntrospectionException JavaDoc {
239         //System.out.println("obj="+obj);
240
if (obj == null)
241             return;
242         // Make sure that we don't get into an infinite loop
243
if (skipChildren.containsKey(obj))
244             return;
245         skipChildren.put(obj, null);
246
247         Class JavaDoc objCls = obj.getClass();
248         /*
249         if (obj instanceof Collection) {
250             System.out.println("Hit Collection");
251             return;
252         }
253         if (objCls.isArray()) {
254             System.out.println("Hit Array");
255             return;
256         }
257         */

258
259         BeanInfo bi = Introspector.getBeanInfo(objCls);
260         PropertyDescriptor[] pds = bi.getPropertyDescriptors();
261         for (int i = 0 ; i < pds.length; ++i) {
262             PropertyDescriptor pd = pds[i];
263             Method reader = pd.getReadMethod();
264             if (reader == null)
265                 continue;
266             Class JavaDoc propertyType = pd.getPropertyType();
267             String JavaDoc propertyName = pd.getName();
268             //System.out.println("pd.getName="+propertyName+" pd.getPropertyType="+pd.getPropertyType());
269
//System.out.println("reader="+reader);
270
Class JavaDoc declaringClass = reader.getDeclaringClass();
271             //System.out.println("reader.declaring="+declaringClass);
272
// Need to handle indexed properties
273
if (declaringClass.equals(Object JavaDoc.class))
274                 continue;
275             if (propertyType == null)
276                 continue;
277             Object JavaDoc childObj = null;
278             try {
279                 childObj = reader.invoke(obj, null);
280             } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
281                 e.printStackTrace();
282             } catch (java.lang.IllegalAccessException JavaDoc e) {
283                 e.printStackTrace();
284             }
285             if (childObj != null) {
286                 if (childObj instanceof Collection) {
287                     //System.out.println("childObj is Collection");
288
Iterator it = ((Collection)childObj).iterator();
289                     while (it.hasNext()) {
290                         Object JavaDoc childElement = it.next();
291                         writeBeanProperty(childElement, out, skipChildren,
292                                           propertyName);
293                     }
294                 } else if (childObj.getClass().isArray()) {
295                     //System.out.println("childObj is Array");
296
int size = Array.getLength(childObj);
297                     for (int j = 0; j < size; ++j) {
298                         Object JavaDoc childElement = Array.get(childObj, j);
299                         writeBeanProperty(childElement, out, skipChildren,
300                                           propertyName);
301                     }
302                 } else {
303                     writeBeanProperty(childObj, out, skipChildren,
304                                       propertyName);
305                 }
306             }
307         }
308         skipChildren.remove(obj);
309     }
310
311     /**
312      * Construct a new cls and fill in it's contents from in.
313      *
314      * @param cls the Class to construct from the XML.
315      * @param in the source of the XML.
316      */

317     public static Object JavaDoc readBean(Class JavaDoc cls, java.io.InputStream JavaDoc in) throws javax.xml.parsers.ParserConfigurationException JavaDoc, org.xml.sax.SAXException JavaDoc, java.io.IOException JavaDoc, java.beans.IntrospectionException JavaDoc, java.lang.NoSuchMethodException JavaDoc, java.lang.InstantiationException JavaDoc, java.lang.IllegalAccessException JavaDoc, java.lang.reflect.InvocationTargetException JavaDoc {
318         Constructor construct = cls.getConstructor(new Class JavaDoc[0]);
319         Object JavaDoc newValue = construct.newInstance(new Object JavaDoc[0]);
320         readBean(newValue, in);
321         return newValue;
322     }
323
324     /**
325      * Fill in the contents of obj from the XML that's in in.
326      *
327      * @param obj the object to fill in from the XML.
328      * @param in the source of the XML.
329      */

330     public static void readBean(Object JavaDoc obj, java.io.InputStream JavaDoc in) throws javax.xml.parsers.ParserConfigurationException JavaDoc, org.xml.sax.SAXException JavaDoc, java.io.IOException JavaDoc, java.beans.IntrospectionException JavaDoc {
331         readBean(obj, new org.xml.sax.InputSource JavaDoc(in), false, null, null);
332     }
333
334     /**
335      * Warning: in readNoEntityResolver character and entity references will
336      * not be read from any DTD in the XML source.
337      * However, this way is faster since no DTDs are looked up
338      * (possibly skipping network access) or parsed.
339      */

340     public static void readBeanNoEntityResolver(Object JavaDoc obj, java.io.InputStream JavaDoc in) throws javax.xml.parsers.ParserConfigurationException JavaDoc, org.xml.sax.SAXException JavaDoc, java.io.IOException JavaDoc, java.beans.IntrospectionException JavaDoc {
341         readBean(obj, new org.xml.sax.InputSource JavaDoc(in), false,
342                  new org.xml.sax.EntityResolver JavaDoc() {
343                          public org.xml.sax.InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId) {
344                              java.io.ByteArrayInputStream JavaDoc bin = new java.io.ByteArrayInputStream JavaDoc(new byte[0]);
345                              return new org.xml.sax.InputSource JavaDoc(bin);
346                          }
347                      }
348                  , null);
349     }
350
351     public static void readBean(Object JavaDoc obj, org.xml.sax.InputSource JavaDoc in, boolean validate, org.xml.sax.EntityResolver JavaDoc er, org.xml.sax.ErrorHandler JavaDoc eh) throws javax.xml.parsers.ParserConfigurationException JavaDoc, org.xml.sax.SAXException JavaDoc, java.io.IOException JavaDoc, java.beans.IntrospectionException JavaDoc {
352         javax.xml.parsers.DocumentBuilderFactory JavaDoc dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
353         dbf.setValidating(validate);
354         javax.xml.parsers.DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
355         if (er != null) db.setEntityResolver(er);
356         if (eh != null) db.setErrorHandler(eh);
357         org.w3c.dom.Document JavaDoc doc = db.parse(in);
358         readBean(obj, doc);
359     }
360
361     /**
362      * Construct a new cls and fill in it's contents from document.
363      *
364      * @param cls the Class to construct from the XML.
365      * @param document the source of the XML.
366      */

367     public static Object JavaDoc readBean(Class JavaDoc cls, org.w3c.dom.Document JavaDoc document) throws java.beans.IntrospectionException JavaDoc, java.lang.NoSuchMethodException JavaDoc, java.lang.InstantiationException JavaDoc, java.lang.IllegalAccessException JavaDoc, java.lang.reflect.InvocationTargetException JavaDoc {
368         Constructor construct = cls.getConstructor(new Class JavaDoc[0]);
369         Object JavaDoc newValue = construct.newInstance(new Object JavaDoc[0]);
370         readBean(newValue, document);
371         return newValue;
372     }
373     
374     /**
375      * Fill in the contents of obj from the XML that's in document.
376      *
377      * @param obj the object to fill in from the XML.
378      * @param document the source of the XML.
379      */

380     public static void readBean(Object JavaDoc obj, org.w3c.dom.Document JavaDoc document) throws java.beans.IntrospectionException JavaDoc {
381         readBean(obj, document.getDocumentElement());
382     }
383     
384     public static void readBean(Object JavaDoc obj, Node node) throws java.beans.IntrospectionException JavaDoc {
385         if (obj == null)
386             return;
387         int errorCount = 0;
388         Class JavaDoc objCls = obj.getClass();
389         BeanInfo bi = Introspector.getBeanInfo(objCls);
390         PropertyDescriptor[] pds = bi.getPropertyDescriptors();
391         Map propertyWriters = new HashMap(); // <String, Method>
392
Map propertyTypes = new HashMap(); // <String, Class>
393
for (int i = 0 ; i < pds.length; ++i) {
394             PropertyDescriptor pd = pds[i];
395             Method writer = pd.getWriteMethod();
396             if (writer == null)
397                 continue;
398             Class JavaDoc propertyType = pd.getPropertyType();
399             String JavaDoc propertyName = pd.getName();
400             Class JavaDoc declaringClass = writer.getDeclaringClass();
401             //System.out.println("pd.getName="+propertyName+" pd.getPropertyType="+pd.getPropertyType()+" declaringClass="+declaringClass);
402
if (declaringClass == null || declaringClass.equals(Object JavaDoc.class))
403                 continue;
404             if (propertyType == null)
405                 continue;
406             propertyWriters.put(propertyName, writer);
407             propertyTypes.put(propertyName, propertyType);
408         }
409
410         Map propertiesNewValues = new HashMap();
411         if (node.hasAttributes()) {
412             org.w3c.dom.NamedNodeMap JavaDoc attrs = node.getAttributes();
413             for (int i = 0; i < attrs.getLength(); ++i) {
414                 Attr attr = (Attr) attrs.item(i);
415                 String JavaDoc attrName = attr.getName();
416                 if (!propertyWriters.containsKey(attrName)) {
417                     attrName = Common.convertName(attrName);
418                     if (!propertyWriters.containsKey(attrName)) {
419                         attrName = Introspector.decapitalize(attrName);
420                         if (!propertyWriters.containsKey(attrName)) {
421                             ++errorCount;
422                             System.out.println("Found attribute and did not find property in Java Bean: "+attr.getName());
423                             continue;
424                         }
425                     }
426                 }
427                 Object JavaDoc newValue = convertValue((Class JavaDoc)propertyTypes.get(attrName),
428                                                attr.getValue());
429                 propertiesNewValues.put(attrName, newValue);
430             }
431         }
432         org.w3c.dom.NodeList JavaDoc children = node.getChildNodes();
433         for (int i = 0, size = children.getLength(); i < size; ++i) {
434             org.w3c.dom.Node JavaDoc childNode = children.item(i);
435             if (!(childNode instanceof Element))
436                 continue;
437             String JavaDoc childNodeName = (childNode.getLocalName() == null ? childNode.getNodeName().intern() : childNode.getLocalName().intern());
438             //System.out.println("Found child named "+childNodeName);
439
if (!propertyWriters.containsKey(childNodeName)) {
440                 childNodeName = Common.convertName(childNodeName);
441                 if (!propertyWriters.containsKey(childNodeName)) {
442                     childNodeName = Introspector.decapitalize(childNodeName);
443                     if (!propertyWriters.containsKey(childNodeName)) {
444                         ++errorCount;
445                         System.out.println("Found element and did not find property in Java Bean: "+childNode.getNodeName());
446                         continue;
447                     }
448                 }
449             }
450             Class JavaDoc propertyType = (Class JavaDoc) propertyTypes.get(childNodeName);
451             Object JavaDoc newValue = null;
452             if (isJavaBeanType(propertyType)) {
453                 Class JavaDoc propertyTypeOnce = propertyType;
454                 if (propertyType.isArray())
455                     propertyTypeOnce = propertyType.getComponentType();
456                 try {
457                     //System.out.println("It's a Java Bean type");
458
Constructor construct = propertyTypeOnce.getConstructor(new Class JavaDoc[0]);
459                     newValue = construct.newInstance(new Object JavaDoc[0]);
460                     readBean(newValue, childNode);
461                 } catch (java.lang.NoSuchMethodException JavaDoc e) {
462                     e.printStackTrace();
463                     ++errorCount;
464                 } catch (java.lang.InstantiationException JavaDoc e) {
465                     e.printStackTrace();
466                     ++errorCount;
467                 } catch (java.lang.IllegalAccessException JavaDoc e) {
468                     e.printStackTrace();
469                     ++errorCount;
470                 } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
471                     e.printStackTrace();
472                     ++errorCount;
473                 }
474             } else {
475                 String JavaDoc nodeValue;
476                 if (childNode.getFirstChild() == null)
477                     nodeValue = "";
478                 else
479                     nodeValue = childNode.getFirstChild().getNodeValue();
480                 Class JavaDoc typeOfNewValue = propertyType;
481                 if (propertyType.isArray())
482                     typeOfNewValue = propertyType.getComponentType();
483                 newValue = convertValue(typeOfNewValue, nodeValue);
484             }
485             //System.out.println("newValue="+newValue+" newValue.class="+newValue.getClass()+" propertyType="+propertyType.getName());
486
if (propertyType.isArray()) {
487                 List values = (List) propertiesNewValues.get(childNodeName);
488                 if (values == null) {
489                     values = new ArrayList();
490                     propertiesNewValues.put(childNodeName, values);
491                 }
492                 values.add(newValue);
493             } else {
494                 propertiesNewValues.put(childNodeName, newValue);
495             }
496         }
497
498         for (Iterator it = propertiesNewValues.keySet().iterator();
499              it.hasNext(); ) {
500             String JavaDoc propertyName = (String JavaDoc) it.next();
501             Class JavaDoc propertyType = (Class JavaDoc) propertyTypes.get(propertyName);
502             Method writer = (Method) propertyWriters.get(propertyName);
503
504             //System.out.println("propertyName="+propertyName+" writer="+writer);
505
Object JavaDoc newValue;
506             if (propertyType.isArray()) {
507                 // convert our List into an array
508
List values = (List) propertiesNewValues.get(propertyName);
509                 newValue = Array.newInstance(propertyType.getComponentType(),
510                                              values.size());
511                 //newValue = values.toArray((Object[])newValue);
512
for (int i = 0; i < values.size(); ++i) {
513                     //System.out.println("i="+i+" values.get(i)="+values.get(i)+" values.get(i).class="+values.get(i).getClass());
514
Array.set(newValue, i, values.get(i));
515                 }
516             } else {
517                 newValue = propertiesNewValues.get(propertyName);
518             }
519
520             //System.out.println("newValue="+newValue+" newValue.class="+newValue.getClass());
521
try {
522                 writer.invoke(obj, new Object JavaDoc[] {newValue});
523             } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
524                 e.printStackTrace();
525                 ++errorCount;
526             } catch (java.lang.IllegalAccessException JavaDoc e) {
527                 e.printStackTrace();
528                 ++errorCount;
529             }
530         }
531     }
532
533
534     /**
535      * Find matching properties between these 2 beans and copy over the
536      * contents.
537      */

538     public static void copyBean(Object JavaDoc src, Object JavaDoc dest) throws java.beans.IntrospectionException JavaDoc {
539         copyBean(src, dest, Collections.EMPTY_MAP);
540     }
541     
542     /**
543      * Find matching properties between these 2 beans and copy over the
544      * contents.
545      *
546      * @param nameMapping maps property names from the src object to the dest object.
547      */

548     public static void copyBean(Object JavaDoc src, Object JavaDoc dest, Map nameMapping) throws java.beans.IntrospectionException JavaDoc {
549         if (src == null)
550             return;
551         Class JavaDoc srcCls = src.getClass();
552         BeanInfo bi = Introspector.getBeanInfo(srcCls);
553         PropertyDescriptor[] pds = bi.getPropertyDescriptors();
554         Map propertyReaders = new HashMap(); // <String, Method>
555
Map propertyTypes = new HashMap(); // <String, Class>
556
for (int i = 0 ; i < pds.length; ++i) {
557             PropertyDescriptor pd = pds[i];
558             Method reader = pd.getReadMethod();
559             if (reader == null)
560                 continue;
561             Class JavaDoc propertyType = pd.getPropertyType();
562             String JavaDoc propertyName = pd.getName();
563             Class JavaDoc declaringClass = reader.getDeclaringClass();
564             //System.out.println("pd.getName="+propertyName+" pd.getPropertyType="+pd.getPropertyType()+" declaringClass="+declaringClass);
565
if (declaringClass == null || declaringClass.equals(Object JavaDoc.class))
566                 continue;
567             if (propertyType == null)
568                 continue;
569             if (nameMapping.containsKey(propertyName))
570                 propertyName = (String JavaDoc) nameMapping.get(propertyName);
571             propertyReaders.put(propertyName, reader);
572             propertyTypes.put(propertyName, propertyType);
573         }
574
575         Class JavaDoc destCls = dest.getClass();
576         bi = Introspector.getBeanInfo(destCls);
577         pds = bi.getPropertyDescriptors();
578         for (int i = 0 ; i < pds.length; ++i) {
579             PropertyDescriptor pd = pds[i];
580             Method writer = pd.getWriteMethod();
581             if (writer == null)
582                 continue;
583             Class JavaDoc propertyType = pd.getPropertyType();
584             String JavaDoc propertyName = pd.getName();
585             Class JavaDoc declaringClass = writer.getDeclaringClass();
586             if (declaringClass == null || declaringClass.equals(Object JavaDoc.class))
587                 continue;
588             if (propertyType == null)
589                 continue;
590             if (propertyReaders.containsKey(propertyName)) {
591                 // Found a common property
592
//System.out.println("copying propertyName="+propertyName);
593
try {
594                     Method reader = (Method) propertyReaders.get(propertyName);
595                     Object JavaDoc srcValue = reader.invoke(src, null);
596                     //System.out.println("srcValue="+srcValue);
597
if (isJavaBeanType(propertyType)) {
598                         Class JavaDoc propertyTypeOnce = propertyType;
599                         int size = 1;
600                         Object JavaDoc destValue = null;
601                         if (propertyType.isArray()) {
602                             propertyTypeOnce = propertyType.getComponentType();
603                             size = Array.getLength(srcValue);
604                             destValue = Array.newInstance(propertyTypeOnce, size);
605                         }
606                         for (int index = 0; index < size; ++index) {
607                             Constructor construct = propertyTypeOnce.getConstructor(new Class JavaDoc[0]);
608                             Object JavaDoc srcValueOnce;
609                             Object JavaDoc destValueOnce = construct.newInstance(new Object JavaDoc[0]);
610                             if (propertyType.isArray()) {
611                                 Array.set(destValue, index, destValueOnce);
612                                 srcValueOnce = Array.get(srcValue, index);
613                             } else {
614                                 destValue = destValueOnce;
615                                 srcValueOnce = srcValue;
616                             }
617                             copyBean(srcValueOnce, destValueOnce, nameMapping);
618                             //System.out.println("destValueOnce.class="+destValueOnce.getClass());
619
//System.out.println("destValueOnce="+destValueOnce);
620
}
621                         writer.invoke(dest, new Object JavaDoc[] {destValue});
622                     } else if (propertyType.isAssignableFrom((Class JavaDoc)propertyTypes.get(propertyName))) {
623                         writer.invoke(dest, new Object JavaDoc[] {srcValue});
624                     } else {
625                         //System.out.println("Wrong type!");
626
continue;
627                     }
628                 } catch (java.lang.IllegalAccessException JavaDoc e) {
629                     e.printStackTrace();
630                 } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
631                     e.printStackTrace();
632                 } catch (java.lang.NoSuchMethodException JavaDoc e) {
633                     e.printStackTrace();
634                 } catch (java.lang.InstantiationException JavaDoc e) {
635                     e.printStackTrace();
636                 }
637             }
638         }
639     }
640
641     /**
642      * Determine if type is a java bean or not. This is a tough
643      * decision. This method is called to figure out at what types to
644      * stop recursing in the bean graph. Any type that is not simple
645      * enough is called a java bean.
646      */

647     public static boolean isJavaBeanType(Class JavaDoc type) {
648         if (Collection.class.isAssignableFrom(type))
649             return false;
650         if (type.isArray()) {
651             return isJavaBeanType(type.getComponentType());
652         }
653         String JavaDoc typeName = type.getName().intern();
654         if (typeName == "java.lang.String"||
655             typeName == "java.lang.Integer"|| typeName == "int" ||
656             typeName == "java.lang.Character"|| typeName == "char" ||
657             typeName == "java.lang.Long"|| typeName == "long" ||
658             typeName == "java.lang.Float"|| typeName == "float" ||
659             typeName == "java.lang.Double"|| typeName == "double" ||
660             typeName == "java.lang.Boolean"|| typeName == "boolean" ||
661             typeName == "java.lang.Short"|| typeName == "short" ||
662             typeName == "java.lang.Byte"|| typeName == "byte" ||
663             typeName == "java.math.BigDecimal"||
664             typeName == "java.math.BigInteger"||
665             typeName == "java.lang.Object" ||
666             typeName == "java.util.Calendar" || typeName == "java.util.Date" ||
667             typeName == "java.util.GregorianCalendar" ||
668             typeName == "javax.xml.namespace.QName" ||
669             typeName == "java.net.URL" || typeName == "java.net.URI")
670             return false;
671         return true;
672     }
673
674     /**
675      * Convert a textual representation of type stored in value into a
676      * java object. If we don't know the type, then look for a
677      * constructor that takes a single String as a parameter.
678      */

679     public static Object JavaDoc convertValue(Class JavaDoc type, String JavaDoc value) {
680         String JavaDoc typeName = type.getName().intern();
681         if (typeName == "java.lang.String")
682             return value;
683         if (typeName == "java.lang.Boolean" || typeName == "boolean")
684             return Boolean.valueOf(value);
685         if (typeName == "java.lang.Integer" || typeName == "int")
686             return Integer.valueOf(value);
687         if (typeName == "java.lang.Long" || typeName == "long")
688             return Long.valueOf(value);
689         if (typeName == "java.lang.Float" || typeName == "float")
690             return Float.valueOf(value);
691         if (typeName == "java.lang.Double" || typeName == "double")
692             return Double.valueOf(value);
693         if (typeName == "java.lang.Byte" || typeName == "byte")
694             return Byte.valueOf(value);
695         if (typeName == "java.lang.Short" || typeName == "short")
696             return Short.valueOf(value);
697         if (typeName == "java.lang.Character" || typeName == "char")
698             return new Character JavaDoc(value.charAt(0));
699         if (typeName == "java.net.URL") {
700             try {
701                 return new java.net.URL JavaDoc(value);
702             } catch (java.net.MalformedURLException JavaDoc e) {
703                 throw new RuntimeException JavaDoc(e);
704             }
705         }
706         if (typeName == "java.net.URI") {
707             try {
708                 return new java.net.URI JavaDoc(value);
709             } catch (java.net.URISyntaxException JavaDoc e) {
710                 throw new RuntimeException JavaDoc(e);
711             }
712         }
713         if (typeName == "java.math.BigDecimal")
714             return new java.math.BigDecimal JavaDoc(value);
715         if (typeName == "java.math.BigInteger")
716             return new java.math.BigInteger JavaDoc(value);
717         if (typeName == "java.util.Calendar") {
718             // For XML Schema, we're trying to parse ISO8601 date time format
719
// CCYY-MM-DDThh:mm:ss+TZ:TZ
720
// 1999-05-31T13:20:00-05:00
721
// For -5 time zone, should use
722
// TimeZone.getAvailableIDs(-5*60*60*1000)
723
TimeZone tz = TimeZone.getDefault();
724             Calendar cal = Calendar.getInstance(tz);
725             Date date = null;
726             String JavaDoc[] possibleFormats = {"yyyy-MM-dd'T'HH:mm:ss.S", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd"}; // NOI18N
727
java.text.ParsePosition JavaDoc pos = null;
728             for (int formatNum = 0; formatNum < possibleFormats.length; ++formatNum) {
729                 pos = new java.text.ParsePosition JavaDoc(0);
730                 java.text.SimpleDateFormat JavaDoc formatter = new java.text.SimpleDateFormat JavaDoc(possibleFormats[formatNum]);
731                 formatter.setCalendar(cal);
732                 date = formatter.parse(value, pos);
733                 if (date != null) {
734                     break;
735                 }
736             }
737             if (date == null) {
738                 throw new java.lang.RuntimeException JavaDoc(Common.getMessage("MSG_BadParse", value));
739             }
740             cal.setTime(date);
741             return cal;
742         }
743         
744         Constructor c = null;
745         
746         try {
747             Class JavaDoc[] cc = new Class JavaDoc[] {java.lang.String JavaDoc.class};
748             c = type.getDeclaredConstructor(cc);
749             Object JavaDoc[] p = new Object JavaDoc[] {value};
750             return c.newInstance(p);
751         } catch (NoSuchMethodException JavaDoc me) {
752             throw new RuntimeException JavaDoc(me);
753         } catch (java.lang.InstantiationException JavaDoc e) {
754             throw new RuntimeException JavaDoc(e);
755         } catch (java.lang.IllegalAccessException JavaDoc e) {
756             throw new RuntimeException JavaDoc(e);
757         } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
758             throw new RuntimeException JavaDoc(e);
759         }
760     }
761
762     /**
763      * Used for generating Java code for reading complicated types.
764      * @param typeName the java type to generate the method about, can also
765      * be "base64Binary".
766      */

767     public static void genReadType(Writer out, String JavaDoc typeName) throws IOException {
768         typeName = typeName.intern();
769         if (typeName == "java.util.Calendar") {
770             out.write("public static java.util.Calendar stringToCalendar(String value) throws java.text.ParseException {\n");
771             out.write("java.util.TimeZone tz = java.util.TimeZone.getDefault();\n");
772             out.write("java.util.Calendar cal = java.util.Calendar.getInstance(tz);\n");
773             out.write("java.util.Date date = null;\n");
774             out.write("String[] possibleFormats = {\"yyyy-MM-dd'T'HH:mm:ss.S\", \"yyyy-MM-dd'T'HH:mm:ss\", \"yyyy-MM-dd\"}; // NOI18N\n");
775             out.write("java.text.ParsePosition pos = null;\n");
776             out.write("for (int formatNum = 0; formatNum < possibleFormats.length; ++formatNum) {\n");
777             out.write("pos = new java.text.ParsePosition(0);\n");
778             out.write("java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(possibleFormats[formatNum]);\n");
779             out.write("formatter.setCalendar(cal);\n");
780             out.write("date = formatter.parse(value, pos);\n");
781             out.write("if (date != null) {\n");
782             out.write("break;\n");
783             out.write("}\n");
784             out.write("}\n");
785             out.write("if (date == null) {\n");
786             out.write("throw new java.text.ParseException(\"Bad time/date parse of \"+value, pos.getErrorIndex());\n");
787             out.write("}\n");
788             out.write("int len = value.length();\n");
789             out.write("if (pos.getIndex() < len) {\n");
790             out.write("if (value.charAt(pos.getIndex()) == 'Z') {\n");
791             out.write("// The Timezone is UTC\n");
792             out.write("tz = java.util.TimeZone.getTimeZone(\"GMT\");\n");
793             out.write("cal.setTimeZone(tz);\n");
794             out.write("} else {\n");
795             out.write("tz = java.util.TimeZone.getTimeZone(\"GMT\"+value.substring(pos.getIndex(), len));\n");
796             out.write("cal.setTimeZone(tz);\n");
797             out.write("}\n");
798             out.write("}\n");
799             out.write("cal.setTime(date);\n");
800             out.write("return cal;\n");
801             out.write("}\n");
802         } else if (typeName == "base64Binary") {
803             out.write("public static byte[] decodeBase64BinaryString(String text) {\n");
804             out.write("final int decodeBase64Table[] = {62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51};\n");
805             out.write("StringBuffer cleanedEncoding = new StringBuffer();\n");
806             out.write("int len = text.length();\n");
807             out.write("// Get rid of extraneous characters (like whitespace).\n");
808             out.write("for (int i = 0; i < len; ++i) {\n");
809             out.write("if (text.charAt(i) > 0x20) {\n");
810             out.write("cleanedEncoding.append(text.charAt(i));\n");
811             out.write("}\n");
812             out.write("}\n");
813             out.write("char[] encodedText = cleanedEncoding.toString().toCharArray();\n");
814             out.write("len = encodedText.length;\n");
815             out.write("if (len == 0) {\n");
816             out.write("return new byte[0];\n");
817             out.write("}\n");
818             out.write("int howManyBlocks = len / 4;\n");
819             out.write("int partialLen = 3;\n");
820             out.write("if (encodedText[len-1] == '=') {\n");
821             out.write("partialLen -= 1;\n");
822             out.write("if (encodedText[len-2] == '=') {\n");
823             out.write("partialLen -= 1;\n");
824             out.write("}\n");
825             out.write("}\n");
826             out.write("int resultLen = partialLen + (howManyBlocks - 1) * 3;\n");
827             out.write("byte[] result = new byte[resultLen];\n");
828             out.write("int resultIndex = 0;\n");
829             out.write("int encodedTextIndex = 0;\n");
830             out.write("for (int blockNum = 0; blockNum < howManyBlocks; ++blockNum) {\n");
831             out.write("int a = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n");
832             out.write("int b = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n");
833             out.write("int c = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n");
834             out.write("int d = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n");
835             
836             out.write("result[resultIndex++] = (byte) ( (b >> 4) | (a << 2) );\n");
837             out.write("if (resultIndex < resultLen) {\n");
838             out.write("result[resultIndex++] = (byte) ( ((b & 0xf) << 4) | (c >> 2) );\n");
839             out.write("}\n");
840             out.write("if (resultIndex < resultLen) {\n");
841             out.write("result[resultIndex++] = (byte) ( ((c & 0x3) << 6) | d);\n");
842             out.write("}\n");
843             out.write("}\n");
844             out.write("return result;\n");
845             out.write("}\n");
846         }
847     }
848
849     /**
850      * Used for generating Java code for writing complicated types.
851      * @param typeName the java type to generate the method about, can also
852      * be "base64Binary".
853      */

854     public static void genWriteType(Writer out, String JavaDoc typeName) throws IOException {
855         typeName = typeName.intern();
856         if (typeName == "java.util.Calendar") {
857             out.write("public static String calendarToString(java.util.Calendar cal) {\n");
858             out.write("java.util.Date date = cal.getTime();\n");
859             out.write("java.text.SimpleDateFormat formatter;\n");
860             out.write("if (cal.get(java.util.Calendar.HOUR) == 0 && cal.get(java.util.Calendar.MINUTE) == 0 && cal.get(java.util.Calendar.SECOND) == 0) {\n");
861             out.write("formatter = new java.text.SimpleDateFormat(\"yyyy-MM-dd\"); // NOI18N\n");
862             out.write("} else if (cal.get(java.util.Calendar.MILLISECOND) == 0) {\n");
863             out.write("formatter = new java.text.SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\"); // NOI18N\n");
864             out.write("} else {\n");
865             out.write("formatter = new java.text.SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.S\"); // NOI18N\n");
866             out.write("}\n");
867             out.write("String result = formatter.format(date);\n");
868             out.write("if (java.util.TimeZone.getDefault().hasSameRules(cal.getTimeZone())) {\n");
869             out.write("return result;\n");
870             out.write("}\n");
871             out.write("int offset = cal.getTimeZone().getOffset(0);\n");
872             out.write("if (offset == 0) {\n");
873             out.write("return result+\"Z\";\n");
874             out.write("}\n");
875             out.write("int seconds = offset / 1000;\n");
876             out.write("if (seconds > 0) {\n");
877             out.write("result += \"+\";\n");
878             out.write("} else {\n");
879             out.write("seconds = -1 * seconds;\n");
880             out.write("result += \"-\";\n");
881             out.write("}\n");
882             out.write("int hours = seconds / 3600;\n");
883             out.write("if (hours < 10) {\n");
884             out.write("result += \"0\";\n");
885             out.write("}\n");
886             out.write("result += hours + \":\";\n");
887             out.write("int minutes = (seconds / 60) % 60;\n");
888             out.write("if (minutes < 10) {\n");
889             out.write("result += \"0\";\n");
890             out.write("}\n");
891             out.write("result += minutes;\n");
892             out.write("return result;\n");
893             out.write("}\n");
894         } else if (typeName == "base64Binary") {
895             out.write("public static String encodeBase64BinaryString(byte[] instance) {\n");
896             out.write("final char encodeBase64Table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};\n");
897             out.write("byte[] value = (byte[]) instance;\n");
898             out.write("int len = value.length;\n");
899             out.write("if (len == 0) {\n");
900             out.write("return \"\";\n");
901             out.write("}\n");
902             out.write("int howManyBlocks = len / 3;\n");
903             out.write("int partialLen = len % 3;\n");
904             out.write("if (partialLen != 0) {\n");
905             out.write("howManyBlocks += 1;\n");
906             out.write("}\n");
907             out.write("int resultLen = howManyBlocks * 4;\n");
908             out.write("StringBuffer result = new StringBuffer(resultLen);\n");
909             out.write("int valueIndex = 0;\n");
910             out.write("for (int blockNum = 0; blockNum < howManyBlocks; ++blockNum) {\n");
911             out.write("int a = value[valueIndex++];\n");
912             out.write("int b;\n");
913             out.write("int c;\n");
914             out.write("if (valueIndex < len) {\n");
915             out.write("b = value[valueIndex++];\n");
916             out.write("} else {\n");
917             out.write("b = 0;\n");
918             out.write("}\n");
919             out.write("if (valueIndex < len) {\n");
920             out.write("c = value[valueIndex++];\n");
921             out.write("} else {\n");
922             out.write("c = 0;\n");
923             out.write("}\n");
924             out.write("if (a < 0) {\n");
925             out.write("a += 256;\n");
926             out.write("}\n");
927             out.write("if (b < 0) {\n");
928             out.write("b += 256;\n");
929             out.write("}\n");
930             out.write("if (c < 0) {\n");
931             out.write("c += 256;\n");
932             out.write("}\n");
933             out.write("result.append(encodeBase64Table[a >> 2]);\n");
934             out.write("result.append(encodeBase64Table[((a & 0x3) << 4) | (b >> 4)]);\n");
935             out.write("result.append(encodeBase64Table[((b & 0xf) << 2) | (c >> 6)]);\n");
936             out.write("result.append(encodeBase64Table[c & 0x3f]);\n");
937             out.write("}\n");
938             out.write("if (partialLen == 1) {\n");
939             out.write("result.setCharAt(resultLen - 1, '=');\n");
940             out.write("result.setCharAt(resultLen - 2, '=');\n");
941             out.write("} else if (partialLen == 2) {\n");
942             out.write("result.setCharAt(resultLen - 1, '=');\n");
943             out.write("}\n");
944             out.write("return result.toString();\n");
945             out.write("}\n");
946         }
947     }
948
949     ///////////////////////////////////////////////////////////////////////
950

951     /**
952      * Create a bean with dummy values.
953      * If a bean property write method fails or the constructor to the bean
954      * fails, then a null value is used.
955      */

956     public static Object JavaDoc dummyBean(Class JavaDoc cls, int arraySize) throws java.beans.IntrospectionException JavaDoc {
957
958         // construct a new instance
959
if (!isJavaBeanType(cls)) {
960             return dummyValue(cls, arraySize);
961         }
962         
963         Object JavaDoc obj = null;
964         try {
965             Constructor construct = cls.getConstructor(new Class JavaDoc[0]);
966             obj = construct.newInstance(new Object JavaDoc[0]);
967         } catch (java.lang.NoSuchMethodException JavaDoc e) {
968             e.printStackTrace();
969             return null;
970         } catch (java.lang.InstantiationException JavaDoc e) {
971             e.printStackTrace();
972             return null;
973         } catch (java.lang.IllegalAccessException JavaDoc e) {
974             e.printStackTrace();
975             return null;
976         } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
977             e.printStackTrace();
978             return null;
979         }
980
981         // stuff the bean with the dummy values
982
BeanInfo bi = Introspector.getBeanInfo(cls);
983         PropertyDescriptor[] pds = bi.getPropertyDescriptors();
984
985         for (int i = 0 ; i < pds.length; ++i) {
986             PropertyDescriptor pd = pds[i];
987             Method writer = pd.getWriteMethod();
988             if (writer == null) continue;
989             Class JavaDoc propertyType = pd.getPropertyType();
990             String JavaDoc propertyName = pd.getName();
991             Class JavaDoc declaringClass = writer.getDeclaringClass();
992             if (declaringClass == null || declaringClass.equals(Object JavaDoc.class)) continue;
993             if (propertyType == null) continue;
994
995             Object JavaDoc newValue=null;
996             Object JavaDoc baseValue=null;
997             if (isJavaBeanType(propertyType)) {
998                 Class JavaDoc baseType = propertyType;
999                 if (propertyType.isArray())
1000                    baseType = propertyType.getComponentType();
1001                baseValue = dummyBean(baseType, arraySize);
1002                if (propertyType.isArray()) {
1003                    // if array of beans, set each element
1004
newValue = Array.newInstance(baseType, arraySize);
1005                    for (int ii=0; ii<arraySize; ++ii) {
1006                        Array.set(newValue, ii, baseValue);
1007                    }
1008                } else {
1009                    newValue = baseValue;
1010                }
1011            } else {
1012                Class JavaDoc baseType = propertyType;
1013                if (propertyType.isArray())
1014                    baseType = propertyType.getComponentType();
1015                baseValue = dummyValue(baseType, arraySize);
1016                if (propertyType.isArray()) {
1017                    // if array, set each elements
1018
newValue = Array.newInstance(baseType, arraySize);
1019                    for (int ii=0; ii<arraySize; ++ii) {
1020                        Array.set(newValue, ii, baseValue);
1021                    }
1022                } else {
1023                    newValue = baseValue;
1024                }
1025            }
1026
1027            // set the value to property
1028
try {
1029                writer.invoke(obj, new Object JavaDoc[] {newValue});
1030            } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
1031                // Let the null value be used
1032
e.printStackTrace();
1033            } catch (java.lang.IllegalAccessException JavaDoc e) {
1034                // Let the null value be used
1035
e.printStackTrace();
1036            }
1037        }
1038
1039        // return the dummy bean
1040
return obj;
1041    }
1042
1043
1044    /**
1045     * @return dummy value for a particular type. If it's not a standard
1046     * type, then look for a constructor that takes a single String as
1047     * a parameter; if that fails, then return null.
1048     */

1049    public static Object JavaDoc dummyValue(Class JavaDoc type, int arraySize) {
1050        String JavaDoc typeName = type.getName().intern();
1051        if (Collection.class.isAssignableFrom(type)) {
1052            // if collection - make an arraylist of string
1053
ArrayList lst = new ArrayList();
1054            for (int ii=0; ii < arraySize; ++ii) {
1055                lst.add("collection-element");
1056            }
1057            return lst;
1058        } else if (typeName == "java.lang.String")
1059            return "string";
1060        else if (typeName == "java.lang.Boolean" || typeName == "boolean")
1061            return Boolean.FALSE;
1062        else if (typeName == "java.lang.Integer" || typeName == "int")
1063            return Integer.valueOf("1");
1064        else if (typeName == "java.lang.Long" || typeName == "long")
1065            return Long.valueOf("1");
1066        else if (typeName == "java.lang.Float" || typeName == "float")
1067            return Float.valueOf("1.0");
1068        else if (typeName == "java.lang.Double" || typeName == "double")
1069            return Double.valueOf("1.0");
1070        else if (typeName == "java.lang.Byte" || typeName == "byte")
1071            return Byte.valueOf("1");
1072        else if (typeName == "java.lang.Short" || typeName == "short")
1073            return Short.valueOf("1");
1074        else if (typeName == "java.lang.Character" || typeName == "char")
1075            return new Character JavaDoc('C');
1076        else if (typeName == "java.math.BigDecimal")
1077            return new java.math.BigDecimal JavaDoc("1.0");
1078        else if (typeName == "java.math.BigInteger")
1079            return new java.math.BigInteger JavaDoc("1");
1080        else if (typeName == "java.util.Calendar") {
1081            Calendar cal = Calendar.getInstance();
1082            cal.setTime(new Date());
1083            return cal;
1084        } else {
1085            // all other types, try to construct using string constructor.
1086
Constructor c = null;
1087    
1088            try {
1089                Class JavaDoc[] cc = new Class JavaDoc[] {java.lang.String JavaDoc.class};
1090                c = type.getDeclaredConstructor(cc);
1091                Object JavaDoc[] p = new Object JavaDoc[] {"string"};
1092                return c.newInstance(p);
1093            } catch (NoSuchMethodException JavaDoc e) {
1094                e.printStackTrace();
1095                return null;
1096            } catch (java.lang.InstantiationException JavaDoc e) {
1097                e.printStackTrace();
1098                return null;
1099            } catch (java.lang.IllegalAccessException JavaDoc e) {
1100                e.printStackTrace();
1101                return null;
1102            } catch (java.lang.reflect.InvocationTargetException JavaDoc e) {
1103                e.printStackTrace();
1104                return null;
1105            }
1106        }
1107    }
1108}
1109
Popular Tags