KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > utils > JavaUtils


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.axis.utils;
18
19 import org.apache.axis.attachments.AttachmentPart;
20 import org.apache.axis.attachments.OctetStream;
21 import org.apache.axis.components.image.ImageIO;
22 import org.apache.axis.components.image.ImageIOFactory;
23 import org.apache.axis.components.logger.LogFactory;
24 import org.apache.axis.types.HexBinary;
25 import org.apache.commons.logging.Log;
26
27 import javax.activation.DataHandler JavaDoc;
28 import javax.xml.soap.SOAPException JavaDoc;
29 import javax.xml.transform.Source JavaDoc;
30 import javax.xml.transform.stream.StreamSource JavaDoc;
31 import java.awt.*;
32 import java.beans.Introspector JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.io.InputStream JavaDoc;
35 import java.io.StringReader JavaDoc;
36 import java.io.ByteArrayOutputStream JavaDoc;
37 import java.lang.reflect.Array JavaDoc;
38 import java.lang.reflect.Field JavaDoc;
39 import java.text.Collator JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.Arrays JavaDoc;
42 import java.util.Calendar JavaDoc;
43 import java.util.Collection JavaDoc;
44 import java.util.Date JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.HashSet JavaDoc;
47 import java.util.Hashtable JavaDoc;
48 import java.util.Iterator JavaDoc;
49 import java.util.List JavaDoc;
50 import java.util.Locale JavaDoc;
51 import java.util.Set JavaDoc;
52
53 /** Utility class to deal with Java language related issues, such
54  * as type conversions.
55  *
56  * @author Glen Daniels (gdaniels@apache.org)
57  */

