KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001-2003 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Axis" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55
56 package org.jboss.axis.utils;
57
58 import org.jboss.axis.attachments.AttachmentPartImpl;
59 import org.jboss.axis.attachments.OctetStream;
60 import org.jboss.axis.components.image.ImageIO;
61 import org.jboss.axis.components.image.ImageIOFactory;
62 import org.jboss.axis.types.HexBinary;
63 import org.jboss.logging.Logger;
64
65 import javax.activation.DataHandler JavaDoc;
66 import javax.xml.namespace.QName JavaDoc;
67 import javax.xml.rpc.holders.*;
68 import javax.xml.soap.SOAPException JavaDoc;
69 import javax.xml.transform.Source JavaDoc;
70 import javax.xml.transform.stream.StreamSource JavaDoc;
71 import java.awt.*;
72 import java.beans.Introspector JavaDoc;
73 import java.io.ByteArrayOutputStream JavaDoc;
74 import java.io.IOException JavaDoc;
75 import java.io.InputStream JavaDoc;
76 import java.io.StringReader JavaDoc;
77 import java.lang.reflect.Array JavaDoc;
78 import java.lang.reflect.Constructor JavaDoc;
79 import java.lang.reflect.Field JavaDoc;
80 import java.lang.reflect.Method JavaDoc;
81 import java.math.BigDecimal JavaDoc;
82 import java.math.BigInteger JavaDoc;
83 import java.text.Collator JavaDoc;
84 import java.util.ArrayList JavaDoc;
85 import java.util.Arrays JavaDoc;
86 import java.util.Calendar JavaDoc;
87 import java.util.Collection JavaDoc;
88 import java.util.GregorianCalendar JavaDoc;
89 import java.util.HashMap JavaDoc;
90 import java.util.HashSet JavaDoc;
91 import java.util.Hashtable JavaDoc;
92 import java.util.Iterator JavaDoc;
93 import java.util.List JavaDoc;
94 import java.util.Locale JavaDoc;
95 import java.util.Set JavaDoc;
96
97 /**
98  * Utility class to deal with Java language related issues, such
99  * as type conversions.
100  *
101  * @author Glen Daniels (gdaniels@macromedia.com)
102  */

