File: JavaUtils.java

package info (click to toggle)
libjboss-web-services-java 0.0%2Bsvn5660%2Bdak2-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 7,276 kB
  • sloc: java: 79,207; xml: 29; makefile: 19; sh: 16
file content (649 lines) | stat: -rw-r--r-- 19,725 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.wsf.common;

// $Id: JavaUtils.java 3959 2007-07-20 14:44:19Z heiko.braun@jboss.com $

import java.lang.reflect.*;
import java.util.HashMap;
import java.util.HashSet;

import org.jboss.logging.Logger;

/** Java utilities
 *
 * @author Thomas.Diesler@jboss.org
 * @since 22-Dec-2004
 */
public class JavaUtils
{
   // provide logging
   private static final Logger log = Logger.getLogger(JavaUtils.class);

   private static HashMap<String, Class> primitiveNames = new HashMap<String, Class>(8);
   private static HashMap<String, String> primitiveNameDescriptors = new HashMap<String, String>(8);
   private static HashSet<String> reservedKeywords = new HashSet<String>(50);

   static
   {
      primitiveNames.put("int", int.class);
      primitiveNames.put("short", short.class);
      primitiveNames.put("boolean", boolean.class);
      primitiveNames.put("byte", byte.class);
      primitiveNames.put("long", long.class);
      primitiveNames.put("double", double.class);
      primitiveNames.put("float", float.class);
      primitiveNames.put("char", char.class);

      primitiveNameDescriptors.put("int", "I");
      primitiveNameDescriptors.put("short", "S");
      primitiveNameDescriptors.put("boolean", "Z");
      primitiveNameDescriptors.put("byte", "B");
      primitiveNameDescriptors.put("long", "J");
      primitiveNameDescriptors.put("double", "D");
      primitiveNameDescriptors.put("float", "F");
      primitiveNameDescriptors.put("char", "C");

      reservedKeywords.add("abstract");
      reservedKeywords.add("continue");
      reservedKeywords.add("for");
      reservedKeywords.add("new");
      reservedKeywords.add("switch");
      reservedKeywords.add("assert");
      reservedKeywords.add("default");
      reservedKeywords.add("if");
      reservedKeywords.add("package");
      reservedKeywords.add("synchronized");
      reservedKeywords.add("boolean");
      reservedKeywords.add("do");
      reservedKeywords.add("goto");
      reservedKeywords.add("private");
      reservedKeywords.add("this");
      reservedKeywords.add("break");
      reservedKeywords.add("double");
      reservedKeywords.add("implements");
      reservedKeywords.add("protected");
      reservedKeywords.add("throw");
      reservedKeywords.add("byte");
      reservedKeywords.add("else");
      reservedKeywords.add("import");
      reservedKeywords.add("public");
      reservedKeywords.add("throws");
      reservedKeywords.add("case");
      reservedKeywords.add("enum");
      reservedKeywords.add("instanceof");
      reservedKeywords.add("return");
      reservedKeywords.add("transient");
      reservedKeywords.add("catch");
      reservedKeywords.add("extends");
      reservedKeywords.add("int");
      reservedKeywords.add("short");
      reservedKeywords.add("try");
      reservedKeywords.add("char");
      reservedKeywords.add("final");
      reservedKeywords.add("interface");
      reservedKeywords.add("static");
      reservedKeywords.add("void");
      reservedKeywords.add("class");
      reservedKeywords.add("finally");
      reservedKeywords.add("long");
      reservedKeywords.add("strictfp");
      reservedKeywords.add("volatile");
      reservedKeywords.add("const");
      reservedKeywords.add("float");
      reservedKeywords.add("native");
      reservedKeywords.add("super");
      reservedKeywords.add("while");
   }

   /**
    * Load a Java type from a given class loader.
    *
    * @param typeName maybe the source notation of a primitve, class name, array of both
    */
   public static Class loadJavaType(String typeName) throws ClassNotFoundException
   {
      return loadJavaType(typeName, null);
   }

   /**
    * Load a Java type from a given class loader.
    *
    * @param typeName maybe the source notation of a primitve, class name, array of both
    */
   public static Class loadJavaType(String typeName, ClassLoader classLoader) throws ClassNotFoundException
   {
      if (classLoader == null)
         classLoader = Thread.currentThread().getContextClassLoader();

      Class javaType = primitiveNames.get(typeName);
      if (javaType == null)
         javaType = getArray(typeName, classLoader);

      if (javaType == null)
         javaType = classLoader.loadClass(typeName);

      return javaType;
   }