58 public class JavaUtils
59 {
60     private JavaUtils() {
61     }
62
63     protected static Log log =
64         LogFactory.getLog(JavaUtils.class.getName());
65     
66     public static final char NL = '\n';
67
68     public static final char CR = '\r';
69
70     /**
71      * The prefered line separator
72      */

73     public static final String JavaDoc LS = System.getProperty("line.separator",
74                                                        (new Character JavaDoc(NL)).toString());
75
76
77     public static Class JavaDoc getWrapperClass(Class JavaDoc primitive)
78     {
79         if (primitive == int.class)
80             return java.lang.Integer JavaDoc.class;
81         else if (primitive == short.class)
82             return java.lang.Short JavaDoc.class;
83         else if (primitive == boolean.class)
84             return java.lang.Boolean JavaDoc.class;
85         else if (primitive == byte.class)
86             return java.lang.Byte JavaDoc.class;
87         else if (primitive == long.class)
88             return java.lang.Long JavaDoc.class;
89         else if (primitive == double.class)
90             return java.lang.Double JavaDoc.class;
91         else if (primitive == float.class)
92             return java.lang.Float JavaDoc.class;
93         else if (primitive == char.class)
94             return java.lang.Character JavaDoc.class;
95         
96         return null;
97     }
98     
99     public static String JavaDoc getWrapper(String JavaDoc primitive)
100     {
101         if (primitive.equals("int"))
102             return "Integer";
103         else if (primitive.equals("short"))
104             return "Short";
105         else if (primitive.equals("boolean"))
106             return "Boolean";
107         else if (primitive.equals("byte"))
108             return "Byte";
109         else if (primitive.equals("long"))
110             return "Long";
111         else if (primitive.equals("double"))
112             return "Double";
113         else if (primitive.equals("float"))
114             return "Float";
115         else if (primitive.equals("char"))
116             return "Character";
117         
118         return null;
119     }
120
121     public static Class JavaDoc getPrimitiveClass(Class JavaDoc wrapper)
122     {
123         if (wrapper == java.lang.Integer JavaDoc.class)
124             return int.class;
125         else if (wrapper == java.lang.Short JavaDoc.class)
126             return short.class;
127         else if (wrapper == java.lang.Boolean JavaDoc.class)
128             return boolean.class;
129         else if (wrapper == java.lang.Byte JavaDoc.class)
130             return byte.class;
131         else if (wrapper == java.lang.Long JavaDoc.class)
132             return long.class;
133         else if (wrapper == java.lang.Double JavaDoc.class)
134             return double.class;
135         else if (wrapper == java.lang.Float JavaDoc.class)
136             return float.class;
137         else if (wrapper == java.lang.Character JavaDoc.class)
138             return char.class;
139         
140         return null;
141     }
142
143     /*
144          * Any builtin type that has a constructor that takes a String is a basic
145          * type.
146          * This is for optimization purposes, so that we don't introspect
147          * primitive java types or some basic Axis types.
148          */

149     public static boolean isBasic(Class JavaDoc javaType) {
150         return (javaType.isPrimitive() ||
151                 javaType == String JavaDoc.class ||
152                 javaType == Boolean JavaDoc.class ||
153                 javaType == Float JavaDoc.class ||
154                 javaType == Double JavaDoc.class ||
155                 Number JavaDoc.class.isAssignableFrom(javaType) ||
156                 javaType == org.apache.axis.types.Day.class ||
157                 javaType == org.apache.axis.types.Duration.class ||
158                 javaType == org.apache.axis.types.Entities.class ||
159                 javaType == org.apache.axis.types.Entity.class ||
160                 javaType == HexBinary.class ||
161                 javaType == org.apache.axis.types.Id.class ||
162                 javaType == org.apache.axis.types.IDRef.class ||
163                 javaType == org.apache.axis.types.IDRefs.class ||
164                 javaType == org.apache.axis.types.Language.class ||
165                 javaType == org.apache.axis.types.Month.class ||
166                 javaType == org.apache.axis.types.MonthDay.class ||
167                 javaType == org.apache.axis.types.Name.class ||
168                 javaType == org.apache.axis.types.NCName.class ||
169                 javaType == org.apache.axis.types.NegativeInteger.class ||
170                 javaType == org.apache.axis.types.NMToken.class ||
171                 javaType == org.apache.axis.types.NMTokens.class ||
172                 javaType == org.apache.axis.types.NonNegativeInteger.class ||
173                 javaType == org.apache.axis.types.NonPositiveInteger.class ||
174                 javaType == org.apache.axis.types.NormalizedString.class ||
175                 javaType == org.apache.axis.types.PositiveInteger.class ||
176                 javaType == org.apache.axis.types.Time.class ||
177                 javaType == org.apache.axis.types.Token.class ||
178                 javaType == org.apache.axis.types.UnsignedByte.class ||
179                 javaType == org.apache.axis.types.UnsignedInt.class ||
180                 javaType == org.apache.axis.types.UnsignedLong.class ||
181                 javaType == org.apache.axis.types.UnsignedShort.class ||
182                 javaType == org.apache.axis.types.URI.class ||
183                 javaType == org.apache.axis.types.Year.class ||
184                 javaType == org.apache.axis.types.YearMonth.class);
185     }
186
187     /**
188      * It the argument to the convert(...) method implements
189      * the ConvertCache interface, the convert(...) method
190      * will use the set/get methods to store and retrieve
191      * converted values.
192      **/

193     public interface ConvertCache {
194         /**
195          * Set/Get converted values of the convert method.
196          **/

197         public void setConvertedValue(Class JavaDoc cls, Object JavaDoc value);
198         public Object JavaDoc getConvertedValue(Class JavaDoc cls);
199         /**
200          * Get the destination array class described by the xml
201          **/

202         public Class JavaDoc getDestClass();
203     }
204
205     /** Utility function to convert an Object to some desired Class.
206      *
207      * Right now this works for:
208      * arrays <-> Lists,
209      * Holders <-> held values
210      * @param arg the array to convert
211      * @param destClass the actual class we want
212      */

213     public static Object JavaDoc convert(Object JavaDoc arg, Class JavaDoc destClass)
214     {
215         if (destClass == null) {
216             return arg;
217         }
218
219         Class JavaDoc argHeldType = null;
220         if (arg != null) {
221             argHeldType = getHolderValueType(arg.getClass());
222         }
223
224         if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass())) {
225             return arg;
226         }
227
228         if (log.isDebugEnabled()) {
229             String JavaDoc clsName = "null";
230             if (arg != null) clsName = arg.getClass().getName();
231             log.debug( Messages.getMessage("convert00", clsName, destClass.getName()));
232         }
233
234         // See if a previously converted value is stored in the argument.
235
Object JavaDoc destValue = null;
236         if (arg instanceof ConvertCache) {
237             destValue = (( ConvertCache) arg).getConvertedValue(destClass);
238             if (destValue != null)
239                 return destValue;
240         }
241
242         // Get the destination held type or the argument held type if they exist
243
Class JavaDoc destHeldType = getHolderValueType(destClass);
244
245         // Convert between Axis special purpose HexBinary and byte[]
246
if (arg instanceof HexBinary &&
247             destClass == byte[].class) {
248             return ((HexBinary) arg).getBytes();
249         } else if (arg instanceof byte[] &&
250                    destClass == HexBinary.class) {
251             return new HexBinary((byte[]) arg);
252         }
253
254         // Convert between Calendar and Date
255
if (arg instanceof Calendar JavaDoc && destClass == Date JavaDoc.class) {
256             return ((Calendar JavaDoc) arg).getTime();
257         }
258         if (arg instanceof Date JavaDoc && destClass == Calendar JavaDoc.class) {
259             Calendar JavaDoc calendar = Calendar.getInstance();
260             calendar.setTime((Date JavaDoc) arg);
261             return calendar;
262         }
263
264         // Convert between Calendar and java.sql.Date
265
if (arg instanceof Calendar JavaDoc && destClass == java.sql.Date JavaDoc.class) {
266             return new java.sql.Date JavaDoc(((Calendar JavaDoc) arg).getTime().getTime());
267         }
268
269         // Convert between HashMap and Hashtable
270
if (arg instanceof HashMap JavaDoc && destClass == Hashtable JavaDoc.class) {
271             return new Hashtable JavaDoc((HashMap JavaDoc)arg);
272         }
273
274         // Convert an AttachmentPart to the given destination class.
275
if (isAttachmentSupported() &&
276                 (arg instanceof InputStream JavaDoc || arg instanceof AttachmentPart || arg instanceof DataHandler JavaDoc)) {
277             try {
278                 String JavaDoc destName = destClass.getName();
279                 if (destClass == String JavaDoc.class
280                         || destClass == OctetStream.class
281                         || destClass == byte[].class
282                         || destClass == Image.class
283                         || destClass == Source JavaDoc.class
284                         || destClass == DataHandler JavaDoc.class
285                         || destName.equals("javax.mail.internet.MimeMultipart")) {
286                     DataHandler JavaDoc handler = null;
287                     if (arg instanceof AttachmentPart) {
288                         handler = ((AttachmentPart) arg).getDataHandler();
289                     }
290                     else if (arg instanceof DataHandler JavaDoc) {
291                         handler = (DataHandler JavaDoc) arg;
292                     }
293                     if (destClass == Image.class) {
294                         // Note: An ImageIO component is required to process an Image
295
// attachment, but if the image would be null
296
// (is.available == 0) then ImageIO component isn't needed
297
// and we can return null.
298
InputStream JavaDoc is = (InputStream JavaDoc) handler.getContent();
299                         if (is.available() == 0) {
300                             return null;
301                         }
302                         else {
303                             ImageIO imageIO = ImageIOFactory.getImageIO();
304                             if (imageIO != null) {
305                                 return getImageFromStream(is);
306                             }
307                             else {
308                                 log.info(Messages.getMessage("needImageIO"));
309                                 return arg;
310                             }
311                         }
312                     }
313                     else if (destClass == javax.xml.transform.Source JavaDoc.class) {
314                         // For a reason unknown to me, the handler's
315
// content is a String. Convert it to a
316
// StreamSource.
317
return new StreamSource JavaDoc(new StringReader JavaDoc(
318                                 (String JavaDoc) handler.getContent()));
319                     }
320                     else if (destClass == OctetStream.class || destClass == byte[].class) {
321                         InputStream JavaDoc in = null;
322                         if (arg instanceof InputStream JavaDoc) {
323                             in = (InputStream JavaDoc) arg;
324                         } else {
325                             in = (InputStream JavaDoc)handler.getContent();
326                         }
327                         ByteArrayOutputStream baos = new ByteArrayOutputStream();
328                         int byte1 = -1;
329                         while((byte1 = in.read())!=-1)
330                             baos.write(byte1);
331                         return new OctetStream(baos.toByteArray());
332                     }
333                     else if (destClass == DataHandler JavaDoc.class) {
334                         return handler;
335                     }
336                     else {
337                         return handler.getContent();
338                     }
339                 }
340             }
341             catch (IOException JavaDoc ioe) {
342             }
343             catch (SOAPException JavaDoc se) {
344             }
345         }
346
347         // If the destination is an array and the source
348
// is a suitable component, return an array with
349
// the single item.
350
if (arg != null &&
351             destClass.isArray() &&
352             !destClass.getComponentType().equals(Object JavaDoc.class) &&
353             destClass.getComponentType().isAssignableFrom(arg.getClass())) {
354             Object JavaDoc array =
355                 Array.newInstance(destClass.getComponentType(), 1);
356             Array.set(array, 0, arg);
357             return array;
358         }
359
360         // in case destClass is array and arg is ArrayOfT class. (ArrayOfT -> T[])
361
if (arg != null && destClass.isArray()) {
362             Object JavaDoc newArg = ArrayUtil.convertObjectToArray(arg, destClass);
363             if (newArg == null
364                     || (newArg != ArrayUtil.NON_CONVERTABLE && newArg != arg)) {
365                 return newArg;
366             }
367         }
368                
369         // in case arg is ArrayOfT and destClass is an array. (T[] -> ArrayOfT)
370
if (arg != null && arg.getClass().isArray()) {
371             Object JavaDoc newArg = ArrayUtil.convertArrayToObject(arg, destClass);
372             if (newArg != null)
373                 return newArg;
374         }
375
376         // Return if no conversion is available
377
if (!(arg instanceof Collection JavaDoc ||
378               (arg != null && arg.getClass().isArray())) &&
379             ((destHeldType == null && argHeldType == null) ||
380              (destHeldType != null && argHeldType != null))) {
381             return arg;
382         }
383
384         // Take care of Holder conversion
385
if (destHeldType != null) {
386             // Convert arg into Holder holding arg.
387
Object JavaDoc newArg = convert(arg, destHeldType);
388             Object JavaDoc argHolder = null;
389             try {
390                 argHolder = destClass.newInstance();
391                 setHolderValue(argHolder, newArg);
392                 return argHolder;
393             } catch (Exception JavaDoc e) {
394                 return arg;
395             }
396         } else if (argHeldType != null) {
397             // Convert arg into the held type
398
try {
399                 Object JavaDoc newArg = getHolderValue(arg);
400                 return convert(newArg, destClass);
401             } catch (HolderException e) {
402                 return arg;
403             }
404         }
405
406         // Flow to here indicates that neither arg or destClass is a Holder
407

