KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > core > mop > Utils


1 /*
2 * ################################################################
3 *
4 * ProActive: The Java(TM) library for Parallel, Distributed,
5 * Concurrent computing with Security and Mobility
6 *
7 * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
8 * Contact: proactive-support@inria.fr
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23 * USA
24 *
25 * Initial developer(s): The ProActive Team
26 * http://www.inria.fr/oasis/ProActive/contacts.html
27 * Contributor(s):
28 *
29 * ################################################################
30 */

31 package org.objectweb.proactive.core.mop;
32
33 import java.lang.reflect.Field JavaDoc;
34 import java.lang.reflect.Method JavaDoc;
35 import java.lang.reflect.Modifier JavaDoc;
36
37 /**
38  * This class contains static convenience and utility methods
39  */

40
41 public abstract class Utils extends Object JavaDoc {
42
43   /**
44    * Static variables
45    */

46   public static final Class JavaDoc JAVA_LANG_NUMBER = silentForName("java.lang.Number");
47   public static final Class JavaDoc JAVA_LANG_CHARACTER = silentForName("java.lang.Character");
48   public static final Class JavaDoc JAVA_LANG_BOOLEAN = silentForName("java.lang.Boolean");
49   public static final Class JavaDoc JAVA_LANG_VOID = silentForName("java.lang.Void");
50   public static final Class JavaDoc JAVA_LANG_RUNTIMEEXCEPTION = silentForName("java.lang.RuntimeException");
51   public static final Class JavaDoc JAVA_LANG_EXCEPTION = silentForName("java.lang.Exception");
52   public static final Class JavaDoc JAVA_LANG_THROWABLE = silentForName("java.lang.Throwable");
53   public static final String JavaDoc STUB_DEFAULT_PREFIX = "Stub_";
54   public static final String JavaDoc STUB_DEFAULT_PACKAGE = "pa.stub.";
55
56   /**
57    * Static methods
58    */

59
60   /**
61    * Removes the keyword 'native' from the String given as argument.
62    *
63    * We assume there is only one occurence of 'native' in the string.
64    *
65    * @return the input String minus the first occurence of 'native'.
66    * @param in The String the keyword 'native' is to be removed from.
67    */

68   static public String JavaDoc getRidOfNative(String JavaDoc in) {
69     String JavaDoc result;
70     int leftindex, rightindex;
71
72     leftindex = in.indexOf("native");
73     if (leftindex == -1)
74       return in;
75     rightindex = leftindex + 6;
76
77     result = in.substring(0, leftindex) + in.substring(rightindex, in.length());
78     return result;
79   }
80
81   static public String JavaDoc getRidOfAbstract(String JavaDoc in) {
82     String JavaDoc result;
83     int leftindex, rightindex;
84
85     leftindex = in.indexOf("abstract");
86     if (leftindex == -1)
87       return in;
88     rightindex = leftindex + 8;
89
90     result = in.substring(0, leftindex) + in.substring(rightindex, in.length());
91     return result;
92   }
93
94   static public String JavaDoc getRidOfNativeAndAbstract(String JavaDoc in) {
95     String JavaDoc s = in;
96     s = getRidOfAbstract(s);
97     return getRidOfNative(s);
98   }
99
100   /**
101    * Checks if the given method can be reified.
102    *
103    * Criteria for NOT being reifiable are :
104    * <UL>
105    * <LI> method is final
106    * <LI> method is static
107    * <LI> method is finalize ()
108    * </UL>
109    *
110    * @return True if the method is reifiable
111    * @param met The method to be checked
112    */

113
114   static public boolean checkMethod(Method JavaDoc met) {
115     int modifiers = met.getModifiers();
116
117     // Final methods cannot be reified since we cannot redefine them
118
// in a subclass
119
if (Modifier.isFinal(modifiers))
120       return false;
121     // Static methods cannot be reified since they are not 'virtual'
122
if (Modifier.isStatic(modifiers))
123       return false;
124     if (!(Modifier.isPublic(modifiers)))
125       return false;
126     // If method is finalize (), don't reify it
127
if ((met.getName().equals("finalize")) && (met.getParameterTypes().length == 0))
128       return false;
129     return true;
130   }
131
132   /**
133    * Returns a String representing the'source code style' declaration
134    * of the Class object representing an array type given as argument.
135    *
136    * The problem is that the <code>toString()</code> method of class Class
137    * does not
138    * return what we are expecting, i-e the type definition that appears in
139    * the source code (like <code>char[][]</code>).
140    *
141    * @param tab A class object representing an array type.
142    * @return A String with the'source code representation' of that array type
143    */

144
145   static public String JavaDoc sourceLikeForm(Class JavaDoc cl) {
146     if (!(cl.isArray())) {
147       //to fix an issue with jdk1.3 and inner class
148
// A$B should be A.B in source code
149
//System.out.println("Remplacing in " + cl.getName());
150

151       return cl.getName().replace('$', '.');
152     } else {
153       int nb = 0;
154       Class JavaDoc current = cl;
155       String JavaDoc result = "";
156
157       do {
158         current = current.getComponentType();
159         result = "[]" + result;
160         nb++;
161       } while ((current.getComponentType()) != null);
162
163       result = current.getName() + result;
164       return result;
165     }
166   }
167
168   /*
169    * Returns the name of the wrapper class for class <code>cl</code>.
170    * If <code>cl</code> is not a primitive type, returns <code>null</code>
171    */

172
173   static public String JavaDoc nameOfWrapper(Class JavaDoc cl) {
174     String JavaDoc str = cl.getName();
175
176     if (cl.isPrimitive()) {
177       if (str.equals("int"))
178         return "java.lang.Integer";
179       else if (str.equals("boolean"))
180         return "java.lang.Boolean";
181       else if (str.equals("byte"))
182         return "java.lang.Byte";
183       else if (str.equals("short"))
184         return "java.lang.Short";
185       else if (str.equals("long"))
186         return "java.lang.Long";
187       else if (str.equals("float"))
188         return "java.lang.Float";
189       else if (str.equals("double"))
190         return "java.lang.Double";
191       else if (str.equals("void"))
192         return "void";
193       else if (str.equals("char"))
194         return "java.lang.Character";
195       else {
196         throw new InternalException("Unknown primitive type: " + cl.getName());
197       }
198     } else {
199       return null;
200     }
201   }
202
203   /*
204    * Extract the package name from the fully qualified class name given as
205    * an argument
206    */

207
208   public static String JavaDoc getPackageName(String JavaDoc fqnameofclass) {
209     int indexoflastdot;
210
211     indexoflastdot = fqnameofclass.lastIndexOf('.');
212
213     if (indexoflastdot == -1) {
214       return "";
215     } else {
216       return fqnameofclass.substring(0, indexoflastdot);
217     }
218
219   }
220
221   /**
222    * Extracts the simple name of the class from its fully qualified name
223    */

224
225   public static String JavaDoc getSimpleName(String JavaDoc fullyQualifiedNameOfClass) {
226     int indexOfLastDot = fullyQualifiedNameOfClass.lastIndexOf('.');
227     if (indexOfLastDot == -1) // There are no dots
228
{
229       return fullyQualifiedNameOfClass;
230     } else {
231       // If last character is a dot, returns an empty string
232
if (indexOfLastDot == (fullyQualifiedNameOfClass.length() - 1))
233         return "";
234       else
235         return fullyQualifiedNameOfClass.substring(indexOfLastDot + 1);
236     }
237   }
238
239   /**
240    * Returns the Class object that is a wrapper for the given <code>cl</code>
241    * class.
242    */

243   public static Class JavaDoc getWrapperClass(Class JavaDoc cl) {
244     if (!(cl.isPrimitive()))
245       return null;
246     String JavaDoc s = Utils.nameOfWrapper(cl);
247     try {
248       return MOP.forName(s);
249     } catch (ClassNotFoundException JavaDoc e) {
250       throw new InternalException("Cannot load wrapper class " + s);
251     }
252   }
253
254   /**
255    * Performs the opposite operation as getWrapperClass
256    */

257   public static Class JavaDoc getPrimitiveType(Class JavaDoc cl) {
258     Field JavaDoc cst;
259     if (Utils.isWrapperClass(cl)) {
260       // These types are not classes , yet class static variables
261
// We want to locale the TYPE field in the class
262
try {
263         cst = cl.getField("TYPE");
264         return (Class JavaDoc) cst.get(null);
265       } catch (NoSuchFieldException JavaDoc e) {
266         throw new InternalException("Cannot locate constant TYPE in class " + cl.getName());
267       } catch (SecurityException JavaDoc e) {
268         throw new InternalException("Access to field TYPE in class " + cl.getName() + " denied");
269       } catch (IllegalAccessException JavaDoc e) {
270         throw new InternalException("Access to field TYPE in class " + cl.getName() + " denied");
271       }
272     } else {
273       throw new InternalException("Not a wrapper class: " + cl.getName());
274     }
275   }
276
277   /**
278    * Tests if the class given as an argument is a wrapper class
279    * How can we be sure that all subclasses of java.lang.Number are wrappers ??
280    */

281
282   public static boolean isWrapperClass(Class JavaDoc cl) {
283     if (Utils.JAVA_LANG_NUMBER.isAssignableFrom(cl))
284       return true;
285     else if (Utils.JAVA_LANG_BOOLEAN.isAssignableFrom(cl))
286       return true;
287     else if (Utils.JAVA_LANG_CHARACTER.isAssignableFrom(cl))
288       return true;
289     else if (Utils.JAVA_LANG_VOID.isAssignableFrom(cl))
290       return true;
291     else
292       return false;
293   }
294
295   public static String JavaDoc getRelativePath(String JavaDoc className) {
296     String JavaDoc packageName;
297     String JavaDoc fileSeparator;
298     String JavaDoc result;
299     int indexOfDot, indexOfLastDot;
300
301     fileSeparator = System.getProperty("file.separator");
302     packageName = Utils.getPackageName(className);
303
304     indexOfDot = packageName.indexOf((int) '.', 0);
305     result = "";
306     indexOfLastDot = 0;
307
308     while (indexOfDot != -1) {
309
310       result = result + fileSeparator + packageName.substring(indexOfLastDot, indexOfDot);
311       indexOfLastDot = indexOfDot + 1;
312       indexOfDot = packageName.indexOf((int) '.', indexOfDot + 1);
313       if (indexOfDot == -1)
314         result = result + fileSeparator + packageName.substring(indexOfLastDot, packageName.length());
315     }
316
317     if (result.equals(""))
318       result = fileSeparator + packageName;
319
320     return result;
321   }
322
323   /*
324     public static String getStubName(String nameOfClass) {
325       return Utils.getPackageName(nameOfClass) + "." + STUB_DEFAULT_PREFIX + Utils.getSimpleName(nameOfClass);
326     }
327   */

328
329   public static boolean isNormalException(Class JavaDoc exc) {
330     boolean result;
331
332     if (Utils.JAVA_LANG_THROWABLE.isAssignableFrom(exc)) {
333       // It is a subclass of Throwable
334
if (Utils.JAVA_LANG_EXCEPTION.isAssignableFrom(exc)) {
335         if (Utils.JAVA_LANG_RUNTIMEEXCEPTION.isAssignableFrom(exc))
336           result = false;
337         else
338           result = true;
339       } else
340         result = false; // This must be an Error
341

342     } else
343       result = false;
344
345     return result;
346   }
347
348   public static Class JavaDoc decipherPrimitiveType(String JavaDoc str) {
349     if (str.equals("int"))
350       return java.lang.Integer.TYPE;
351     else if (str.equals("boolean"))
352       return java.lang.Boolean.TYPE;
353     else if (str.equals("byte"))
354       return java.lang.Byte.TYPE;
355     else if (str.equals("short"))
356       return java.lang.Short.TYPE;
357     else if (str.equals("long"))
358       return java.lang.Long.TYPE;
359     else if (str.equals("float"))
360       return java.lang.Float.TYPE;
361     else if (str.equals("double"))
362       return java.lang.Double.TYPE;
363     else if (str.equals("void"))
364       return java.lang.Void.TYPE;
365     else if (str.equals("char"))
366       return java.lang.Character.TYPE;
367
368     return null;
369   }
370
371   public static boolean isSuperTypeInArray(String JavaDoc className, Class JavaDoc[] types) {
372     try {
373       Class JavaDoc c = MOP.forName(className);
374       return isSuperTypeInArray(c, types);
375     } catch (ClassNotFoundException JavaDoc e) {
376       throw new InternalException(e);
377     }
378   }
379
380   public static boolean isSuperTypeInArray(Class JavaDoc c, Class JavaDoc[] types) {
381     for (int i = 0; i < types.length; i++) {
382       if (types[i].isAssignableFrom(c))
383         return true;
384     }
385     return false;
386   }
387
388   public static Object JavaDoc makeDeepCopy(Object JavaDoc source) throws java.io.IOException JavaDoc {
389     java.io.ByteArrayOutputStream JavaDoc baos = new java.io.ByteArrayOutputStream JavaDoc();
390     //java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
391
java.io.ObjectOutputStream JavaDoc oos = new PAObjectOutputStream(baos);
392     oos.writeObject(source);
393     oos.flush();
394     oos.close();
395     java.io.ByteArrayInputStream JavaDoc bais = new java.io.ByteArrayInputStream JavaDoc(baos.toByteArray());
396 // java.io.ObjectInputStream ois = new java.io.ObjectInputStream(bais);
397
java.io.ObjectInputStream JavaDoc ois = new PAObjectInputStream(bais);
398     try {
399       Object JavaDoc result = ois.readObject();
400       ois.close();
401       return result;
402     } catch (ClassNotFoundException JavaDoc e) {
403       throw new java.io.IOException JavaDoc("ClassNotFoundException e=" + e);
404     }
405   }
406
407   public static String JavaDoc convertClassNameToStubClassName(String JavaDoc classname) {
408     if (classname.length() == 0) {
409             return classname;
410     }
411     int n = classname.lastIndexOf('.');
412     if (n == -1) {
413         // no package
414
return STUB_DEFAULT_PACKAGE + STUB_DEFAULT_PREFIX + classname;
415     } else {
416         return STUB_DEFAULT_PACKAGE + classname.substring(0, n + 1) +
417                STUB_DEFAULT_PREFIX + classname.substring(n + 1);
418     }
419   }
420
421   public static boolean isStubClassName(String JavaDoc classname) {
422     if (classname.startsWith(STUB_DEFAULT_PACKAGE)) {
423       // Extracts the simple name from the fully-qualified class name
424
int index = classname.lastIndexOf(".");
425       if (index != -1) {
426         return classname.substring(index + 1).startsWith(Utils.STUB_DEFAULT_PREFIX);
427       } else {
428         return classname.startsWith(Utils.STUB_DEFAULT_PREFIX);
429       }
430     } else {
431       return false;
432     }
433   }
434
435   public static String JavaDoc convertStubClassNameToClassName(String JavaDoc stubclassname) {
436     if (isStubClassName(stubclassname)) {
437       String JavaDoc temp = stubclassname.substring(Utils.STUB_DEFAULT_PACKAGE.length());
438       String JavaDoc packageName = Utils.getPackageName(temp);
439       String JavaDoc stubClassSimpleName = Utils.getSimpleName(temp);
440       String JavaDoc classsimplename = stubClassSimpleName.substring(Utils.STUB_DEFAULT_PREFIX.length());
441       // consider the "no package" case
442
String JavaDoc result;
443       if (packageName.equals("")) {
444       //no package
445
result = classsimplename;
446       } else {
447         result = packageName + "." + classsimplename;
448       }
449       // System.out.println ("CONVERT "+stubclassname+" -> "+result);
450
return result;
451     } else {
452       return stubclassname;
453     }
454   }
455
456   private static final Class JavaDoc silentForName(String JavaDoc classname) {
457     try {
458       return MOP.forName(classname);
459     } catch (ClassNotFoundException JavaDoc e) {
460       System.err.println("Static initializer in class org.objectweb.proactive.core.mop.Utils: Cannot load classe " + classname);
461       return null;
462     }
463   }
464
465 }
466
Popular Tags