103 public class JavaUtils
104 {
105    private static Logger log = Logger.getLogger(JavaUtils.class.getName());
106
107    public static final char NL = '\n';
108
109    public static final char CR = '\r';
110
111    /**
112     * The prefered line separator
113     */

114    public static final String JavaDoc LS = System.getProperty("line.separator",
115            (new Character JavaDoc(NL)).toString());
116
117
118    public static Class JavaDoc getWrapperClass(Class JavaDoc primitive)
119    {
120       if (primitive == int.class)
121          return java.lang.Integer JavaDoc.class;
122       else if (primitive == short.class)
123          return java.lang.Short JavaDoc.class;
124       else if (primitive == boolean.class)
125          return java.lang.Boolean JavaDoc.class;
126       else if (primitive == byte.class)
127          return java.lang.Byte JavaDoc.class;
128       else if (primitive == long.class)
129          return java.lang.Long JavaDoc.class;
130       else if (primitive == double.class)
131          return java.lang.Double JavaDoc.class;
132       else if (primitive == float.class)
133          return java.lang.Float JavaDoc.class;
134       else if (primitive == char.class)
135          return java.lang.Character JavaDoc.class;
136
137       return null;
138    }
139
140    public static String JavaDoc getWrapper(String JavaDoc primitive)
141    {
142       if (primitive.equals("int"))
143          return "Integer";
144       else if (primitive.equals("short"))
145          return "Short";
146       else if (primitive.equals("boolean"))
147          return "Boolean";
148       else if (primitive.equals("byte"))
149          return "Byte";
150       else if (primitive.equals("long"))
151          return "Long";
152       else if (primitive.equals("double"))
153          return "Double";
154       else if (primitive.equals("float"))
155          return "Float";
156       else if (primitive.equals("char"))
157          return "Character";
158
159       return null;
160    }
161
162    public static Class JavaDoc getPrimitiveClass(Class JavaDoc wrapper)
163    {
164       if (wrapper == java.lang.Integer JavaDoc.class)
165          return int.class;
166       else if (wrapper == java.lang.Short JavaDoc.class)
167          return short.class;
168       else if (wrapper == java.lang.Boolean JavaDoc.class)
169          return boolean.class;
170       else if (wrapper == java.lang.Byte JavaDoc.class)
171          return byte.class;
172       else if (wrapper == java.lang.Long JavaDoc.class)
173          return long.class;
174       else if (wrapper == java.lang.Double JavaDoc.class)
175          return double.class;
176       else if (wrapper == java.lang.Float JavaDoc.class)
177          return float.class;
178       else if (wrapper == java.lang.Character JavaDoc.class)
179          return char.class;
180
181       return null;
182    }
183
184    public static Class JavaDoc getPrimitiveClass(String JavaDoc javaType)
185    {
186       if ("int".equals(javaType))
187          return int.class;
188       else if ("short".equals(javaType))
189          return short.class;
190       else if ("boolean".equals(javaType))
191          return boolean.class;
192       else if ("byte".equals(javaType))
193          return byte.class;
194       else if ("long".equals(javaType))
195          return long.class;
196       else if ("double".equals(javaType))
197          return double.class;
198       else if ("float".equals(javaType))
199          return float.class;
200       else if ("char".equals(javaType))
201          return char.class;
202
203       return null;
204    }
205
206    /**
207     * It the argument to the convert(...) method implements
208     * the ConvertCache interface, the convert(...) method
209     * will use the set/get methods to store and retrieve
210     * converted values.
211     */

212    public interface ConvertCache
213    {
214       /**
215        * Set/Get converted values of the convert method.
216        */

217       public void setConvertedValue(Class JavaDoc cls, Object JavaDoc value);
218
219       public Object JavaDoc getConvertedValue(Class JavaDoc cls);
220
221       /**
222        * Get the destination array class described by the xml
223        */

224       public Class JavaDoc getDestClass();
225    }
226
227    /**
228     * Utility function to convert an Object to some desired Class.
229     * <p/>
230     * Right now this works for:
231     * arrays <-> Lists,
232     * Holders <-> held values
233     *
234     * @param arg the array to convert
235     * @param destClass the actual class we want
236     */

237    public static Object JavaDoc convert(Object JavaDoc arg, Class JavaDoc destClass)
238    {
239       if (destClass == null)
240       {
241          return arg;
242       }
243
244       Class JavaDoc argHeldType = null;
245       if (arg != null)
246       {
247          argHeldType = getHolderValueType(arg.getClass());
248       }
249
250       if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass()))
251       {
252          return arg;
253       }
254
255       if (arg != null && destClass != null)
256          assertClassLoaders(arg.getClass(), destClass);
257
258       if (log.isDebugEnabled())
259       {
260          String JavaDoc clsName = "null";
261          if (arg != null) clsName = arg.getClass().getName();
262          log.debug(Messages.getMessage("convert00", clsName, destClass.getName()));
263       }
264
265       // See if a previously converted value is stored in the argument.
266
Object JavaDoc destValue = null;
267       if (arg instanceof ConvertCache)
268       {
269          destValue = ((ConvertCache)arg).getConvertedValue(destClass);
270          if (destValue != null)
271             return destValue;
272       }
273
274       // Get the destination held type or the argument held type if they exist
275
Class JavaDoc destHeldType = getHolderValueType(destClass);
276
277       // Convert between Axis special purpose HexBinary and byte[]
278
if (arg instanceof HexBinary && destClass == byte[].class)
279          return ((HexBinary)arg).getBytes();
280       if (arg instanceof byte[] && destClass == HexBinary.class)
281          return new HexBinary((byte[])arg);
282       if (arg instanceof HexBinary && destClass == Byte JavaDoc[].class)
283          return convert(((HexBinary)arg).getBytes(), Byte JavaDoc[].class);
284       if (arg instanceof Byte JavaDoc[] && destClass == HexBinary.class)
285          return new HexBinary((Byte JavaDoc[])arg);
286
287       // Convert between Calendar and Date
288
if (arg instanceof Calendar JavaDoc && destClass.isAssignableFrom(java.util.Date JavaDoc.class))
289       {
290          return ((Calendar JavaDoc)arg).getTime();
291       }
292       if (arg instanceof java.util.Date JavaDoc && destClass.isAssignableFrom(Calendar JavaDoc.class))
293       {
294          GregorianCalendar JavaDoc gregorianCalendar = new GregorianCalendar JavaDoc();
295          gregorianCalendar.setTime((java.util.Date JavaDoc)arg);
296          return gregorianCalendar;
297       }
298
299       // Convert between Calendar and org.jboss.axis.types.Time
300
if (arg instanceof Calendar JavaDoc && destClass.isAssignableFrom(org.jboss.axis.types.Time.class))
301          return new org.jboss.axis.types.Time((Calendar JavaDoc)arg);
302       if (arg instanceof org.jboss.axis.types.Time && destClass.isAssignableFrom(Calendar JavaDoc.class))
303          return ((org.jboss.axis.types.Time)arg).getAsCalendar();
304
305       // Convert between HashMap and Hashtable
306
if (arg instanceof HashMap JavaDoc && destClass == Hashtable JavaDoc.class)
307       {
308          return new Hashtable JavaDoc((HashMap JavaDoc)arg);
309       }
310
311       // Allow mapping of String to org.jboss.axis.types.Language
312
if (arg instanceof org.jboss.axis.types.Language && destClass == String JavaDoc.class)
313          return arg.toString();
314       if (arg instanceof String JavaDoc && destClass == org.jboss.axis.types.Language.class)
315          return new org.jboss.axis.types.Language((String JavaDoc)arg);
316
317       // Allow mapping of String to org.jboss.axis.types.Token
318
if (arg instanceof org.jboss.axis.types.Token && destClass == String JavaDoc.class)
319          return arg.toString();
320       if (arg instanceof String JavaDoc && destClass == org.jboss.axis.types.Token.class)
321          return new org.jboss.axis.types.Token((String JavaDoc)arg);
322
323       // Do fuzzy bean conversion arg -> wrapperBean(dest)
324
if (arg != null && isBeanCompatible(destClass))
325       {
326          try
327          {
328             Constructor JavaDoc ctor = getConstructorForClass(destClass, arg.getClass());
329             Object JavaDoc ctorArg = convert(arg, ctor.getParameterTypes()[0]);
330             return ctor.newInstance(new Object JavaDoc[]{ctorArg});
331          }
332          catch (Exception JavaDoc ignore)
333          {
334             // ignore
335
}
336       }
337       // Do fuzzy bean conversion wrapperBean -> dest
338
if (arg != null && isBeanCompatible(arg.getClass()))
339       {
340          try
341          {
342             Method JavaDoc getter = getAccessorForClass(arg.getClass(), destClass);
343             return getter.invoke(arg, null);
344          }
345          catch (Exception JavaDoc ignore)
346          {
347             // ignore
348
}
349       }
350
351       // Convert an AttachmentPart to the given destination class.
352
if (isAttachmentSupported() &&
353               (arg instanceof InputStream JavaDoc || arg instanceof AttachmentPartImpl || arg instanceof DataHandler JavaDoc))
354       {
355          try
356          {
357             String JavaDoc destName = destClass.getName();
358             if (destClass == String JavaDoc.class
359                     || destClass == OctetStream.class
360                     || destClass == byte[].class
361                     || destClass == Image.class
362                     || destClass == Source JavaDoc.class
363                     || destClass == DataHandler JavaDoc.class
364                     || destName.equals("javax.mail.internet.MimeMultipart"))
365             {
366                DataHandler JavaDoc handler = null;
367                if (arg instanceof AttachmentPartImpl)
368                {
369                   handler = ((AttachmentPartImpl)arg).getDataHandler();
370                }
371                else if (arg instanceof DataHandler JavaDoc)
372                {
373                   handler = (DataHandler JavaDoc)arg;
374                }
375                if (destClass == Image.class)
376                {
377                   // Note: An ImageIO component is required to process an Image
378
// attachment, but if the image would be null
379
// (is.available == 0) then ImageIO component isn't needed
380
// and we can return null.
381
InputStream JavaDoc is = (InputStream JavaDoc)handler.getContent();
382                   if (is.available() == 0)
383                   {
384                      return null;
385                   }
386                   else
387                   {
388                      ImageIO imageIO = ImageIOFactory.getImageIO();
389                      if (imageIO != null)
390                      {
391                         return getImageFromStream(is);
392                      }
393                      else
394                      {
395                         log.info(Messages.getMessage("needImageIO"));
396                         return arg;
397                      }
398                   }
399                }
400                else if (destClass == Source JavaDoc.class)
401                {
402                   // For a reason unknown to me, the handler's
403
// content is a String. Convert it to a
404
// StreamSource.
405
return new StreamSource JavaDoc(new StringReader JavaDoc((String JavaDoc)handler.getContent()));
406                }
407                else if ((arg instanceof InputStream JavaDoc) && (destClass == OctetStream.class || destClass == byte[].class))
408                {
409                   InputStream JavaDoc in = (InputStream JavaDoc)arg;
410                   ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
411                   int byte1 = -1;
412                   while ((byte1 = in.read()) != -1)
413                      baos.write(byte1);
414                   return new OctetStream(baos.toByteArray());
415                }
416                else if (destClass == DataHandler JavaDoc.class)
417                {
418                   return handler;
419                }
420                else
421                {
422                   return handler.getContent();
423                }
424             }
425          }
426          catch (IOException JavaDoc ioe)
427          {
428          }
429          catch (SOAPException JavaDoc se)
430          {
431          }
432       }
433
434       // If the destination is an array and the source
435
// is a suitable component, return an array with
436
// the single item.
437
if (arg != null &&
438               destClass.isArray() &&
439               !destClass.getComponentType().equals(Object JavaDoc.class) &&
440               !destClass.getComponentType().isArray() &&
441               destClass.getComponentType().isAssignableFrom(arg.getClass()))
442       {
443          Object JavaDoc array =
444                  Array.newInstance(destClass.getComponentType(), 1);
445          Array.set(array, 0, arg);
446          return array;
447       }
448
449       // Return if no conversion is available
450
if (!(arg instanceof Collection JavaDoc ||
451               (arg != null && arg.getClass().isArray())) &&
452               ((destHeldType == null && argHeldType == null) ||
453               (destHeldType != null && argHeldType != null)))
454       {
455          return arg;
456       }
457
458       // Take care of Holder conversion
459
if (destHeldType != null)
460       {
461          // Convert arg into Holder holding arg.
462
Object JavaDoc newArg = convert(arg, destHeldType);
463          Object JavaDoc argHolder = null;
464          try
465          {
466             argHolder = destClass.newInstance();
467             setHolderValue(argHolder, newArg);
468             return argHolder;
469          }
470          catch (Exception JavaDoc e)
471          {
472             return arg;
473          }
474       }
475       else if (argHeldType != null)
476       {
477          // Convert arg into the held type
478
try
479          {
480             Object JavaDoc newArg = getHolderValue(arg);
481             return convert(newArg, destClass);
482          }
483          catch (HolderException e)
484          {
485             return arg;
486          }
487       }
488
489       // Flow to here indicates that neither arg or destClass is a Holder
490