408         // Check to see if the argument has a prefered destination class.
409
if (arg instanceof ConvertCache &&
410             (( ConvertCache) arg).getDestClass() != destClass) {
411             Class JavaDoc hintClass = ((ConvertCache) arg).getDestClass();
412             if (hintClass != null &&
413                 hintClass.isArray() &&
414                 destClass.isArray() &&
415                 destClass.isAssignableFrom(hintClass)) {
416                 destClass = hintClass;
417                 destValue = ((ConvertCache) arg).getConvertedValue(destClass);
418                 if (destValue != null)
419                     return destValue;
420             }
421         }
422         
423         if (arg == null) {
424             return arg;
425         }
426
427         // The arg may be an array or List
428
int length = 0;
429         if (arg.getClass().isArray()) {
430             length = Array.getLength(arg);
431         } else {
432             length = ((Collection JavaDoc) arg).size();
433         }
434         if (destClass.isArray()) {
435             if (destClass.getComponentType().isPrimitive()) {
436
437                 Object JavaDoc array = Array.newInstance(destClass.getComponentType(),
438                                                  length);
439                 // Assign array elements
440
if (arg.getClass().isArray()) {
441                     for (int i = 0; i < length; i++) {
442                         Array.set(array, i, Array.get(arg, i));
443                     }
444                 } else {
445                     int idx = 0;
446                     for (Iterator JavaDoc i = ((Collection JavaDoc)arg).iterator();
447                             i.hasNext();) {
448                         Array.set(array, idx++, i.next());
449                     }
450                 }
451                 destValue = array;
452
453             } else {
454                 Object JavaDoc [] array;
455                 try {
456                     array = (Object JavaDoc [])Array.newInstance(destClass.getComponentType(),
457                                                          length);
458                 } catch (Exception JavaDoc e) {
459                     return arg;
460                 }
461
462                 // Use convert to assign array elements.
463
if (arg.getClass().isArray()) {
464                     for (int i = 0; i < length; i++) {
465                         array[i] = convert(Array.get(arg, i),
466                                            destClass.getComponentType());
467                     }
468                 } else {
469                     int idx = 0;
470                     for (Iterator JavaDoc i = ((Collection JavaDoc)arg).iterator();
471                             i.hasNext();) {
472                         array[idx++] = convert(i.next(),
473                                            destClass.getComponentType());
474                     }
475                 }
476                 destValue = array;
477             }
478         }
479         else if (Collection JavaDoc.class.isAssignableFrom(destClass)) {
480             Collection JavaDoc newList = null;
481             try {
482                 // if we are trying to create an interface, build something
483
// that implements the interface
484
if (destClass == Collection JavaDoc.class || destClass == List JavaDoc.class) {
485                     newList = new ArrayList JavaDoc();
486                 } else if (destClass == Set JavaDoc.class) {
487                     newList = new HashSet JavaDoc();
488                 } else {
489                     newList = (Collection JavaDoc)destClass.newInstance();
490                 }
491             } catch (Exception JavaDoc e) {
492                 // Couldn't build one for some reason... so forget it.
493
return arg;
494             }
495
496             if (arg.getClass().isArray()) {
497                 for (int j = 0; j < length; j++) {
498                     newList.add(Array.get(arg, j));
499                 }
500             } else {
501                 for (Iterator JavaDoc j = ((Collection JavaDoc)arg).iterator();
502                             j.hasNext();) {
503                     newList.add(j.next());
504                 }
505             }
506             destValue = newList;
507         }
508         else {
509             destValue = arg;
510         }
511
512         // Store the converted value in the argument if possible.
513
if (arg instanceof ConvertCache) {
514             (( ConvertCache) arg).setConvertedValue(destClass, destValue);
515         }
516         return destValue;
517     }
518
519     public static boolean isConvertable(Object JavaDoc obj, Class JavaDoc dest)
520     {
521         return isConvertable(obj, dest, false);
522     }
523
524     public static boolean isConvertable(Object JavaDoc obj, Class JavaDoc dest, boolean isEncoded)
525     {
526         Class JavaDoc src = null;
527         
528         if (obj != null) {
529             if (obj instanceof Class JavaDoc) {
530                 src = (Class JavaDoc)obj;
531             } else {
532                 src = obj.getClass();
533             }
534         } else {
535             if(!dest.isPrimitive())
536                 return true;
537         }
538         
539         if (dest == null)
540             return false;
541         
542         if (src != null) {
543             // If we're directly assignable, we're good.
544
if (dest.isAssignableFrom(src))
545                 return true;
546
547             //Allow mapping of Map's to Map's
548
if (java.util.Map JavaDoc.class.isAssignableFrom(dest) &&
549                 java.util.Map JavaDoc.class.isAssignableFrom(src)) {
550                   return true;
551             }
552
553             // If it's a wrapping conversion, we're good.
554
if (getWrapperClass(src) == dest)
555                 return true;
556             if (getWrapperClass(dest) == src)
557                 return true;
558             
559             // If it's List -> Array or vice versa, we're good.
560
if ((Collection JavaDoc.class.isAssignableFrom(src) || src.isArray()) &&
561                 (Collection JavaDoc.class.isAssignableFrom(dest) || dest.isArray()) &&
562                 (src.getComponentType() == Object JavaDoc.class ||
563                  src.getComponentType() == null ||
564                  dest.getComponentType() == Object JavaDoc.class ||
565                  dest.getComponentType() == null ||
566                  isConvertable(src.getComponentType(), dest.getComponentType())))
567                     return true;
568             
569             // If destination is an array, and src is a component, we're good
570
// if we're not encoded!
571
if (!isEncoded && dest.isArray() &&
572 // !dest.getComponentType().equals(Object.class) &&
573
dest.getComponentType().isAssignableFrom(src))
574                 return true;
575
576             if ((src == HexBinary.class && dest == byte[].class) ||
577                 (src == byte[].class && dest == HexBinary.class))
578                 return true;
579             
580             // Allow mapping of Calendar to Date
581
if (Calendar JavaDoc.class.isAssignableFrom(src) && dest == Date JavaDoc.class)
582                 return true;
583
584             // Allow mapping of Date to Calendar
585
if (Date JavaDoc.class.isAssignableFrom(src) && dest == Calendar JavaDoc.class)
586                 return true;
587
588             // Allow mapping of Calendar to java.sql.Date
589
if (Calendar JavaDoc.class.isAssignableFrom(src) && dest == java.sql.Date JavaDoc.class)
590                 return true;
591         }
592         
593         Class JavaDoc destHeld = JavaUtils.getHolderValueType(dest);
594         // Can always convert a null to an empty holder
595
if (src == null)
596             return (destHeld != null);
597         
598         if (destHeld != null) {
599             if (destHeld.isAssignableFrom(src) || isConvertable(src, destHeld))
600                 return true;
601         }
602
603         // If it's holder -> held or held -> holder, we're good
604
Class JavaDoc srcHeld = JavaUtils.getHolderValueType(src);
605         if (srcHeld != null) {
606             if (dest.isAssignableFrom(srcHeld) || isConvertable(srcHeld, dest))
607                 return true;
608         }
609
610         // If it's a MIME type mapping and we want a DataHandler,
611
// then we're good.
612
if (dest.getName().equals("javax.activation.DataHandler")) {
613             String JavaDoc name = src.getName();
614             if (src == String JavaDoc.class
615                     || src == java.awt.Image JavaDoc.class
616                     || src == OctetStream.class
617                     || name.equals("javax.mail.internet.MimeMultipart")
618                     || name.equals("javax.xml.transform.Source"))
619                 return true;
620         }
621
622         if (src.getName().equals("javax.activation.DataHandler")) {
623             if (dest == byte[].class)
624                 return true;
625             if (dest.isArray() && dest.getComponentType() == byte[].class)
626                 return true;
627         }
628
629         if (dest.getName().equals("javax.activation.DataHandler")) {
630             if (src == Object JavaDoc[].class)
631                 return true;
632             if (src.isArray() && src.getComponentType() == Object JavaDoc[].class)
633                 return true;
634         }
635
636         if (obj instanceof java.io.InputStream JavaDoc) {
637             if (dest == OctetStream.class)
638                 return true;
639         }
640         
641         if (src.isPrimitive()) {
642             return isConvertable(getWrapperClass(src),dest);
643         }
644         
645         // ArrayOfT -> T[] ?
646
if (dest.isArray()) {
647             if (ArrayUtil.isConvertable(src, dest) == true)
648                 return true;
649         }
650         
651         // T[] -> ArrayOfT ?
652
if (src.isArray()) {
653             if (ArrayUtil.isConvertable(src, dest) == true)
654                 return true;
655         }
656         
657         return false;
658     }
659
660     public static Image getImageFromStream(InputStream JavaDoc is) {
661         try {
662             return ImageIOFactory.getImageIO().loadImage(is);
663         }
664         catch (Throwable JavaDoc t) {
665             return null;
666         }
667     } // getImageFromStream
668