   /**
    * True if the given type name is the source notation of a primitive or array of which.
    */
   public static boolean isPrimitive(String javaType)
   {
      return getPrimitiveType(javaType) != null;
   }

   /**
    * True if the given class is a primitive or array of which.
    */
   public static boolean isPrimitive(Class javaType)
   {
      return javaType.isPrimitive() || (javaType.isArray() && isPrimitive(javaType.getComponentType()));
   }

   public static Class getPrimitiveType(String javaType)
   {
      Class type = primitiveNames.get(javaType);
      if (type != null)
         return type;

      try
      {
         // null loader = primitive only
         type = getArray(javaType, null);
      }
      catch (ClassNotFoundException e)
      {
         // This will actually never be thrown since is null
      }

      return type;
   }

   private static Class getArray(String javaType, ClassLoader loader) throws ClassNotFoundException
   {
      if (javaType.charAt(0) == '[')
         return getArrayFromJVMName(javaType, loader);

      if (javaType.endsWith("[]"))
         return getArrayFromSourceName(javaType, loader);

      return null;
   }

   private static Class getArrayFromJVMName(String javaType, ClassLoader loader) throws ClassNotFoundException
   {
      Class componentType;
      int componentStart = javaType.lastIndexOf('[') + 1;
      switch (javaType.charAt(componentStart))
      {
         case 'I': componentType = int.class; break;
         case 'S': componentType = short.class; break;
         case 'Z': componentType = boolean.class; break;
         case 'B': componentType = byte.class; break;
         case 'J': componentType = long.class; break;
         case 'D': componentType = double.class; break;
         case 'F': componentType = float.class; break;
         case 'C': componentType = char.class; break;
         case 'L':
            if (loader == null)
               return null;
            String name = javaType.substring(componentStart + 1, javaType.length() - 1);
            componentType = loader.loadClass(name);
            break;
         default:
            throw new IllegalArgumentException("Invalid binary component for array: " + javaType.charAt(componentStart));
      }

      // componentStart doubles as the number of '['s which is the number of dimensions
      return Array.newInstance(componentType, new int[componentStart]).getClass();
   }

   private static Class getArrayFromSourceName(String javaType, ClassLoader loader) throws ClassNotFoundException
   {
      int arrayStart = javaType.indexOf('[');
      String componentName = javaType.substring(0, arrayStart);

      Class componentType = primitiveNames.get(componentName);
      if (componentType == null)
      {
         if (loader == null)
            return null;

         componentType = loader.loadClass(componentName);
      }

      // [][][][] divided by 2
      int dimensions = (javaType.length() - arrayStart) >> 1;

      return Array.newInstance(componentType, new int[dimensions]).getClass();
   }

   /**
    * Get the corresponding primitive for a give wrapper type.
    * Also handles arrays of which.
    */
   public static Class getPrimitiveType(Class javaType)
   {
      if (javaType == Integer.class)
         return int.class;
      if (javaType == Short.class)
         return short.class;
      if (javaType == Boolean.class)
         return boolean.class;
      if (javaType == Byte.class)
         return byte.class;
      if (javaType == Long.class)
         return long.class;
      if (javaType == Double.class)
         return double.class;
      if (javaType == Float.class)
         return float.class;
      if (javaType == Character.class)
         return char.class;

      if (javaType == Integer[].class)
         return int[].class;
      if (javaType == Short[].class)
         return short[].class;
      if (javaType == Boolean[].class)
         return boolean[].class;
      if (javaType == Byte[].class)
         return byte[].class;
      if (javaType == Long[].class)
         return long[].class;
      if (javaType == Double[].class)
         return double[].class;
      if (javaType == Float[].class)
         return float[].class;
      if (javaType == Character[].class)
         return char[].class;

      if (javaType.isArray() && javaType.getComponentType().isArray())
      {
         Class compType = getPrimitiveType(javaType.getComponentType());
         return Array.newInstance(compType, 0).getClass();
      }

      return javaType;
   }