491       // Check to see if the argument has a prefered destination class.
492
if (arg instanceof ConvertCache &&
493               ((ConvertCache)arg).getDestClass() != destClass)
494       {
495          Class JavaDoc hintClass = ((ConvertCache)arg).getDestClass();
496          if (hintClass != null &&
497                  hintClass.isArray() &&
498                  destClass.isArray() &&
499                  destClass.isAssignableFrom(hintClass))
500          {
501             destClass = hintClass;
502             destValue = ((ConvertCache)arg).getConvertedValue(destClass);
503             if (destValue != null)
504                return destValue;
505          }
506       }
507
508       if (arg == null)
509       {
510          return arg;
511       }
512
513       // The arg may be an array or List
514
int length = 0;
515       if (arg.getClass().isArray())
516       {
517          length = Array.getLength(arg);
518       }
519       else
520       {
521          length = ((Collection JavaDoc)arg).size();
522       }
523       if (destClass.isArray())
524       {
525          Class JavaDoc componentType = destClass.getComponentType();
526          if (componentType.isPrimitive())
527          {
528
529             Object JavaDoc array = Array.newInstance(componentType, length);
530             // Assign array elements
531
if (arg.getClass().isArray())
532             {
533                for (int i = 0; i < length; i++)
534                {
535                   Object JavaDoc srcObj = Array.get(arg, i);
536                   Object JavaDoc valObj = convert(srcObj, componentType);
537                   Array.set(array, i, valObj);
538                }
539             }
540             else
541             {
542                int idx = 0;
543                for (Iterator JavaDoc i = ((Collection JavaDoc)arg).iterator();
544                     i.hasNext();)
545                {
546                   Array.set(array, idx++, i.next());
547                }
548             }
549             destValue = array;
550
551          }
552          else
553          {
554             Object JavaDoc[] array;
555             try
556             {
557                array = (Object JavaDoc[])Array.newInstance(destClass.getComponentType(),
558                        length);
559             }
560             catch (Exception JavaDoc e)
561             {
562                return arg;
563             }
564
565             // Use convert to assign array elements.
566
if (arg.getClass().isArray())
567             {
568                for (int i = 0; i < length; i++)
569                {
570                   array[i] = convert(Array.get(arg, i),
571                           destClass.getComponentType());
572                }
573             }
574             else
575             {
576                int idx = 0;
577                for (Iterator JavaDoc i = ((Collection JavaDoc)arg).iterator();
578                     i.hasNext();)
579                {
580                   array[idx++] = convert(i.next(),
581                           destClass.getComponentType());
582                }
583             }
584             destValue = array;
585          }
586       }
587       else if (Collection JavaDoc.class.isAssignableFrom(destClass))
588       {
589          Collection JavaDoc newList = null;
590          try
591          {
592             // if we are trying to create an interface, build something
593
// that implements the interface
594
if (destClass == Collection JavaDoc.class || destClass == List JavaDoc.class)
595             {
596                newList = new ArrayList JavaDoc();
597             }
598             else if (destClass == Set JavaDoc.class)
599             {
600                newList = new HashSet JavaDoc();
601             }
602             else
603             {
604                newList = (Collection JavaDoc)destClass.newInstance();
605             }
606          }
607          catch (Exception JavaDoc e)
608          {
609             // Couldn't build one for some reason... so forget it.
610
return arg;
611          }
612
613          if (arg.getClass().isArray())
614          {
615             for (int j = 0; j < length; j++)
616             {
617                newList.add(Array.get(arg, j));
618             }
619          }
620          else
621          {
622             for (Iterator JavaDoc j = ((Collection JavaDoc)arg).iterator();
623                  j.hasNext();)
624             {
625                newList.add(j.next());
626             }
627          }
628          destValue = newList;
629       }
630       else
631       {
632          destValue = arg;
633       }
634
635       // Store the converted value in the argument if possible.
636
if (arg instanceof ConvertCache)
637       {
638          ((ConvertCache)arg).setConvertedValue(destClass, destValue);
639       }
640       return destValue;
641    }
642
643    public static boolean isConvertable(Object JavaDoc obj, Class JavaDoc dest)
644    {
645       return isConvertable(obj, dest, false);
646    }
647
648    public static boolean isConvertable(Object JavaDoc obj, Class JavaDoc dest, boolean isEncoded)
649    {
650       Class JavaDoc src = null;
651
652       if (obj != null)
653       {
654          if (obj instanceof Class JavaDoc)
655          {
656             src = (Class JavaDoc)obj;
657          }
658          else
659          {
660             src = obj.getClass();
661          }
662       }
663       else
664       {
665          if (!dest.isPrimitive())
666             return true;
667       }
668
669       if (dest == null)
670          return false;
671
672       if (src != null)
673       {
674          // If we're directly assignable, we're good.
675
if (dest.isAssignableFrom(src))
676             return true;
677
678          assertClassLoaders(src, dest);
679
680          if (src.getName().equals(dest.getName()))
681          {
682             log.error("Conflicting classloaders detected: [src=" + src.getClassLoader() + ",dest=" + dest.getClassLoader() + "]");
683             return false;
684          }
685
686          //Allow mapping of Map's to Map's
687
if (java.util.Map JavaDoc.class.isAssignableFrom(dest) &&
688                  java.util.Map JavaDoc.class.isAssignableFrom(src))
689          {
690             return true;
691          }
692
693          // If it's a wrapping conversion, we're good.
694
if (getWrapperClass(src) == dest)
695             return true;
696          if (getWrapperClass(dest) == src)
697             return true;
698
699          // If it's List -> Array or vice versa, we're good.
700
if ((Collection JavaDoc.class.isAssignableFrom(src) || src.isArray()) &&
701                  (Collection JavaDoc.class.isAssignableFrom(dest) || dest.isArray()) &&
702                  (src.getComponentType() == Object JavaDoc.class ||
703                  src.getComponentType() == null ||
704                  dest.getComponentType() == Object JavaDoc.class ||
705                  dest.getComponentType() == null ||
706                  isConvertable(src.getComponentType(), dest.getComponentType())))
707             return true;
708
709          // If destination is an array, and src is a component, we're good
710
// if we're not encoded!
711
if (!isEncoded && dest.isArray() &&
712                  !dest.getComponentType().equals(Object JavaDoc.class) &&
713                  dest.getComponentType().isAssignableFrom(src))
714             return true;
715
716          if (src == HexBinary.class && dest == byte[].class)
717             return true;
718          if (src == byte[].class && dest == HexBinary.class)
719             return true;
720          if (src == HexBinary.class && dest == Byte JavaDoc[].class)
721             return true;
722          if (src == Byte JavaDoc[].class && dest == HexBinary.class)
723             return true;
724
725          // Hack to allow attachments to function
726
if (src == byte[].class || dest == byte[].class)
727             return true;
728
729          // Allow mapping of Calendar to Date
730
if (Calendar JavaDoc.class.isAssignableFrom(src) && java.util.Date JavaDoc.class.isAssignableFrom(dest))
731             return true;
732          if (Calendar JavaDoc.class.isAssignableFrom(dest) && java.util.Date JavaDoc.class.isAssignableFrom(src))
733             return true;
734
735          // Allow mapping of Calendar to org.jboss.axis.types.Time
736
if (org.jboss.axis.types.Time.class.isAssignableFrom(src) && Calendar JavaDoc.class.isAssignableFrom(dest))
737             return true;
738          if (org.jboss.axis.types.Time.class.isAssignableFrom(dest) && Calendar JavaDoc.class.isAssignableFrom(src))
739             return true;
740
741          // Allow mapping of String to org.jboss.axis.types.Language
742
if (org.jboss.axis.types.Language.class.isAssignableFrom(src) && String JavaDoc.class.isAssignableFrom(dest))
743             return true;
744          if (org.jboss.axis.types.Language.class.isAssignableFrom(dest) && String JavaDoc.class.isAssignableFrom(src))
745             return true;
746
747          // Allow mapping of String to org.jboss.axis.types.Token
748
if (org.jboss.axis.types.Token.class.isAssignableFrom(src) && String JavaDoc.class.isAssignableFrom(dest))
749             return true;
750          if (org.jboss.axis.types.Token.class.isAssignableFrom(dest) && String JavaDoc.class.isAssignableFrom(src))
751             return true;
752       }
753
754       Class JavaDoc destHeld = JavaUtils.getHolderValueType(dest);
755       // Can always convert a null to an empty holder
756
if (src == null)
757          return (destHeld != null);
758
759       if (destHeld != null)
760       {
761          if (destHeld.isAssignableFrom(src) || isConvertable(src, destHeld))
762             return true;
763       }
764
765       // If it's holder -> held or held -> holder, we're good
766
Class JavaDoc srcHeld = JavaUtils.getHolderValueType(src);
767       if (srcHeld != null)
768       {
769          if (dest.isAssignableFrom(srcHeld) || isConvertable(srcHeld, dest))
770             return true;
771       }
772
773       if (isEncoded == false)
774       {
775          if (isBeanCompatible(dest) && getConstructorForClass(dest, src) != null && getAccessorForClass(dest, src) != null)
776             return true;
777          if (isBeanCompatible(src) && getConstructorForClass(src, dest) != null && getAccessorForClass(src, dest) != null)
778             return true;
779       }
780
781       // convert will always unwrap an attachment, so this is ok
782
if (src.isAssignableFrom(AttachmentPartImpl.class))
783          return true;
784
785       // If it's a MIME type mapping and we want a DataHandler,
786
// then we're good.
787
if (dest.getName().equals("javax.activation.DataHandler"))
788       {
789          String JavaDoc name = src.getName();
790          if (src == String JavaDoc.class
791                  || src == java.awt.Image JavaDoc.class
792                  || src == OctetStream.class
793                  || name.equals("javax.mail.internet.MimeMultipart")
794                  || name.equals("javax.xml.transform.Source"))
795             return true;
796       }
797
798       if (src.getName().equals("javax.activation.DataHandler"))
799       {
800          if (dest == byte[].class)
801             return true;
802          if (dest.isArray() && dest.getComponentType() == byte[].class)
803             return true;
804       }
805
806       if (dest.getName().equals("javax.activation.DataHandler"))
807       {
808          if (src == Object JavaDoc[].class)
809             return true;
810          if (src.isArray() && src.getComponentType() == Object JavaDoc[].class)
811             return true;
812       }
813
814       if (obj instanceof java.io.InputStream JavaDoc)
815       {
816          if (dest == OctetStream.class)
817             return true;
818       }
819
820       if (src.isPrimitive())
821       {
822          return isConvertable(getWrapperClass(src), dest);
823       }
824
825       log.debug("Not convertible: [src=" + src + ",dest=" + dest + "]");
826       return false;
827    }
828
829    /** Throws an IllegalStateException if class names correspond but ClassLoaders do not.
830     */