669     /**
670      * These are java keywords as specified at the following URL (sorted alphabetically).
671      * http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#229308
672      * Note that false, true, and null are not strictly keywords; they are literal values,
673      * but for the purposes of this array, they can be treated as literals.
674      * ****** PLEASE KEEP THIS LIST SORTED IN ASCENDING ORDER ******
675      */

676     static final String JavaDoc keywords[] =
677     {
678         "abstract", "assert", "boolean", "break", "byte", "case",
679         "catch", "char", "class", "const", "continue",
680         "default", "do", "double", "else", "extends",
681         "false", "final", "finally", "float", "for",
682         "goto", "if", "implements", "import", "instanceof",
683         "int", "interface", "long", "native", "new",
684         "null", "package", "private", "protected", "public",
685         "return", "short", "static", "strictfp", "super",
686         "switch", "synchronized", "this", "throw", "throws",
687         "transient", "true", "try", "void", "volatile",
688         "while"
689     };
690
691     /** Collator for comparing the strings */
692     static final Collator JavaDoc englishCollator = Collator.getInstance(Locale.ENGLISH);
693
694     /** Use this character as suffix */
695     static final char keywordPrefix = '_';
696
697     /**
698      * isJavaId
699      * Returns true if the name is a valid java identifier.
700      * @param id to check
701      * @return boolean true/false
702      **/