   /**
    * Converts an n-dimensional array of wrapper types to primitive types
    */
   public static Object getPrimitiveValueArray(Object value)
   {
      if (value == null)
         return null;

      Class javaType = value.getClass();
      if (javaType.isArray())
      {
         int length = Array.getLength(value);
         Object destArr = Array.newInstance(getPrimitiveType(javaType.getComponentType()), length);
         for (int i = 0; i < length; i++)
         {
            Object srcObj = Array.get(value, i);
            Array.set(destArr, i, getPrimitiveValueArray(srcObj));
         }
         return destArr;
      }

      return value;
   }

   /**
    * Get the corresponding wrapper type for a give primitive.
    * Also handles arrays of which.
    */
   public static Class getWrapperType(Class javaType)
   {
      if (javaType == int.class)
         return Integer.class;
      if (javaType == short.class)
         return Short.class;
      if (javaType == boolean.class)
         return Boolean.class;
      if (javaType == byte.class)
         return Byte.class;
      if (javaType == long.class)
         return Long.class;
      if (javaType == double.class)
         return Double.class;
      if (javaType == float.class)
         return Float.class;
      if (javaType == char.class)
         return Character.class;

      if (javaType == int[].class)
         return Integer[].class;
      if (javaType == short[].class)
         return Short[].class;
      if (javaType == boolean[].class)
         return Boolean[].class;
      if (javaType == byte[].class)
         return Byte[].class;
      if (javaType == long[].class)
         return Long[].class;
      if (javaType == double[].class)
         return Double[].class;
      if (javaType == float[].class)
         return Float[].class;
      if (javaType == char[].class)
         return Character[].class;

      if (javaType.isArray() && javaType.getComponentType().isArray())
      {
         Class compType = getWrapperType(javaType.getComponentType());
         return Array.newInstance(compType, 0).getClass();
      }

      return javaType;
   }

   /**
    * Converts an n-dimensional array of primitive types to wrapper types
    */
   public static Object getWrapperValueArray(Object value)
   {
      if (value == null)
         return null;

      Class javaType = value.getClass();
      if (javaType.isArray())
      {
         int length = Array.getLength(value);
         Object destArr = Array.newInstance(getWrapperType(javaType.getComponentType()), length);
         for (int i = 0; i < length; i++)
         {
            Object srcObj = Array.get(value, i);
            Array.set(destArr, i, getWrapperValueArray(srcObj));
         }
         return destArr;
      }

      return value;
   }

   public static Object syncArray(Object array, Class target)
   {
      return (JavaUtils.isPrimitive(target)) ? JavaUtils.getPrimitiveValueArray(array) : JavaUtils.getWrapperValueArray(array);
   }

   /**
    * Return true if the dest class is assignable from the src.
    * Also handles arrays and primitives.
    */
   public static boolean isAssignableFrom(Class dest, Class src)
   {
      if (dest == null)
         throw new IllegalArgumentException("Destination class cannot be null");
      if (src == null)
         throw new IllegalArgumentException("Source class cannot be null");

      boolean isAssignable = dest.isAssignableFrom(src);
      if (isAssignable == false && dest.getName().equals(src.getName()))
      {
         ClassLoader destLoader = dest.getClassLoader();
         ClassLoader srcLoader = src.getClassLoader();
         if(log.isDebugEnabled()) log.debug("Not assignable because of conflicting class loaders:\ndstLoader=" + destLoader + "\nsrcLoader=" + srcLoader);
      }

      if (isAssignable == false && isPrimitive(dest))
      {
         dest = getWrapperType(dest);
         isAssignable = dest.isAssignableFrom(src);
      }
      if (isAssignable == false && isPrimitive(src))
      {
         src = getWrapperType(src);
         isAssignable = dest.isAssignableFrom(src);
      }
      return isAssignable;
   }

   public static String convertJVMNameToSourceName(String typeName, ClassLoader loader)
   {
      // TODO Don't use a ClassLoader for this, we need to just convert it
      try
      {
         Class javaType = loadJavaType(typeName, loader);
         typeName = getSourceName(javaType);
      }
      catch (Exception e)
      {
      }

      return typeName;
   }

   /**
    * Converts a JVM external name to a JVM signature name. An external name is
    * that which is returned from {@link Class#getName()} A signature name is
    * the name in class file format.
    * <p>
    * For example:
    * <p>
    * [java.lang.Object
    * <p>
    * becomes:
    * <p>
    * [Ljava/lang/Object;
    *
    * @param externalName
    * @return
    */
   public static String toSignature(String externalName)
   {
      if (externalName == null)
         return null;

      String ret = primitiveNameDescriptors.get(externalName);
      if (ret != null)
         return ret;

      ret = externalName.replace('.', '/');
      return (ret.charAt(0) == '[') ? ret : "L" + ret + ";";
   }