831    private static void assertClassLoaders(Class JavaDoc src, Class JavaDoc dest)
832    {
833       if (src.getName().equals(dest.getName()) && src.getClassLoader() != dest.getClassLoader())
834       {
835          throw new IllegalStateException JavaDoc("Class loading conflict detected: " + src.getName() +
836                  "\nsrcCL=" + src.getClassLoader() +
837                  "\ndestCL=" + dest.getClassLoader());
838       }
839    }
840
841    private static Method JavaDoc getAccessorForClass(Class JavaDoc bean, Class JavaDoc param)
842    {
843       try
844       {
845          Method JavaDoc[] methods = bean.getMethods();
846          for (int i = 0; i < methods.length; i++)
847          {
848             Method JavaDoc getter = methods[i];
849             String JavaDoc name = getter.getName();
850             Class JavaDoc returnType = getter.getReturnType();
851             if (name.startsWith("get") && getter.getParameterTypes().length == 0 && isConvertable(returnType, param))
852             {
853                name = "set" + name.substring(3);
854                bean.getMethod(name, new Class JavaDoc[]{returnType});
855                return getter;
856             }
857          }
858          return null;
859       }
860       catch (NoSuchMethodException JavaDoc e)
861       {
862          return null;
863       }
864    }
865
866    private static Constructor JavaDoc getConstructorForClass(Class JavaDoc bean, Class JavaDoc param)
867    {
868       Constructor JavaDoc[] ctors = bean.getConstructors();
869       for (int i = 0; i < ctors.length; i++)
870       {
871          Constructor JavaDoc ctor = ctors[i];
872          Class JavaDoc[] paramTypes = ctor.getParameterTypes();
873          if (paramTypes != null && paramTypes.length == 1)
874          {
875             if (isConvertable(param, paramTypes[0]))
876                return ctor;
877          }
878       }
879       return null;
880    }
881
882    /**
883     * isBeanCompatible
884     *
885     * @param javaType Class
886     */