703     public static boolean isJavaId(String JavaDoc id) {
704         if (id == null || id.equals("") || isJavaKeyword(id))
705             return false;
706         if (!Character.isJavaIdentifierStart(id.charAt(0)))
707             return false;
708         for (int i=1; i<id.length(); i++)
709             if (!Character.isJavaIdentifierPart(id.charAt(i)))
710                 return false;
711         return true;
712     }
713
714     /**
715      * checks if the input string is a valid java keyword.
716      * @return boolean true/false
717      */

718     public static boolean isJavaKeyword(String JavaDoc keyword) {
719       return (Arrays.binarySearch(keywords, keyword, englishCollator) >= 0);
720     }
721
722     /**
723      * Turn a java keyword string into a non-Java keyword string. (Right now
724      * this simply means appending an underscore.)
725      */

726     public static String JavaDoc makeNonJavaKeyword(String JavaDoc keyword){
727         return keywordPrefix + keyword;
728      }
729
730     /**
731      * Converts text of the form
732      * Foo[] to the proper class name for loading [LFoo
733      */

734     public static String JavaDoc getLoadableClassName(String JavaDoc text) {
735         if (text == null ||
736             text.indexOf("[") < 0 ||
737             text.charAt(0) == '[')
738             return text;
739         String JavaDoc className = text.substring(0,text.indexOf("["));
740         if (className.equals("byte"))
741             className = "B";
742         else if (className.equals("char"))
743             className = "C";
744         else if (className.equals("double"))
745             className = "D";
746         else if (className.equals("float"))
747             className = "F";
748         else if (className.equals("int"))
749             className = "I";
750         else if (className.equals("long"))
751             className = "J";
752         else if (className.equals("short"))
753             className = "S";
754         else if (className.equals("boolean"))
755             className = "Z";
756         else
757             className = "L" + className + ";";
758         int i = text.indexOf("]");
759         while (i > 0) {
760             className = "[" + className;
761             i = text.indexOf("]", i+1);
762         }
763         return className;
764     }
765
766     /**
767      * Converts text of the form
768      * [LFoo to the Foo[]
769      */

770     public static String JavaDoc getTextClassName(String JavaDoc text) {
771         if (text == null ||
772             text.indexOf("[") != 0)
773             return text;
774         String JavaDoc className = "";
775         int index = 0;
776         while(index < text.length() &&
777               text.charAt(index) == '[') {
778             index ++;
779             className += "[]";
780         }
781         if (index < text.length()) {
782             if (text.charAt(index)== 'B')
783                 className = "byte" + className;
784             else if (text.charAt(index) == 'C')
785                 className = "char" + className;
786             else if (text.charAt(index) == 'D')
787                 className = "double" + className;
788             else if (text.charAt(index) == 'F')
789                 className = "float" + className;
790             else if (text.charAt(index) == 'I')
791                 className = "int" + className;
792             else if (text.charAt(index) == 'J')
793                 className = "long" + className;
794             else if (text.charAt(index) == 'S')
795                 className = "short" + className;
796             else if (text.charAt(index) == 'Z')
797                 className = "boolean" + className;
798             else {
799                 className = text.substring(index+1, text.indexOf(";")) + className;
800             }
801         }
802         return className;
803     }
804
805     /**
806      * Map an XML name to a Java identifier per
807      * the mapping rules of JSR 101 (in version 1.0 this is
808      * "Chapter 20: Appendix: Mapping of XML Names"
809      *
810      * @param name is the xml name
811      * @return the java name per JSR 101 specification
812      */