   public static String printArray(Object[] val)
   {
      if (val == null)
         return "null";

      StringBuilder out = new StringBuilder("[");
      for (int i = 0; i < val.length; i++)
      {
         if (i > 0)
         {
            out.append(",");
         }
         out.append(val[i].getClass().isArray() ? printArray((Object[])val[i]) : val[i]);
      }
      return out.append("]").toString();
   }

   public static String getSourceName(Class type)
   {
      if (! type.isArray())
         return type.getName();

      String arrayNotation = "";
      Class component = type;
      while(component.isArray())
      {
         component = component.getComponentType();
         arrayNotation += "[]";
      }

      return component.getName() + arrayNotation;
   }

   public static String capitalize(String source)
   {
      if (source == null)
         return null;

      if (source.length() == 0)
         return source;

      if (Character.isUpperCase(source.charAt(0)))
         return source;

      char c = Character.toUpperCase(source.charAt(0));

      return c + source.substring(1);
   }

   public static boolean isLoaded(String className, ClassLoader loader)
   {
      try
      {
         loadJavaType(className, loader);
      }
      catch (ClassNotFoundException e)
      {
         return false;
      }

      return true;
   }

   public static String getPackageName(Class<?> clazz)
   {
      String fullName = clazz.getName();
      return fullName.substring(0, fullName.lastIndexOf("."));
   }

   public static boolean isReservedKeyword(String keyword)
   {
      return reservedKeywords.contains(keyword);
   }

   /**
    * Erases a type according to the JLS type erasure rules
    *
    * @param t type to erase
    * @return erased type
    */
   public static Class erasure(Type type)
   {
      if (type instanceof ParameterizedType)
      {
         return erasure(((ParameterizedType)type).getRawType());
      }
      if (type instanceof TypeVariable)
      {
         return erasure(((TypeVariable)type).getBounds()[0]);
      }
      if (type instanceof WildcardType)
      {
         return erasure(((WildcardType)type).getUpperBounds()[0]);
      }
      if (type instanceof GenericArrayType)
      {
         return Array.newInstance(erasure(((GenericArrayType)type).getGenericComponentType()), 0).getClass();
      }

      // Only type left is class
      return (Class)type;
   }

   public static String[] getRawParameterTypeArguments(ParameterizedType type)
   {
      Type[] arguments = type.getActualTypeArguments();
      String[] ret = new String[arguments.length];
      for (int i = 0; i < arguments.length; i++)
      {
         Class raw = erasure(arguments[i]);
         ret[i] = raw.getName();
      }

      return ret;
   }

   /**
    * This method tests for retro translation by searching for a known problem where Class
    * does not implement Type. If this is true, then code must never cast a Class to a Type.
    *
    * @return true if we are in retro
    */
   public static boolean isRetro14()
   {
      return !(String.class instanceof java.lang.reflect.Type);
   }

   /**
    * Tests if this class loader is a JBoss RepositoryClassLoader
    *
    * @param loader
    * @return
    */
   public static boolean isJBossRepositoryClassLoader(ClassLoader loader)
   {
      Class clazz = loader.getClass();
      while (!clazz.getName().startsWith("java"))
      {
         if ("org.jboss.mx.loading.RepositoryClassLoader".equals(clazz.getName()))
            return true;
         clazz = clazz.getSuperclass();
      }

      return false;
   }

   /**
    * Clears black lists on a JBoss RepositoryClassLoader. This is somewhat of a hack, and
    * could be replaced with an integration module. This is needed when the following order of
    * events occur.
    *
    * <ol>
    *   <li>loadClass() returns not found</li>
    *   <li>Some call to defineClass()</li>
    * <ol>
    *
    * The CNFE triggers a black list addition, which cause the class never again to be found.
    *
    * @param loader the loader to clear black lists for
    */
   public static void clearBlacklists(ClassLoader loader)
   {
      if (isJBossRepositoryClassLoader(loader))
      {
			for(Method m : loader.getClass().getMethods())
			{
				if("clearBlackLists".equalsIgnoreCase(m.getName()))
				{
					try
					{
						m.invoke(loader);
					}
					catch (Exception e)
					{
						if(log.isDebugEnabled()) log.debug("Could not clear blacklists on " + loader);
					}
				}
			}			
      }
   }
}