887    public static boolean isBeanCompatible(Class JavaDoc javaType)
888    {
889
890       // Must be a non-primitive and non array
891
if (javaType.isArray() || javaType.isPrimitive())
892       {
893          return false;
894       }
895
896       // Anything in the java or javax package that
897
// does not have a defined mapping is excluded.
898
if (javaType.getName().startsWith("java.") || javaType.getName().startsWith("javax."))
899       {
900          return false;
901       }
902
903       // Return true if appears to be an enums class
904
if (JavaUtils.isEnumClass(javaType))
905       {
906          return true;
907       }
908
909       // Must have a default public constructor if not Throwable
910
if (!java.lang.Throwable JavaDoc.class.isAssignableFrom(javaType))
911       {
912          try
913          {
914             javaType.getConstructor(new Class JavaDoc[]{});
915          }
916          catch (java.lang.NoSuchMethodException JavaDoc e)
917          {
918             return false;
919          }
920       }
921
922       // Make sure superclass is compatible
923
Class JavaDoc superClass = javaType.getSuperclass();
924       if (superClass != null &&
925               superClass != java.lang.Object JavaDoc.class &&
926               superClass != java.lang.Exception JavaDoc.class &&
927               superClass != java.lang.Throwable JavaDoc.class &&
928               superClass != java.rmi.RemoteException JavaDoc.class &&
929               superClass != org.jboss.axis.AxisFault.class)
930       {
931
932          if (!isBeanCompatible(superClass))
933          {
934             return false;
935          }
936       }
937       return true;
938    }
939
940    public static Image getImageFromStream(InputStream JavaDoc is)
941    {
942       try
943       {
944          return ImageIOFactory.getImageIO().loadImage(is);
945       }
946       catch (Throwable JavaDoc t)
947       {
948          return null;
949       }
950    } // getImageFromStream
951

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

959    static final String JavaDoc keywords[] =
960            {
961               "abstract", "assert", "boolean", "break", "byte", "case",
962               "catch", "char", "class", "const", "continue",
963               "default", "do", "double", "else", "extends",
964               "false", "final", "finally", "float", "for",
965               "goto", "if", "implements", "import", "instanceof",
966               "int", "interface", "long", "native", "new",
967               "null", "package", "private", "protected", "public",
968               "return", "short", "static", "strictfp", "super",
969               "switch", "synchronized", "this", "throw", "throws",
970               "transient", "true", "try", "void", "volatile",
971               "while"
972            };
973
974    /**
975     * Collator for comparing the strings
976     */

977    static final Collator JavaDoc englishCollator = Collator.getInstance(Locale.ENGLISH);
978
979    /**
980     * Use this character as suffix
981     */

982    static final char keywordPrefix = '_';
983
984    /**
985     * isJavaId
986     * Returns true if the name is a valid java identifier.
987     *
988     * @param id to check
989     * @return boolean true/false
990     */

991    public static boolean isJavaId(String JavaDoc id)
992    {
993       if (id == null || id.equals("") || isJavaKeyword(id))
994          return false;
995       if (!Character.isJavaIdentifierStart(id.charAt(0)))
996          return false;
997       for (int i = 1; i < id.length(); i++)
998          if (!Character.isJavaIdentifierPart(id.charAt(i)))
999             return false;
1000      return true;
1001   }
1002
1003   /**
1004    * checks if the input string is a valid java keyword.
1005    *
1006    * @return boolean true/false
1007    */

1008   public static boolean isJavaKeyword(String JavaDoc keyword)
1009   {
1010      return (Arrays.binarySearch(keywords, keyword, englishCollator) >= 0);
1011   }
1012
1013   /**
1014    * Turn a java keyword string into a non-Java keyword string. (Right now
1015    * this simply means appending an underscore.)
1016    */

1017   public static String JavaDoc makeNonJavaKeyword(String JavaDoc keyword)
1018   {
1019      return keywordPrefix + keyword;
1020   }
1021
1022   /**
1023    * Converts text of the form
1024    * Foo[] to the proper class name for loading [LFoo
1025    */

1026   public static String JavaDoc getLoadableClassName(String JavaDoc text)
1027   {
1028      if (text == null ||
1029              text.indexOf("[") < 0 ||
1030              text.charAt(0) == '[')
1031         return text;
1032      String JavaDoc className = text.substring(0, text.indexOf("["));
1033      if (className.equals("byte"))
1034         className = "B";
1035      else if (className.equals("char"))
1036         className = "C";
1037      else if (className.equals("double"))
1038         className = "D";
1039      else if (className.equals("float"))
1040         className = "F";
1041      else if (className.equals("int"))
1042         className = "I";
1043      else if (className.equals("long"))
1044         className = "J";
1045      else if (className.equals("short"))
1046         className = "S";
1047      else if (className.equals("boolean"))
1048         className = "Z";
1049      else
1050         className = "L" + className + ";";
1051      int i = text.indexOf("]");
1052      while (i > 0)
1053      {
1054         className = "[" + className;
1055         i = text.indexOf("]", i + 1);
1056      }
1057      return className;
1058   }
1059
1060   /**
1061    * Converts text of the form
1062    * [LFoo to the Foo[]
1063    */

