KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > micronova > util > TypeUtil


1 /*
2
3 Copyright 2003-2007 MicroNova (R)
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or
7 without modification, are permitted provided that the following
8 conditions are met:
9
10     * Redistributions of source code must retain the above copyright
11     notice, this list of conditions and the following disclaimer.
12
13     * Redistributions in binary form must reproduce the above copyright
14     notice, this list of conditions and the following disclaimer in the
15     documentation and/or other materials provided with the distribution.
16
17     * Neither the name of MicroNova nor the names of its contributors
18     may be used to endorse or promote products derived from this
19     software without specific prior written permission.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE.
32
33 */

34
35
36 package com.micronova.util;
37
38 import java.util.*;
39 import java.util.regex.*;
40 import java.lang.reflect.*;
41 import java.text.*;
42 import java.io.*;
43 import java.net.*;
44 import javax.xml.parsers.*;
45 import javax.xml.transform.*;
46 import javax.xml.transform.dom.*;
47 import javax.xml.transform.stream.*;
48 import org.w3c.dom.*;
49
50 /** datatype-related utilities */
51
52 public class TypeUtil
53 {
54     /** primitive type map */
55
56     private static final Map PRIMITIVETYPE;
57     private static final Map WRAPPERTYPE;
58
59     static
60     {
61         PRIMITIVETYPE = new HashMap();
62
63         PRIMITIVETYPE.put("boolean", Boolean.TYPE);
64         PRIMITIVETYPE.put("char", Character.TYPE);
65         PRIMITIVETYPE.put("byte", Byte.TYPE);
66         PRIMITIVETYPE.put("short", Short.TYPE);
67         PRIMITIVETYPE.put("int", Integer.TYPE);
68         PRIMITIVETYPE.put("long", Long.TYPE);
69         PRIMITIVETYPE.put("float", Float.TYPE);
70         PRIMITIVETYPE.put("double", Double.TYPE);
71
72         WRAPPERTYPE = new HashMap();
73
74         WRAPPERTYPE.put(Boolean.TYPE, Boolean JavaDoc.class);
75         WRAPPERTYPE.put(Character.TYPE, Character JavaDoc.class);
76         WRAPPERTYPE.put(Byte.TYPE, Byte JavaDoc.class);
77         WRAPPERTYPE.put(Short.TYPE, Short JavaDoc.class);
78         WRAPPERTYPE.put(Integer.TYPE, Integer JavaDoc.class);
79         WRAPPERTYPE.put(Long.TYPE, Long JavaDoc.class);
80         WRAPPERTYPE.put(Float.TYPE, Float JavaDoc.class);
81         WRAPPERTYPE.put(Double.TYPE, Double JavaDoc.class);
82     }
83
84     /** returns object as Double if possible, null otherwise. */
85     
86     public static final Double JavaDoc isDouble(Object JavaDoc object)
87     {
88         if (object != null)
89         {
90             if (object instanceof Double JavaDoc)
91             {
92                 return (Double JavaDoc)object;
93             }
94             else
95             {
96                 try
97                 {
98                     return Double.valueOf(object.toString());
99                 }
100                 catch (Exception JavaDoc e)
101                 {
102                 }
103             }
104         }
105
106         return null;
107     }
108
109     /** returns object as Float if possible, null otherwise. */
110     
111     public static final Float JavaDoc isFloat(Object JavaDoc object)
112     {
113         if (object != null)
114         {
115             if (object instanceof Float JavaDoc)
116             {
117                 return (Float JavaDoc)object;
118             }
119             else
120             {
121                 try
122                 {
123                     return Float.valueOf(object.toString());
124                 }
125                 catch (Exception JavaDoc e)
126                 {
127                 }
128             }
129         }
130
131         return null;
132     }
133
134     /** returns object as Long if possible, null otherwise. */
135     
136     public static final Long JavaDoc isLong(Object JavaDoc object)
137     {
138         if (object != null)
139         {
140             if (object instanceof Long JavaDoc)
141             {
142                 return (Long JavaDoc)object;
143             }
144             else
145             {
146                 try
147                 {
148                     return new Long JavaDoc(((Double JavaDoc)isDouble(object)).longValue());
149                 }
150                 catch (Exception JavaDoc e)
151                 {
152                 }
153             }
154         }
155         
156         return null;
157     }
158
159     /** returns object as Integer if possible, null otherwise. */
160     
161     public static final Integer JavaDoc isInteger(Object JavaDoc object)
162     {
163         if (object != null)
164         {
165             if (object instanceof Integer JavaDoc)
166             {
167                 return (Integer JavaDoc)object;
168             }
169             else
170             {
171                 try
172                 {
173                     return new Integer JavaDoc(((Long JavaDoc)isLong(object)).intValue());
174                 }
175                 catch (Exception JavaDoc e)
176                 {
177                 }
178             }
179         }
180         
181         return null;
182     }
183
184     /** returns object as Short if possible, null otherwise. */
185     
186     public static final Short JavaDoc isShort(Object JavaDoc object)
187     {
188         if (object != null)
189         {
190             if (object instanceof Short JavaDoc)
191             {
192                 return (Short JavaDoc)object;
193             }
194             else
195             {
196                 try
197                 {
198                     return new Short JavaDoc(((Long JavaDoc)isLong(object)).shortValue());
199                 }
200                 catch (Exception JavaDoc e)
201                 {
202                 }
203             }
204         }
205         
206         return null;
207     }
208
209     /** returns object as Byte if possible, null otherwise. */
210     
211     public static final Byte JavaDoc isByte(Object JavaDoc object)
212     {
213         if (object != null)
214         {
215             if (object instanceof Byte JavaDoc)
216             {
217                 return (Byte JavaDoc)object;
218             }
219             else
220             {
221                 try
222                 {
223                     return new Byte JavaDoc(((Long JavaDoc)isLong(object)).byteValue());
224                 }
225                 catch (Exception JavaDoc e)
226                 {
227                 }
228             }
229         }
230         
231         return null;
232     }
233
234     /** returns object as String if possible, null otherwise. */
235
236     public static final String JavaDoc isString(Object JavaDoc object)
237     {
238         if (object != null)
239         {
240             try
241             {
242                 if (object instanceof InputStream)
243                 {
244                     return StringUtil.toBinaryString(IOUtil.readAll((InputStream)object));
245                 }
246                 else if (object instanceof Reader)
247                 {
248                     return new String JavaDoc(IOUtil.readAll((Reader)object));
249                 }
250                 else if (object instanceof Node)
251                 {
252                     Node node = (Node)object;
253
254                     Transformer transformer = TransformerFactory.newInstance().newTransformer();
255                     transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
256                     
257                     StringWriter writer = new StringWriter();
258                     
259                     Source source = new DOMSource(node);
260                     Result result = new StreamResult(writer);
261                     
262                     transformer.transform(source, result);
263
264                     return writer.toString();
265                 }
266                 else
267                 {
268                     try
269                     {
270                         if (object instanceof javax.mail.internet.MimeMessage JavaDoc)
271                         {
272                             ByteArrayOutputStream bOut = new ByteArrayOutputStream();
273                             
274                             ((javax.mail.internet.MimeMessage JavaDoc)object).writeTo(bOut);
275                             
276                             return bOut.toString();
277                         }
278                     }
279                     catch (Exception JavaDoc ee)
280                     {
281                     }
282
283                     return object.toString();
284                 }
285             }
286             catch (Exception JavaDoc e)
287             {
288             }
289         }
290
291         return null;
292     }
293
294     /** returns object as Boolean if possible, null otherwise. */
295
296     public static final Boolean JavaDoc isBoolean(Object JavaDoc object)
297     {
298         if (object != null)
299         {
300             if (object instanceof Boolean JavaDoc)
301             {
302                 return (Boolean JavaDoc)object;
303             }
304             else
305             {
306                 try
307                 {
308                     return Boolean.valueOf(object.toString());
309                 }
310                 catch (Exception JavaDoc e)
311                 {
312                 }
313             }
314         }
315
316         return null;
317     }
318
319     /** returns true if object is boolean "true" or null */
320
321     public static final boolean isTrue(Object JavaDoc object)
322     {
323         Boolean JavaDoc b = isBoolean(object);
324
325         return ((b != null) && (b.booleanValue()));
326     }
327
328     /** returns true if object is boolean "false" or null */
329
330     public static final boolean isFalse(Object JavaDoc object)
331     {
332         Boolean JavaDoc b = isBoolean(object);
333
334         return ((b != null) && (!b.booleanValue()));
335     }
336
337     /** returns object as Character if possible, null otherwise. */
338     
339     public static final Character JavaDoc isCharacter(Object JavaDoc object)
340     {
341         if (object != null)
342         {
343             if (object instanceof Character JavaDoc)
344             {
345                 return (Character JavaDoc)object;
346             }
347             else
348             {
349                 String JavaDoc s = object.toString();
350                 
351                 if (s.length() > 0)
352                 {
353                     return new Character JavaDoc(s.charAt(0));
354                 }
355             }
356         }
357         
358         return null;
359     }
360
361     /** returns object as Object[] if object is an array, null otherwise */
362
363     public static final Object JavaDoc[] isArray(Object JavaDoc object)
364     {
365         if (object != null)
366         {
367             if (object instanceof Object JavaDoc[])
368             {
369                 return (Object JavaDoc[])object;
370             }
371             else if (object instanceof Collection)
372             {
373                 return ((Collection)object).toArray();
374             }
375             else if (object.getClass().isArray())
376             {
377                 int i = Array.getLength(object);
378
379                 Object JavaDoc[] array = new Object JavaDoc[i];
380                 
381                 while (--i >= 0)
382                 {
383                     array[i] = Array.get(object, i);
384                 }
385
386                 return array;
387             }
388         }
389
390         return null;
391     }
392
393     /** returns object as list of Strings if possible, null otherwise */
394
395     public static final String JavaDoc[] isStringArray(Object JavaDoc object)
396     {
397         String JavaDoc[] s = null;
398
399         if (object != null)
400         {
401             if (object instanceof String JavaDoc[])
402             {
403                 s = (String JavaDoc[])object;
404             }
405             else if (object instanceof Object JavaDoc[])
406             {
407                 Object JavaDoc[] array = (Object JavaDoc[])object;
408                 int arraySize = array.length;
409
410                 s = new String JavaDoc[arraySize];
411
412                 for (int i = arraySize; --i >=0; )
413                 {
414                     Object JavaDoc a = array[i];
415
416                     s[i] = (a != null) ? a.toString() : null;
417                 }
418             }
419             else if (object instanceof List)
420             {
421                 List list = (List)object;
422                 int listSize = list.size();
423
424                 s = new String JavaDoc[listSize];
425
426                 for (int i = listSize; --i >=0; )
427                 {
428                     Object JavaDoc a = list.get(i);
429
430                     s[i] = (a != null) ? a.toString() : null;
431                 }
432             }
433         }
434
435         return s;
436     }
437
438     /** returns object as List if possible, null otherwise. */
439
440     public static final List isList(Object JavaDoc object)
441     {
442         if (object != null)
443         {
444             if (object instanceof List)
445             {
446                 return (List)object;
447             }
448             else
449             {
450                 Object JavaDoc[] array = isArray(object);
451
452                 if (array != null)
453                 {
454                     return Arrays.asList(array);
455                 }
456             }
457         }
458
459         return null;
460     }
461
462     /** returns list from list/array or a string with separator/escape */
463
464     public static final List isStringList(Object JavaDoc object, char separator, char escape)
465     {
466         List list = null;
467
468         if (object != null)
469         {
470             list = isList(object);
471
472             if (list == null)
473             {
474                 list = StringUtil.split(object.toString(), separator, escape);
475             }
476         }
477
478         return list;
479     }
480     
481     /** returns as Collection if possible, null otherwise */
482
483     public static final Collection isCollection(Object JavaDoc object)
484     {
485         if (object instanceof Collection)
486         {
487             return (Collection)object;
488         }
489         else
490         {
491             return isList(object);
492         }
493     }
494
495     /** returns as URI if possible, null otherwise */
496
497     public static final URI isURI(Object JavaDoc object)
498     {
499         URI uri = null;
500
501         if (object != null)
502         {
503             try
504             {
505                 if (object instanceof URI)
506                 {
507                     uri = (URI)object;
508                 }
509                 else
510                 {
511                     uri = new URI(object.toString());
512                 }
513             }
514             catch (Exception JavaDoc e)
515             {
516                 uri = null;
517             }
518         }
519
520         return uri;
521     }
522
523     /** returns as URL if possible, null otherwise */
524
525     public static final URL isURL(Object JavaDoc object, URL contextURL)
526     {
527         URL url = null;
528
529         if (object != null)
530         {
531             try
532             {
533                 url = new URL(contextURL, object.toString());
534             }
535             catch (Exception JavaDoc e)
536             {
537                 url = null;
538             }
539         }
540
541         return url;
542     }
543
544     /** returns as URL if possible, null otherwise */
545
546     public static final URL isURL(Object JavaDoc object)
547     {
548         URL url = null;
549
550         if (object != null)
551         {
552             try
553             {
554                 url = new URL(object.toString());
555             }
556             catch (Exception JavaDoc e)
557             {
558                 url = null;
559             }
560         }
561
562         return url;
563     }
564
565     /** returns as File if possible, otherwise null */
566
567     public static final File isFile(Object JavaDoc object, Object JavaDoc parentObject)
568     {
569         File file = null;
570
571         if (object != null)
572         {
573             try
574             {
575                 if (object instanceof URI)
576                 {
577                     file = new File((URI)object);
578                 }
579                 else if (object instanceof File)
580                 {
581                     file = (File)object;
582                 }
583                 else
584                 {
585                     file = new File(object.toString());
586                 }
587
588                 if (parentObject != null)
589                 {
590                     file = new File(isFile(parentObject), file.toString());
591                 }
592             }
593             catch (Exception JavaDoc e)
594             {
595                 file = null;
596             }
597         }
598
599         return file;
600     }
601
602     public static final File isFile(Object JavaDoc object)
603     {
604         return isFile(object, null);
605     }
606
607     /** converts to NestedMap */
608
609     public static final NestedMap isNestedMap(Object JavaDoc object)
610     {
611         if (object instanceof NestedMap)
612         {
613             return (NestedMap)object;
614         }
615         else
616         {
617             try
618             {
619                 return new NestedMap(object);
620             }
621             catch (Exception JavaDoc e)
622             {
623                 return null;
624             }
625         }
626     }
627
628     /** returns Locale for given spec (map or string). If object is null or empty, default locale is returned. */
629
630     public static final Locale isLocale(Object JavaDoc object)
631     {
632         if (object instanceof Locale)
633         {
634             return (Locale)object;
635         }
636         else
637         {
638             NestedMap specMap = isNestedMap(object);
639
640             String JavaDoc language = specMap.getString("language", "");
641             String JavaDoc country = specMap.getString("country", "");
642             String JavaDoc variant = specMap.getString("variant", "");
643                 
644             return new Locale(language, country, variant);
645         }
646     }
647
648     /** returns TimezZone for given spec (map or string). If object is null or empty, default TimeZone is returned. */
649
650     public static final TimeZone isTimeZone(Object JavaDoc object)
651     {
652         if (object instanceof TimeZone)
653         {
654             return (TimeZone)object;
655         }
656         else
657         {
658             NestedMap specMap = isNestedMap(object);
659
660             String JavaDoc id = specMap.getString("id", "");
661             
662             if (id == null)
663             {
664                 return TimeZone.getDefault();
665             }
666             else
667             {
668                 return TimeZone.getTimeZone(id);
669             }
670         }
671     }
672
673
674     /** returns object as Calendar if possible */
675
676     public static final Calendar isCalendar(Object JavaDoc object, String JavaDoc pattern, Locale locale, TimeZone timeZone) throws Exception JavaDoc
677     {
678         Calendar calendar = null;
679
680         if (object != null)
681         {
682             if (object instanceof Calendar)
683             {
684                 calendar = (Calendar)object;
685             }
686             else
687             {
688                 if (locale == null)
689                 {
690                     locale = Locale.getDefault();
691                 }
692
693                 calendar = Calendar.getInstance(locale);
694
695                 Date date = isDate(object, pattern, locale, timeZone);
696
697                 calendar.setTime(date);
698             }
699         }
700
701         return calendar;
702     }
703
704     /** returns object as Date if possible.*/
705
706     public static final Date isDate(Object JavaDoc object, String JavaDoc pattern, Locale locale, TimeZone timeZone) throws Exception JavaDoc
707     {
708         Date date = null;
709
710         if (object != null)
711         {
712             if (object instanceof Date)
713             {
714                 date = (Date)object;
715             }
716             else if (object instanceof Calendar)
717             {
718                 date = ((Calendar)object).getTime();
719             }
720             else
721             {
722                 if (object instanceof Number JavaDoc)
723                 {
724                     Long JavaDoc longObject = (Long JavaDoc)isLong(object);
725
726                     date = new Date();
727                     date.setTime(longObject.longValue());
728                 }
729                 else
730                 {
731                     SimpleDateFormat simpleDateFormat;
732                     
733                     if (pattern == null)
734                     {
735                         simpleDateFormat = new SimpleDateFormat();
736                     }
737                     else
738                     {
739                         simpleDateFormat = new SimpleDateFormat(pattern, locale);
740                     }
741
742                     if (timeZone != null)
743                     {
744                         simpleDateFormat.setTimeZone(timeZone);
745                     }
746                     
747                     ParsePosition parsePosition = new ParsePosition(0);
748                     
749                     String JavaDoc objectString = object.toString();
750                     
751                     date = simpleDateFormat.parse(objectString, parsePosition);
752                     
753                     if (parsePosition.getIndex() != objectString.length())
754                     {
755                         date = null;
756                     }
757                 }
758             }
759         }
760
761         return date;
762     }
763
764     /** returns object as number if possible, according to the spec */
765
766     public static final Number JavaDoc isNumber(Object JavaDoc object, String JavaDoc pattern, Locale locale) throws Exception JavaDoc
767     {
768         Number JavaDoc number = null;
769
770         if (object != null)
771         {
772             if (object instanceof Number JavaDoc)
773             {
774                 number = (Number JavaDoc)object;
775             }
776             else
777             {
778                 DecimalFormat decimalFormat;
779
780                 if (pattern == null)
781                 {
782                     decimalFormat = new DecimalFormat();
783                 }
784                 else
785                 {
786                     decimalFormat = new DecimalFormat(pattern, new DecimalFormatSymbols(locale));
787                 }
788
789                 ParsePosition parsePosition = new ParsePosition(0);
790                 
791                 String JavaDoc objectString = object.toString();
792
793                 number = decimalFormat.parse(objectString, parsePosition);
794
795                 if (parsePosition.getIndex() != objectString.length())
796                 {
797                     number = null;
798                 }
799             }
800         }
801
802         return number;
803     }
804
805     /** returns length if possible, -1 otherwise */
806
807     public static final int length(Object JavaDoc object)
808     {
809         if (object != null)
810         {
811             if (object instanceof String JavaDoc)
812             {
813                 return object.toString().length();
814             }
815             else if (object instanceof Collection)
816             {
817                 return ((Collection)object).size();
818             }
819             else if (object.getClass().isArray())
820             {
821                 return Array.getLength(object);
822             }
823         }
824
825         return -1;
826     }
827
828     /** alias for 'length' */
829
830     public static final int size(Object JavaDoc object)
831     {
832         return length(object);
833     }
834
835     /** actual size if object is sparse, otherwise length */
836
837     public static final int getActualSize(Object JavaDoc object)
838     {
839         if (object instanceof SparseObject)
840         {
841             return ((SparseObject)object).getActualSize();
842         }
843         else
844         {
845             return size(object);
846         }
847     }
848
849     /** returns true if given object is either null or "" */
850
851     public static final boolean isEmptyString(Object JavaDoc object)
852     {
853         return ((object == null) || ("".equals(object)));
854     }
855
856     /** loose check for 'emptiness', returns true if the object is null, "", or an empty collection or an array. */
857
858     public static final boolean isEmpty(Object JavaDoc object)
859     {
860         if (isEmptyString(object))
861         {
862             return true;
863         }
864         else if (object instanceof Collection)
865         {
866             return ((Collection)object).isEmpty();
867         }
868         else if (object.getClass().isArray())
869         {
870             return (Array.getLength(object) == 0);
871         }
872         else
873         {
874             return false;
875         }
876     }
877
878     /** convert object to given class if possible, null otherwise. If classObject is a primitive or its wrapper class (say, "int" or "Integer"), then tries to convert to the wrapper class. */
879
880     public static final Object JavaDoc isClass(Object JavaDoc object, Class JavaDoc classObject)
881     {
882         if (classObject.isInstance(object))
883         {
884             return object;
885         }
886         else
887         {
888             try
889             {
890                 if ((classObject == Boolean.TYPE) || (classObject == Boolean JavaDoc.class))
891                 {
892                     return Boolean.valueOf(object.toString());
893                 }
894                 else if ((classObject == Byte.TYPE) || (classObject == Byte JavaDoc.class))
895                 {
896                     return Byte.valueOf(object.toString());
897                 }
898                 else if ((classObject == Short.TYPE) || (classObject == Short JavaDoc.class))
899                 {
900                     return Short.valueOf(object.toString());
901                 }
902                 else if ((classObject == Integer.TYPE) || (classObject == Integer JavaDoc.class))
903                 {
904                     return Integer.valueOf(object.toString());
905                 }
906                 else if ((classObject == Long.TYPE) || (classObject == Long JavaDoc.class))
907                 {
908                     return Long.valueOf(object.toString());
909                 }
910                 else if ((classObject == Float.TYPE) || (classObject == Float JavaDoc.class))
911                 {
912                     return Float.valueOf(object.toString());
913                 }
914                 else if ((classObject == Double.TYPE) || (classObject == Double JavaDoc.class))
915                 {
916                     return Double.valueOf(object.toString());
917                 }
918                 else if ((classObject == Character.TYPE) || (classObject == Character JavaDoc.class))
919                 {
920                     return new Character JavaDoc(object.toString().charAt(0));
921                 }
922                 else if (classObject == String JavaDoc.class)
923                 {
924                     return object.toString();
925                 }
926             }
927             catch (Exception JavaDoc e)
928             {
929             }
930         }
931
932         return null;
933     }
934
935     /** tries to create an instance of classObject with given args. Exact type matches take precedence. */
936
937     public static final Object JavaDoc newInstance(Class JavaDoc classObject, Object JavaDoc[] args) throws Exception JavaDoc
938     {
939         if (args == null)
940         {
941             return classObject.newInstance();
942         }
943         
944         Constructor[] constructors = classObject.getConstructors();
945
946         Object JavaDoc[] cArgs = new Object JavaDoc[args.length];
947
948         // exact matches
949

950         for (int i = 0; i < constructors.length; i ++)
951         {
952             Constructor constructor = constructors[i];
953             Class JavaDoc[] parameterTypes = constructor.getParameterTypes();
954
955             if (parameterTypes.length == args.length)
956             {
957                 boolean isMatching = true;
958                 
959                 for (int j = 0; j < parameterTypes.length; j ++)
960                 {
961                     Class JavaDoc parameterClass = parameterTypes[j];
962                     Class JavaDoc wrapperClass = (Class JavaDoc)WRAPPERTYPE.get(parameterClass);
963
964                     if (wrapperClass != null)
965                     {
966                         parameterClass = wrapperClass;
967                     }
968                     
969                     Object JavaDoc arg = args[j];
970                     
971                     if (arg != null)
972                     {
973                         if (!parameterClass.isInstance(arg))
974                         {
975                             isMatching = false;
976                             break;
977                         }
978                     }
979                     
980                     cArgs[j] = arg;
981                 }
982                 
983                 if (isMatching)
984                 {
985                     return constructor.newInstance(cArgs);
986                 }
987             }
988         }
989
990         // matching with conversion
991

992         for (int i = 0; i < constructors.length; i ++)
993         {
994             Constructor constructor = constructors[i];
995             Class JavaDoc[] parameterTypes = constructor.getParameterTypes();
996
997             if (parameterTypes.length == args.length)
998             {
999                 boolean isMatching = true;
1000                
1001                for (int j = 0; j < parameterTypes.length; j ++)
1002                {
1003                    Object JavaDoc arg = args[j];
1004                    
1005                    if (arg != null)
1006                    {
1007                        arg = isClass(arg, parameterTypes[j]);
1008                        
1009                        if (arg == null)
1010                        {
1011                            isMatching = false;
1012                            break;
1013                        }
1014                    }
1015                    
1016                    cArgs[j] = arg;
1017                }
1018                
1019                if (isMatching)
1020                {
1021                    return constructor.newInstance(cArgs);
1022                }
1023            }
1024        }
1025
1026        return null;
1027    }
1028
1029    /** converts given object to Pattern */
1030
1031    public static final Pattern isPattern(Object JavaDoc object)
1032    {
1033        Pattern pattern = null;
1034
1035        try
1036        {
1037            if (object instanceof Pattern)
1038            {
1039                pattern = (Pattern)object;
1040            }
1041            else if (!isEmptyString(object))
1042            {
1043                pattern = Pattern.compile(object.toString());
1044            }
1045        }
1046        catch (Exception JavaDoc e)
1047        {
1048        }
1049
1050        return pattern;
1051    }
1052
1053    /** returns Class with given className. ClassName can be primitive type (e.g., "int", "double", etc.). If className is not primitive but doesn't contain a ".", then defaultPrefix is added to the className. If defaultPrefix = null, then "java.lang." is assumed.*/
1054
1055    public static final Class JavaDoc forName(String JavaDoc className, String JavaDoc defaultPrefix) throws Exception JavaDoc
1056    {
1057        int dimensions = 0;
1058
1059        for (;;)
1060        {
1061            int arrayIndex = className.lastIndexOf("[]");
1062
1063            if (arrayIndex == -1)
1064            {
1065                break;
1066            }
1067            else
1068            {
1069                dimensions ++;
1070                className = className.substring(0, arrayIndex);
1071            }
1072        }
1073
1074        Class JavaDoc classObject = null;
1075
1076        if (className.indexOf('.') >= 0)
1077        {
1078            classObject = Class.forName(className);
1079        }
1080        else
1081        {
1082            Class JavaDoc primitiveClass = (Class JavaDoc)(PRIMITIVETYPE.get(className));
1083
1084            if (primitiveClass != null)
1085            {
1086                classObject = primitiveClass;
1087            }
1088            else
1089            {
1090                classObject = Class.forName(defaultPrefix + className);
1091            }
1092        }
1093        
1094        if (dimensions == 0)
1095        {
1096            return classObject;
1097        }
1098        else
1099        {
1100            return (Array.newInstance(classObject, new int[dimensions])).getClass();
1101        }
1102    }
1103
1104    /** forName with default "java.lang." prefix */
1105
1106    public static final Class JavaDoc forName(String JavaDoc className) throws Exception JavaDoc
1107    {
1108        return forName(className, "java.lang.");
1109    }
1110
1111    /** dynamic method call */
1112
1113    public static final Object JavaDoc invoke(Object JavaDoc object, Class JavaDoc classObject, String JavaDoc methodName, Class JavaDoc[] types, Object JavaDoc[] args) throws Exception JavaDoc
1114    {
1115        if (classObject == null)
1116        {
1117            classObject = object.getClass();
1118        }
1119
1120        if ("*".equals(methodName))
1121        {
1122            Constructor c = classObject.getConstructor(types);
1123
1124            return c.newInstance(args);
1125        }
1126        else if (methodName.startsWith("."))
1127        {
1128            Field field = classObject.getDeclaredField(methodName.substring(1));
1129            return field.get(object);
1130        }
1131        else
1132        {
1133            Method m = classObject.getMethod(methodName, types);
1134
1135            return m.invoke(object, args);
1136        }
1137    }
1138
1139    /** method invoker */
1140
1141    public final static String JavaDoc OBJECT = "object";
1142    public final static String JavaDoc CLASS = "class";
1143    public final static String JavaDoc METHOD = "method";
1144    public final static String JavaDoc TYPE = "type";
1145    public final static String JavaDoc VALUE = "value";
1146    public final static String JavaDoc OBJECTPROPERTY = "objectProperty";
1147
1148    public static Object JavaDoc invoke(NestedMap map) throws Exception JavaDoc
1149    {
1150        Object JavaDoc returnValue = null;
1151
1152        Object JavaDoc object = map.get(OBJECT);
1153        List list = map.getSubList(false);
1154
1155        Class JavaDoc[] argTypes = null;
1156        Object JavaDoc[] argValues = null;
1157
1158        if (list != null)
1159        {
1160            int listSize = list.size();
1161
1162            argTypes = new Class JavaDoc[listSize];
1163            argValues = new Object JavaDoc[listSize];
1164
1165            for (int i = 0; i < listSize; i ++)
1166            {
1167                Object JavaDoc argSpec = list.get(i);
1168
1169                Object JavaDoc argType = null;
1170                Object JavaDoc argValue = argSpec;
1171
1172                if (argSpec instanceof Map)
1173                {
1174                    Map argMap = (Map)argSpec;
1175
1176                    argType = argMap.get(TYPE);
1177                    argValue = argMap.get(VALUE);
1178                }
1179
1180                Class JavaDoc argClass = Object JavaDoc.class;
1181
1182                if (argType instanceof String JavaDoc)
1183                {
1184                    argClass = TypeUtil.forName(argType.toString());
1185                }
1186                else if (argType instanceof Class JavaDoc)
1187                {
1188                    argClass = (Class JavaDoc)argType;
1189                }
1190                else if (argType != null)
1191                {
1192                    argClass = argType.getClass();
1193                }
1194                else if (argValue != null)
1195                {
1196                    argClass = argValue.getClass();
1197                }
1198
1199                argTypes[i] = argClass;
1200
1201                argValues[i] = TypeUtil.isClass(argValue, argClass);
1202            }
1203        }
1204
1205        String JavaDoc methodName = (String JavaDoc)map.get(METHOD);
1206
1207        Class JavaDoc classObject = null;
1208
1209        Object JavaDoc classSpec = map.get(CLASS);
1210
1211        if (classSpec != null)
1212        {
1213            if (classSpec instanceof Class JavaDoc)
1214            {
1215                classObject = (Class JavaDoc)classSpec;
1216            }
1217            else
1218            {
1219                classObject = TypeUtil.forName(classSpec.toString());
1220            }
1221        }
1222
1223        return invoke(object, classObject, methodName, argTypes, argValues);
1224    }
1225
1226    /** invoke method on an object instance */
1227
1228    public static Object JavaDoc invoke(Object JavaDoc object, NestedMap map, String JavaDoc objectProperty) throws Exception JavaDoc
1229    {
1230        map.put(objectProperty, object);
1231
1232        return invoke(map);
1233    }
1234
1235    /** invoke method on an object instance */
1236
1237    public static Object JavaDoc invoke(Object JavaDoc object, NestedMap map) throws Exception JavaDoc
1238    {
1239        return invoke(object, map, map.getString(OBJECTPROPERTY, OBJECT));
1240    }
1241
1242    /** sublist, with index handling */
1243
1244    public static List subList(List list, int start, int end)
1245    {
1246        if (list != null)
1247        {
1248            int length = list.size();
1249            
1250            if (start < 0)
1251            {
1252                start = length + start;
1253            }
1254            
1255            if (end <= 0)
1256            {
1257                end = length + end;
1258            }
1259            
1260            if (start < 0)
1261            {
1262                start = 0;
1263            }
1264            
1265            if (end > length)
1266            {
1267                end = length;
1268            }
1269            
1270            if (end <= start)
1271            {
1272                list = new ArrayList();
1273            }
1274            else
1275            {
1276                list = list.subList(start, end);
1277            }
1278        }
1279
1280        return list;
1281    }
1282
1283    /** Returns object as Node if possible, otherwise null. Tries to decode as NodeMap if not a Node. */
1284    
1285    public static Node isNode(Object JavaDoc object, Document document) throws Exception JavaDoc
1286    {
1287        if (object == null)
1288        {
1289            return null;
1290        }
1291        else if (object instanceof Node)
1292        {
1293            return (Node)object;
1294        }
1295        else
1296        {
1297            return XMLUtil.decodeNodeMap(isNestedMap(object), document);
1298        }
1299    }
1300
1301    public static Node isNode(Object JavaDoc object) throws Exception JavaDoc
1302    {
1303        return isNode(object, null);
1304    }
1305}
1306
Popular Tags