813     public static String JavaDoc xmlNameToJava(String JavaDoc name)
814     {
815         // protect ourselves from garbage
816
if (name == null || name.equals(""))
817             return name;
818
819         char[] nameArray = name.toCharArray();
820         int nameLen = name.length();
821         StringBuffer JavaDoc result = new StringBuffer JavaDoc(nameLen);
822         boolean wordStart = false;
823
824         // The mapping indicates to convert first character.
825
int i = 0;
826         while (i < nameLen
827                 && (isPunctuation(nameArray[i])
828                 || !Character.isJavaIdentifierStart(nameArray[i]))) {
829             i++;
830         }
831         if (i < nameLen) {
832             // Decapitalization code used to be here, but we use the
833
// Introspector function now after we filter out all bad chars.
834

835             result.append(nameArray[i]);
836             //wordStart = !Character.isLetter(nameArray[i]);
837
wordStart = !Character.isLetter(nameArray[i]) && nameArray[i] != "_".charAt(0);
838         }
839         else {
840             // The identifier cannot be mapped strictly according to
841
// JSR 101
842
if (Character.isJavaIdentifierPart(nameArray[0])) {
843                 result.append("_" + nameArray[0]);
844             }
845             else {
846                 // The XML identifier does not contain any characters
847
// we can map to Java. Using the length of the string
848
// will make it somewhat unique.
849
result.append("_" + nameArray.length);
850             }
851         }
852
853         // The mapping indicates to skip over
854
// all characters that are not letters or
855
// digits. The first letter/digit
856
// following a skipped character is
857
// upper-cased.
858
for (++i; i < nameLen; ++i) {
859             char c = nameArray[i];
860
861             // if this is a bad char, skip it and remember to capitalize next
862
// good character we encounter
863
if (isPunctuation(c) || !Character.isJavaIdentifierPart(c)) {
864                 wordStart = true;
865                 continue;
866             }
867             if (wordStart && Character.isLowerCase(c)) {
868                 result.append(Character.toUpperCase(c));
869             }
870             else {
871                 result.append(c);
872             }
873             // If c is not a character, but is a legal Java
874
// identifier character, capitalize the next character.
875
// For example: "22hi" becomes "22Hi"
876
//wordStart = !Character.isLetter(c);
877
wordStart = !Character.isLetter(c) && c != "_".charAt(0);
878         }
879
880         // covert back to a String
881
String JavaDoc newName = result.toString();
882         
883         // Follow JavaBean rules, but we need to check if the first
884
// letter is uppercase first
885
if (Character.isUpperCase(newName.charAt(0)))
886             newName = Introspector.decapitalize(newName);
887
888         // check for Java keywords
889
if (isJavaKeyword(newName))
890             newName = makeNonJavaKeyword(newName);
891
892         return newName;
893     } // xmlNameToJava
894

895     /**
896      * Is this an XML punctuation character?
897      */

898     private static boolean isPunctuation(char c)
899     {
900         return '-' == c
901             || '.' == c
902             || ':' == c
903             || '\u00B7' == c
904             || '\u0387' == c
905             || '\u06DD' == c
906             || '\u06DE' == c;
907     } // isPunctuation
908

909
910     /**
911      * replace:
912      * Like String.replace except that the old new items are strings.
913      *
914      * @param name string
915      * @param oldT old text to replace
916      * @param newT new text to use
917      * @return replacement string
918      **/

919     public static final String JavaDoc replace (String JavaDoc name,
920                                         String JavaDoc oldT, String JavaDoc newT) {
921
922         if (name == null) return "";
923
924         // Create a string buffer that is twice initial length.
925
// This is a good starting point.
926
StringBuffer JavaDoc sb = new StringBuffer JavaDoc(name.length()* 2);
927
928         int len = oldT.length ();
929         try {
930             int start = 0;
931             int i = name.indexOf (oldT, start);
932
933             while (i >= 0) {
934                 sb.append(name.substring(start, i));
935                 sb.append(newT);
936                 start = i+len;
937                 i = name.indexOf(oldT, start);
938             }
939             if (start < name.length())
940                 sb.append(name.substring(start));
941         } catch (NullPointerException JavaDoc e) {
942         }
943
944         return new String JavaDoc(sb);
945     }
946
947     /**
948      * Determines if the Class is a Holder class. If so returns Class of held type
949      * else returns null
950      * @param type the suspected Holder Class
951      * @return class of held type or null
952      */

953     public static Class JavaDoc getHolderValueType(Class JavaDoc type) {
954         if (type != null) {
955             Class JavaDoc[] intf = type.getInterfaces();
956             boolean isHolder = false;
957             for (int i=0; i<intf.length && !isHolder; i++) {
958                 if (intf[i] == javax.xml.rpc.holders.Holder JavaDoc.class) {
959                     isHolder = true;
960                 }
961             }
962             if (isHolder == false) {
963                 return null;
964             }
965
966             // Holder is supposed to have a public value field.
967
java.lang.reflect.Field JavaDoc field;
968             try {
969                 field = type.getField("value");
970             } catch (Exception JavaDoc e) {
971                 field = null;
972             }
973             if (field != null) {
974                 return field.getType();
975             }
976         }
977         return null;
978     }
979
980     /**
981      * Gets the Holder value.
982      * @param holder Holder object
983      * @return value object
984      */

985     public static Object JavaDoc getHolderValue(Object JavaDoc holder) throws HolderException {
986         if (!(holder instanceof javax.xml.rpc.holders.Holder JavaDoc)) {
987             throw new HolderException(Messages.getMessage("badHolder00"));
988         }
989         try {
990             Field JavaDoc valueField = holder.getClass().getField("value");
991             return valueField.get(holder);
992         } catch (Exception JavaDoc e) {
993           throw new HolderException(Messages.getMessage("exception01", e.getMessage()));
994         }
995     }
996
997     /**
998      * Sets the Holder value.
999      * @param holder Holder object
1000     * @param value is the object value
1001     */

1002    public static void setHolderValue(Object JavaDoc holder, Object JavaDoc value) throws HolderException {
1003        if (!(holder instanceof javax.xml.rpc.holders.Holder JavaDoc)) {
1004            throw new HolderException(Messages.getMessage("badHolder00"));
1005        }
1006        try {
1007            Field JavaDoc valueField = holder.getClass().getField("value");
1008            if (valueField.getType().isPrimitive()) {
1009                if (value == null)
1010                    ; // Don't need to set anything
1011
else
1012                    valueField.set(holder, value); // Automatically unwraps value to primitive
1013
} else {
1014                valueField.set(holder, value);
1015            }
1016        } catch (Exception JavaDoc e) {
1017          throw new HolderException(Messages.getMessage("exception01", e.getMessage()));
1018        }
1019    }
1020    public static class HolderException extends Exception JavaDoc
1021    {
1022        public HolderException(String JavaDoc msg) { super(msg); }
1023    }
1024
1025    
1026    /**
1027     * Used to cache a result from IsEnumClassSub().
1028     * Class->Boolean mapping.
1029     */

1030    private static HashMap JavaDoc enumMap = new HashMap JavaDoc();
1031    
1032    /**
1033     * Determine if the class is a JAX-RPC enum class.
1034     * An enumeration class is recognized by
1035     * a getValue() method, a toString() method, a fromString(String) method
1036     * a fromValue(type) method and the lack
1037     * of a setValue(type) method
1038     */