1064   public static String JavaDoc getTextClassName(String JavaDoc text)
1065   {
1066      if (text == null ||
1067              text.indexOf("[") != 0)
1068         return text;
1069      String JavaDoc className = "";
1070      int index = 0;
1071      while (index < text.length() &&
1072              text.charAt(index) == '[')
1073      {
1074         index++;
1075         className += "[]";
1076      }
1077      if (index < text.length())
1078      {
1079         if (text.charAt(index) == 'B')
1080            className = "byte" + className;
1081         else if (text.charAt(index) == 'C')
1082            className = "char" + className;
1083         else if (text.charAt(index) == 'D')
1084            className = "double" + className;
1085         else if (text.charAt(index) == 'F')
1086            className = "float" + className;
1087         else if (text.charAt(index) == 'I')
1088            className = "int" + className;
1089         else if (text.charAt(index) == 'J')
1090            className = "long" + className;
1091         else if (text.charAt(index) == 'S')
1092            className = "short" + className;
1093         else if (text.charAt(index) == 'Z')
1094            className = "boolean" + className;
1095         else
1096         {
1097            className = text.substring(index + 1, text.indexOf(";")) + className;
1098         }
1099      }
1100      return className;
1101   }
1102
1103   /**
1104    * Map an XML name to a Java identifier per
1105    * the mapping rules of JSR 101 (in version 1.0 this is
1106    * "Chapter 20: Appendix: Mapping of XML Names"
1107    *
1108    * @param name is the xml name
1109    * @return the java name per JSR 101 specification
1110    */

1111   public static String JavaDoc xmlNameToJava(String JavaDoc name)
1112   {
1113      // protect ourselves from garbage
1114
if (name == null || name.equals(""))
1115         return name;
1116
1117      char[] nameArray = name.toCharArray();
1118      int nameLen = name.length();
1119      StringBuffer JavaDoc result = new StringBuffer JavaDoc(nameLen);
1120      boolean wordStart = false;
1121
1122      // The mapping indicates to convert first character.
1123
int i = 0;
1124      while (i < nameLen
1125              && (isPunctuation(nameArray[i])
1126              || !Character.isJavaIdentifierStart(nameArray[i])))
1127      {
1128         i++;
1129      }
1130      if (i < nameLen)
1131      {
1132         // Decapitalization code used to be here, but we use the
1133
// Introspector function now after we filter out all bad chars.
1134

1135         result.append(nameArray[i]);
1136         //wordStart = !Character.isLetter(nameArray[i]);
1137
wordStart = !Character.isLetter(nameArray[i]) && nameArray[i] != "_".charAt(0);
1138      }
1139      else
1140      {
1141         // The identifier cannot be mapped strictly according to JSR 101
1142
if (Character.isJavaIdentifierPart(nameArray[0]))
1143         {
1144            result.append("_" + nameArray[0]);
1145         }
1146         else
1147         {
1148            // The XML identifier does not contain any characters
1149
// we can map to Java. Using the length of the string
1150
// will make it somewhat unique.
1151
result.append("_" + nameArray.length);
1152         }
1153      }
1154
1155      // The mapping indicates to skip over all characters that are not letters or digits.
1156
// The first letter/digit following a skipped character is upper-cased.
1157
for (++i; i < nameLen; ++i)
1158      {
1159         char c = nameArray[i];
1160
1161         // if this is a bad char, skip it and remember to capitalize next good character we encounter
1162
if (isPunctuation(c) || !Character.isJavaIdentifierPart(c))
1163         {
1164            wordStart = true;
1165            continue;
1166         }
1167         if (wordStart && Character.isLowerCase(c))
1168         {
1169            result.append(Character.toUpperCase(c));
1170         }
1171         else
1172         {
1173            result.append(c);
1174         }
1175         // If c is not a character, but is a legal Java identifier character, capitalize the next character.
1176
// For example: "22hi" becomes "22Hi"
1177
wordStart = !Character.isLetter(c) && c != "_".charAt(0);
1178      }
1179
1180      // covert back to a String
1181
String JavaDoc newName = result.toString();
1182
1183      // Follow JavaBean rules, but we need to check if the first
1184
// letter is uppercase first
1185
if (Character.isUpperCase(newName.charAt(0)))
1186         newName = Introspector.decapitalize(newName);
1187
1188      // check for Java keywords
1189
if (isJavaKeyword(newName))
1190         newName = makeNonJavaKeyword(newName);
1191
1192      return newName;
1193   } // xmlNameToJava
1194

1195   /**
1196    * Is this an XML punctuation character?
1197    */

1198   private static boolean isPunctuation(char c)
1199   {
1200      return '-' == c
1201              || '.' == c
1202              || ':' == c
1203              || '\u00B7' == c
1204              || '\u0387' == c
1205              || '\u06DD' == c
1206              || '\u06DE' == c;
1207   } // isPunctuation
1208

1209
1210   /**
1211    * replace:
1212    * Like String.replace except that the old new items are strings.
1213    *
1214    * @param name string
1215    * @param oldT old text to replace
1216    * @param newT new text to use
1217    * @return replacement string
1218    */

1219   public static final String JavaDoc replace(String JavaDoc name,
1220                                      String JavaDoc oldT, String JavaDoc newT)
1221   {
1222
1223      if (name == null) return "";
1224
1225// Create a string buffer that is twice initial length.
1226
// This is a good starting point.
1227
StringBuffer JavaDoc sb = new StringBuffer JavaDoc(name.length() * 2);
1228
1229      int len = oldT.length();
1230      try
1231      {
1232         int start = 0;
1233         int i = name.indexOf(oldT, start);
1234
1235         while (i >= 0)
1236         {
1237            sb.append(name.substring(start, i));
1238            sb.append(newT);
1239            start = i + len;
1240            i = name.indexOf(oldT, start);
1241         }
1242         if (start < name.length())
1243            sb.append(name.substring(start));
1244      }
1245      catch (NullPointerException JavaDoc e)
1246      {
1247      }
1248
1249      return new String JavaDoc(sb);
1250   }
1251
1252   /**
1253    * Determines if the Holder Class for a given held class.
1254    *
1255    * @param type the held class
1256    * @return holder class or null
1257    */