1039    public static boolean isEnumClass(Class JavaDoc cls) {
1040        Boolean JavaDoc b = (Boolean JavaDoc)enumMap.get(cls);
1041        if (b == null) {
1042            b = (isEnumClassSub(cls)) ? Boolean.TRUE : Boolean.FALSE;
1043            enumMap.put(cls, b);
1044        }
1045        return b.booleanValue();
1046    }
1047
1048    private static boolean isEnumClassSub(Class JavaDoc cls) {
1049        try {
1050            java.lang.reflect.Method JavaDoc[] methods = cls.getMethods();
1051            java.lang.reflect.Method JavaDoc getValueMethod = null,
1052                fromValueMethod = null,
1053                setValueMethod = null, fromStringMethod = null;
1054            
1055            // linear search: in practice, this is faster than
1056
// sorting/searching a short array of methods.
1057
for (int i = 0; i < methods.length; i++) {
1058                String JavaDoc name = methods[i].getName();
1059
1060                if (name.equals("getValue")
1061                    && methods[i].getParameterTypes().length == 0) { // getValue()
1062
getValueMethod = methods[i];
1063                } else if (name.equals("fromString")) { // fromString(String s)
1064
Object JavaDoc[] params = methods[i].getParameterTypes();
1065                    if (params.length == 1
1066                        && params[0] == String JavaDoc.class) {
1067                        fromStringMethod = methods[i];
1068                    }
1069                } else if (name.equals("fromValue")
1070                           && methods[i].getParameterTypes().length == 1) { // fromValue(Something s)
1071
fromValueMethod = methods[i];
1072                } else if (name.equals("setValue")
1073                           && methods[i].getParameterTypes().length == 1) { // setValue(Something s)
1074
setValueMethod = methods[i];
1075                }
1076            }
1077
1078            // must have getValue and fromString, but not setValue
1079
// must also have toString(), but every Object subclass has that, so
1080
// no need to check for it.
1081
if (null != getValueMethod && null != fromStringMethod) {
1082                if (null != setValueMethod
1083                    && setValueMethod.getParameterTypes().length == 1
1084                    && getValueMethod.getReturnType() == setValueMethod.getParameterTypes()[0]) {
1085                    // setValue exists: return false
1086
return false;
1087                } else {
1088                    return true;
1089                }
1090            } else {
1091                return false;
1092            }
1093        } catch (java.lang.SecurityException JavaDoc e) {
1094            return false;
1095        } // end of catch
1096
}
1097
1098    public static String JavaDoc stackToString(Throwable JavaDoc e){
1099      java.io.StringWriter JavaDoc sw= new java.io.StringWriter JavaDoc(1024);
1100      java.io.PrintWriter JavaDoc pw= new java.io.PrintWriter JavaDoc(sw);
1101      e.printStackTrace(pw);
1102      pw.close();
1103      return sw.toString();
1104    }
1105
1106    /**
1107     * Tests the String 'value':
1108     * return 'false' if its 'false', '0', or 'no' - else 'true'
1109     *
1110     * Follow in 'C' tradition of boolean values:
1111     * false is specific (0), everything else is true;
1112     */

1113    public static final boolean isTrue(String JavaDoc value) {
1114        return !isFalseExplicitly(value);
1115    }
1116
1117    /**
1118     * Tests the String 'value':
1119     * return 'true' if its 'true', '1', or 'yes' - else 'false'
1120     */

1121    public static final boolean isTrueExplicitly(String JavaDoc value) {
1122        return value != null &&
1123               (value.equalsIgnoreCase("true") ||
1124                value.equals("1") ||
1125                value.equalsIgnoreCase("yes"));
1126    }
1127
1128    /**
1129     * Tests the Object 'value':
1130     * if its null, return default.
1131     * if its a Boolean, return booleanValue()
1132     * if its an Integer, return 'false' if its '0' else 'true'
1133     * if its a String, return isTrueExplicitly((String)value).
1134     * All other types return 'true'
1135     */

1136    public static final boolean isTrueExplicitly(Object JavaDoc value, boolean defaultVal) {
1137        if ( value == null ) return defaultVal;
1138        if ( value instanceof Boolean JavaDoc ) {
1139            return ((Boolean JavaDoc)value).booleanValue();
1140        }
1141        if ( value instanceof Integer JavaDoc ) {
1142            return ((Integer JavaDoc)value).intValue() != 0;
1143        }
1144        if ( value instanceof String JavaDoc ) {
1145            return isTrueExplicitly( (String JavaDoc)value );
1146        }
1147        return true;
1148    }
1149    
1150    public static final boolean isTrueExplicitly(Object JavaDoc value) {
1151        return isTrueExplicitly(value, false);
1152    }
1153
1154    /**
1155     * Tests the Object 'value':
1156     * if its null, return default.
1157     * if its a Boolean, return booleanValue()
1158     * if its an Integer, return 'false' if its '0' else 'true'
1159     * if its a String, return 'false' if its 'false', 'no', or '0' - else 'true'
1160     * All other types return 'true'
1161     */

1162    public static final boolean isTrue(Object JavaDoc value, boolean defaultVal) {
1163        return !isFalseExplicitly(value, !defaultVal);
1164    }
1165    
1166    public static final boolean isTrue(Object JavaDoc value) {
1167        return isTrue(value, false);
1168    }
1169    
1170    /**
1171     * Tests the String 'value':
1172     * return 'true' if its 'false', '0', or 'no' - else 'false'
1173     *
1174     * Follow in 'C' tradition of boolean values:
1175     * false is specific (0), everything else is true;
1176     */

1177    public static final boolean isFalse(String JavaDoc value) {
1178        return isFalseExplicitly(value);
1179    }
1180
1181    /**
1182     * Tests the String 'value':
1183     * return 'true' if its null, 'false', '0', or 'no' - else 'false'
1184     */

1185    public static final boolean isFalseExplicitly(String JavaDoc value) {
1186        return value == null ||
1187               value.equalsIgnoreCase("false") ||
1188               value.equals("0") ||
1189               value.equalsIgnoreCase("no");
1190    }
1191    
1192    /**
1193     * Tests the Object 'value':
1194     * if its null, return default.
1195     * if its a Boolean, return !booleanValue()
1196     * if its an Integer, return 'true' if its '0' else 'false'
1197     * if its a String, return isFalseExplicitly((String)value).
1198     * All other types return 'false'
1199     */

1200    public static final boolean isFalseExplicitly(Object JavaDoc value, boolean defaultVal) {
1201        if ( value == null ) return defaultVal;
1202        if ( value instanceof Boolean JavaDoc ) {
1203            return !((Boolean JavaDoc)value).booleanValue();
1204        }
1205        if ( value instanceof Integer JavaDoc ) {
1206            return ((Integer JavaDoc)value).intValue() == 0;
1207        }
1208        if ( value instanceof String JavaDoc ) {
1209            return isFalseExplicitly( (String JavaDoc)value );
1210        }
1211        return false;
1212    }
1213    
1214    public static final boolean isFalseExplicitly(Object JavaDoc value) {
1215        return isFalseExplicitly(value, true);
1216    }
1217
1218    /**
1219     * Tests the Object 'value':
1220     * if its null, return default.
1221     * if its a Boolean, return booleanValue()
1222     * if its an Integer, return 'false' if its '0' else 'true'
1223     * if its a String, return 'false' if its 'false', 'no', or '0' - else 'true'
1224     * All other types return 'true'
1225     */

1226    public static final boolean isFalse(Object JavaDoc value, boolean defaultVal) {
1227        return isFalseExplicitly(value, defaultVal);
1228    }
1229    
1230    public static final boolean isFalse(Object JavaDoc value) {
1231        return isFalse(value, true);
1232    }
1233    
1234    /**
1235     * Given the MIME type string, return the Java mapping.
1236     */

1237    public static String JavaDoc mimeToJava(String JavaDoc mime) {
1238        if ("image/gif".equals(mime) || "image/jpeg".equals(mime)) {
1239            return "java.awt.Image";
1240        }
1241        else if ("text/plain".equals(mime)) {
1242            return "java.lang.String";
1243        }
1244        else if ("text/xml".equals(mime) || "application/xml".equals(mime)) {
1245            return "javax.xml.transform.Source";
1246        }
1247        else if ("application/octet-stream".equals(mime)||
1248                 "application/octetstream".equals(mime)) {
1249            return "org.apache.axis.attachments.OctetStream";
1250        }
1251        else if (mime != null && mime.startsWith("multipart/")) {
1252            return "javax.mail.internet.MimeMultipart";
1253        }
1254        else {
1255            return "javax.activation.DataHandler";
1256        }
1257    } // mimeToJava
1258

1259    //avoid testing and possibly failing everytime.
1260
private static boolean checkForAttachmentSupport = true;
1261    private static boolean attachmentSupportEnabled = false;
1262
1263    /**
1264     * Determine whether attachments are supported by checking if the following
1265     * classes are available: javax.activation.DataHandler,
1266     * javax.mail.internet.MimeMultipart.
1267     */

1268    public static synchronized boolean isAttachmentSupported() {
1269
1270        if (checkForAttachmentSupport) {
1271            //aviod testing and possibly failing everytime.
1272
checkForAttachmentSupport = false;
1273            try {
1274                // Attempt to resolve DataHandler and MimeMultipart and
1275
// javax.xml.transform.Source, all necessary for full
1276
// attachment support
1277
ClassUtils.forName("javax.activation.DataHandler");
1278                ClassUtils.forName("javax.mail.internet.MimeMultipart");
1279                attachmentSupportEnabled = true;
1280            } catch (Throwable JavaDoc t) {
1281            }
1282            log.debug(Messages.getMessage("attachEnabled") + " " +
1283                    attachmentSupportEnabled);
1284            if(!attachmentSupportEnabled) {
1285                log.warn(Messages.getMessage("attachDisabled"));
1286            }
1287        }
1288
1289        return attachmentSupportEnabled;
1290    } // isAttachmentSupported
1291

1292    /**
1293     * Makes the value passed in <code>initValue</code> unique among the
1294     * {@link String} values contained in <code>values</code> by suffixing
1295     * it with a decimal digit suffix.
1296     */

1297    public static String JavaDoc getUniqueValue(Collection JavaDoc values, String JavaDoc initValue) {
1298
1299        if (!values.contains(initValue)) {
1300            return initValue;
1301        }
1302        else {
1303
1304            StringBuffer JavaDoc unqVal = new StringBuffer JavaDoc(initValue);
1305            int beg = unqVal.length(), cur, end;
1306            while (Character.isDigit(unqVal.charAt(beg - 1))) {
1307                beg--;
1308            }
1309            if (beg == unqVal.length()) {
1310                unqVal.append('1');
1311            }
1312            cur = end = unqVal.length() - 1;
1313
1314            while (values.contains(unqVal.toString())) {
1315
1316                if (unqVal.charAt(cur) < '9') {
1317                    unqVal.setCharAt(cur, (char) (unqVal.charAt(cur) + 1));
1318                }
1319
1320                else {
1321
1322                    while (cur-- > beg) {
1323                        if (unqVal.charAt(cur) < '9') {
1324                            unqVal.setCharAt(cur,
1325                                (char) (unqVal.charAt(cur) + 1));
1326                            break;
1327                        }
1328                    }
1329
1330                    // See if there's a need to insert a new digit.
1331
if (cur < beg) {
1332                        unqVal.insert(++cur, '1'); end++;
1333                    }
1334                    while (cur < end) {
1335                        unqVal.setCharAt(++cur, '0');
1336                    }
1337
1338                }
1339
1340            }
1341
1342            return unqVal.toString();
1343
1344        } /* For else clause of selection-statement If(!values ... */
1345
1346    } /* For class method JavaUtils.getUniqueValue */
1347}
1348
Popular Tags