1258   public static Class JavaDoc getHolderType(Class JavaDoc type)
1259   {
1260      if (javax.xml.rpc.holders.Holder JavaDoc.class.isAssignableFrom(type))
1261         throw new IllegalArgumentException JavaDoc("Is already a holder type: " + type);
1262
1263      if (type == BigDecimal JavaDoc.class)
1264         return BigDecimalHolder.class;
1265      if (type == BigInteger JavaDoc.class)
1266         return BigIntegerHolder.class;
1267      if (type == boolean.class)
1268         return BooleanHolder.class;
1269      if (type == Boolean JavaDoc.class)
1270         return BooleanWrapperHolder.class;
1271      if (type == byte[].class)
1272         return ByteArrayHolder.class;
1273      if (type == byte.class)
1274         return ByteHolder.class;
1275      if (type == Byte JavaDoc.class)
1276         return ByteWrapperHolder.class;
1277      if (type == Calendar JavaDoc.class)
1278         return CalendarHolder.class;
1279      if (type == double.class)
1280         return DoubleHolder.class;
1281      if (type == Double JavaDoc.class)
1282         return DoubleWrapperHolder.class;
1283      if (type == float.class)
1284         return FloatHolder.class;
1285      if (type == Float JavaDoc.class)
1286         return FloatWrapperHolder.class;
1287      if (type == int.class)
1288         return IntHolder.class;
1289      if (type == Integer JavaDoc.class)
1290         return IntegerWrapperHolder.class;
1291      if (type == long.class)
1292         return LongHolder.class;
1293      if (type == Long JavaDoc.class)
1294         return LongWrapperHolder.class;
1295      if (type == QName JavaDoc.class)
1296         return QNameHolder.class;
1297      if (type == short.class)
1298         return ShortHolder.class;
1299      if (type == Short JavaDoc.class)
1300         return ShortWrapperHolder.class;
1301      if (type == String JavaDoc.class)
1302         return StringHolder.class;
1303      if (type == Object JavaDoc.class)
1304         return ObjectHolder.class;
1305
1306      return null;
1307   }
1308
1309   /**
1310    * Determines if the Class is a Holder class. If so returns Class of held type
1311    * else returns null
1312    *
1313    * @param type the suspected Holder Class
1314    * @return class of held type or null
1315    */

1316   public static Class JavaDoc getHolderValueType(Class JavaDoc type)
1317   {
1318      if (type != null)
1319      {
1320         Class JavaDoc[] intf = type.getInterfaces();
1321         boolean isHolder = false;
1322         for (int i = 0; i < intf.length && !isHolder; i++)
1323         {
1324            if (intf[i] == javax.xml.rpc.holders.Holder JavaDoc.class)
1325            {
1326               isHolder = true;
1327            }
1328         }
1329         if (isHolder == false)
1330         {
1331            return null;
1332         }
1333
1334// Holder is supposed to have a public value field.
1335
java.lang.reflect.Field JavaDoc field;
1336         try
1337         {
1338            field = type.getField("value");
1339         }
1340         catch (Exception JavaDoc e)
1341         {
1342            field = null;
1343         }
1344         if (field != null)
1345         {
1346            return field.getType();
1347         }
1348      }
1349      return null;
1350   }
1351
1352   /**
1353    * Gets the Holder value.
1354    *
1355    * @param holder Holder object
1356    * @return value object
1357    */

1358   public static Object JavaDoc getHolderValue(Object JavaDoc holder) throws HolderException
1359   {
1360      if (!(holder instanceof javax.xml.rpc.holders.Holder JavaDoc))
1361      {
1362         throw new HolderException(Messages.getMessage("badHolder00"));
1363      }
1364      try
1365      {
1366         Field JavaDoc valueField = holder.getClass().getField("value");
1367         return valueField.get(holder);
1368      }
1369      catch (Exception JavaDoc e)
1370      {
1371         throw new HolderException(Messages.getMessage("exception01", e.getMessage()));
1372      }
1373   }
1374
1375   /**
1376    * Sets the Holder value.
1377    *
1378    * @param holder Holder object
1379    * @param value is the object value
1380    */

1381   public static void setHolderValue(Object JavaDoc holder, Object JavaDoc value) throws HolderException
1382   {
1383      if (!(holder instanceof javax.xml.rpc.holders.Holder JavaDoc))
1384      {
1385         throw new HolderException(Messages.getMessage("badHolder00"));
1386      }
1387      try
1388      {
1389         Field JavaDoc valueField = holder.getClass().getField("value");
1390         if (valueField.getType().isPrimitive())
1391         {
1392            if (value != null)
1393            {
1394               valueField.set(holder, value); // Automatically unwraps value to primitive
1395
}
1396         }
1397         else
1398         {
1399            valueField.set(holder, value);
1400         }
1401      }
1402      catch (Exception JavaDoc e)
1403      {
1404         log.error("Cannot set holder value '" + value + "' on " + holder.getClass().getName(), e);
1405         throw new HolderException(Messages.getMessage("exception01", e.getMessage()));
1406      }
1407   }
1408
1409   public static class HolderException extends Exception JavaDoc
1410   {
1411      public HolderException(String JavaDoc msg)
1412      {
1413         super(msg);
1414      }
1415   }
1416
1417
1418   /**
1419    * Determine if the class is a JAX-RPC enums class.
1420    * An enumeration class is recognized by
1421    * a getValue() method, a toString() method, a fromString(String) method
1422    * a fromValue(type) method and the lack
1423    * of a setValue(type) method
1424    */

1425   public static boolean isEnumClass(Class JavaDoc cls)
1426   {
1427      try
1428      {
1429         java.lang.reflect.Method JavaDoc m = cls.getMethod("getValue", null);
1430         java.lang.reflect.Method JavaDoc m2 = cls.getMethod("toString", null);
1431         java.lang.reflect.Method JavaDoc m3 = cls.getMethod("fromString",
1432                 new Class JavaDoc[]{java.lang.String JavaDoc.class});
1433
1434         if (m != null && m2 != null && m3 != null &&
1435                 cls.getMethod("fromValue", new Class JavaDoc[]{m.getReturnType()}) != null)
1436         {
1437            try
1438            {
1439               if (cls.getMethod("setValue", new Class JavaDoc[]{m.getReturnType()}) == null)
1440                  return true;
1441               return false;
1442            }
1443            catch (java.lang.NoSuchMethodException JavaDoc e)
1444            {
1445               return true; // getValue & fromValue exist. setValue does not exist. Thus return true.
1446
}
1447         }
1448      }
1449      catch (java.lang.NoSuchMethodException JavaDoc e)
1450      {
1451      }
1452      return false;
1453   }
1454
1455   /**
1456    * Determine if the class is an array
1457    * TDI 20-June-2004
1458    */

1459   public static boolean isArrayClass(Class JavaDoc cls)
1460   {
1461      String JavaDoc className = cls.getName();
1462      return className.startsWith("[");
1463   }
1464
1465   public static String JavaDoc stackToString(Throwable JavaDoc e)
1466   {
1467      java.io.StringWriter JavaDoc sw = new java.io.StringWriter JavaDoc(1024);
1468      java.io.PrintWriter JavaDoc pw = new java.io.PrintWriter JavaDoc(sw);
1469      e.printStackTrace(pw);
1470      pw.close();
1471      return sw.toString();
1472   }
1473
1474   /**
1475    * Tests the String 'value':
1476    * return 'false' if its 'false', '0', or 'no' - else 'true'
1477    * <p/>
1478    * Follow in 'C' tradition of boolean values:
1479    * false is specific (0), everything else is true;
1480    */

1481   public static final boolean isTrue(String JavaDoc value)
1482   {
1483      return !isFalseExplicitly(value);
1484   }
1485
1486   /**
1487    * Tests the String 'value':
1488    * return 'true' if its 'true', '1', or 'yes' - else 'false'
1489    */

1490   public static final boolean isTrueExplicitly(String JavaDoc value)
1491   {
1492      return value != null &&
1493              (value.equalsIgnoreCase("true") ||
1494              value.equals("1") ||
1495              value.equalsIgnoreCase("yes"));
1496   }
1497
1498   /**
1499    * Tests the Object 'value':
1500    * if its null, return default.
1501    * if its a Boolean, return booleanValue()
1502    * if its an Integer, return 'false' if its '0' else 'true'
1503    * if its a String, return isTrueExplicitly((String)value).
1504    * All other types return 'true'
1505    */

1506   public static final boolean isTrueExplicitly(Object JavaDoc value, boolean defaultVal)
1507   {
1508      if (value == null) return defaultVal;
1509      if (value instanceof Boolean JavaDoc)
1510      {
1511         return ((Boolean JavaDoc)value).booleanValue();
1512      }
1513      if (value instanceof Integer JavaDoc)
1514      {
1515         return ((Integer JavaDoc)value).intValue() != 0;
1516      }
1517      if (value instanceof String JavaDoc)
1518      {
1519         return isTrueExplicitly((String JavaDoc)value);
1520      }
1521      return true;
1522   }
1523
1524   public static final boolean isTrueExplicitly(Object JavaDoc value)
1525   {
1526      return isTrueExplicitly(value, false);
1527   }
1528
1529   /**
1530    * Tests the Object 'value':
1531    * if its null, return default.
1532    * if its a Boolean, return booleanValue()
1533    * if its an Integer, return 'false' if its '0' else 'true'
1534    * if its a String, return 'false' if its 'false', 'no', or '0' - else 'true'
1535    * All other types return 'true'
1536    */

1537   public static final boolean isTrue(Object JavaDoc value, boolean defaultVal)
1538   {
1539      return !isFalseExplicitly(value, !defaultVal);
1540   }
1541
1542   public static final boolean isTrue(Object JavaDoc value)
1543   {
1544      return isTrue(value, false);
1545   }
1546
1547   /**
1548    * Tests the String 'value':
1549    * return 'true' if its 'false', '0', or 'no' - else 'false'
1550    * <p/>
1551    * Follow in 'C' tradition of boolean values:
1552    * false is specific (0), everything else is true;
1553    */

1554   public static final boolean isFalse(String JavaDoc value)
1555   {
1556      return isFalseExplicitly(value);
1557   }
1558
1559   /**
1560    * Tests the String 'value':
1561    * return 'true' if its null, 'false', '0', or 'no' - else 'false'
1562    */

1563   public static final boolean isFalseExplicitly(String JavaDoc value)
1564   {
1565      return value == null ||
1566              value.equalsIgnoreCase("false") ||
1567              value.equals("0") ||
1568              value.equalsIgnoreCase("no");
1569   }
1570
1571   /**
1572    * Tests the Object 'value':
1573    * if its null, return default.
1574    * if its a Boolean, return !booleanValue()
1575    * if its an Integer, return 'true' if its '0' else 'false'
1576    * if its a String, return isFalseExplicitly((String)value).
1577    * All other types return 'false'
1578    */

1579   public static final boolean isFalseExplicitly(Object JavaDoc value, boolean defaultVal)
1580   {
1581      if (value == null) return defaultVal;
1582      if (value instanceof Boolean JavaDoc)
1583      {
1584         return !((Boolean JavaDoc)value).booleanValue();
1585      }
1586      if (value instanceof Integer JavaDoc)
1587      {
1588         return ((Integer JavaDoc)value).intValue() == 0;
1589      }
1590      if (value instanceof String JavaDoc)
1591      {
1592         return isFalseExplicitly((String JavaDoc)value);
1593      }
1594      return false;
1595   }
1596
1597   public static final boolean isFalseExplicitly(Object JavaDoc value)
1598   {
1599      return isFalseExplicitly(value, true);
1600   }
1601
1602   /**
1603    * Tests the Object 'value':
1604    * if its null, return default.
1605    * if its a Boolean, return booleanValue()
1606    * if its an Integer, return 'false' if its '0' else 'true'
1607    * if its a String, return 'false' if its 'false', 'no', or '0' - else 'true'
1608    * All other types return 'true'
1609    */

1610   public static final boolean isFalse(Object JavaDoc value, boolean defaultVal)
1611   {
1612      return isFalseExplicitly(value, defaultVal);
1613   }
1614
1615   public static final boolean isFalse(Object JavaDoc value)
1616   {
1617      return isFalse(value, true);
1618   }
1619
1620   /**
1621    * Given the MIME type string, return the Java mapping.
1622    */

1623   public static String JavaDoc mimeToJava(String JavaDoc mime)
1624   {
1625      if ("image/gif".equals(mime) || "image/jpeg".equals(mime))
1626      {
1627         return "java.awt.Image";
1628      }
1629      else if ("text/plain".equals(mime))
1630      {
1631         return "java.lang.String";
1632      }
1633      else if ("text/xml".equals(mime) || "application/xml".equals(mime))
1634      {
1635         return "javax.xml.transform.Source";
1636      }
1637      else if ("application/octetstream".equals(mime))
1638      {
1639         return "org.jboss.axis.attachments.OctetStream";
1640      }
1641      else if (mime != null && mime.startsWith("multipart/"))
1642      {
1643         return "javax.mail.internet.MimeMultipart";
1644      }
1645      else
1646      {
1647         return null;
1648      }
1649   } // mimeToJava
1650

1651//avoid testing and possibly failing everytime.
1652
private static boolean checkForAttachmentSupport = true;
1653   private static boolean attachmentSupportEnabled = false;
1654
1655   /**
1656    * Determine whether attachments are supported by checking if the following
1657    * classes are available: javax.activation.DataHandler,
1658    * javax.mail.internet.MimeMultipart.
1659    */

1660   public static synchronized boolean isAttachmentSupported()
1661   {
1662
1663      if (checkForAttachmentSupport)
1664      {
1665         //aviod testing and possibly failing everytime.
1666
checkForAttachmentSupport = false;
1667         try
1668         {
1669// Attempt to resolve DataHandler and MimeMultipart and
1670
// javax.xml.transform.Source, all necessary for full
1671
// attachment support
1672
ClassUtils.forName("javax.activation.DataHandler");
1673            ClassUtils.forName("javax.mail.internet.MimeMultipart");
1674            attachmentSupportEnabled = true;
1675         }
1676         catch (Throwable JavaDoc t)
1677         {
1678         }
1679         log.debug(Messages.getMessage("attachEnabled") + " " +
1680                 attachmentSupportEnabled);
1681      }
1682
1683      return attachmentSupportEnabled;
1684   } // isAttachmentSupported
1685
}
1686
Popular Tags