KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > Utility


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.util;
24
25 import java.net.*;
26 import java.io.*;
27 import java.util.Properties JavaDoc;
28 import java.lang.reflect.*;
29 import javax.naming.*;
30 import javax.rmi.*;
31 import javax.rmi.CORBA.*;
32 import com.sun.enterprise.Switch;
33 import com.sun.enterprise.NamingManager;
34
35 import java.util.logging.*;
36 import com.sun.logging.*;
37
38 /**
39  * Handy class full of static functions.
40  */

41 public final class Utility {
42
43     static Logger _logger=LogDomains.getLogger(LogDomains.UTIL_LOGGER);
44
45     private static LocalStringManagerImpl localStrings =
46     new LocalStringManagerImpl(Utility.class);
47
48     public static void checkJVMVersion()
49     {
50         // do not perform any JVM version checking
51
}
52
53
54     public static Properties JavaDoc getPropertiesFromFile(String JavaDoc file)
55     throws IOException
56     {
57     InputStream is = ClassLoader.getSystemResourceAsStream(file);
58     if (is != null) {
59         Properties JavaDoc config = new Properties JavaDoc();
60         config.load(is);
61         return config;
62     } else {
63         String JavaDoc remoteclient = "/" + file;
64         InputStream is2 = Utility.class.getResourceAsStream(remoteclient);
65         Properties JavaDoc config = new Properties JavaDoc();
66         config.load(is2);
67         return config;
68     }
69     }
70
71
72     /**
73      * Return the hostname of the local machine.
74      */

75     public static String JavaDoc getLocalHost() {
76     String JavaDoc hostname = null;
77     try {
78         InetAddress ia = InetAddress.getLocalHost();
79         hostname = ia.getHostName();
80     } catch(UnknownHostException e) {
81         return "localhost";
82     }
83     return hostname;
84     }
85
86     /**
87      * Return the hostname of the local machine.
88      */

89     public static String JavaDoc getLocalAddress() {
90     String JavaDoc address = null;
91     try {
92         InetAddress ia = InetAddress.getLocalHost();
93         address = ia.getHostAddress();
94     } catch(UnknownHostException e) {
95         return "127.0.0.1";
96     }
97     return address;
98     }
99
100     /**
101      * This is a convenience method to lookup a remote object by name within
102      * the naming context.
103      * @exception javax.naming.NamingException if the object with that
104      * name could not be found.
105      */

106     public static java.rmi.Remote JavaDoc lookupObject(String JavaDoc publishedName,
107                            java.lang.Class JavaDoc anInterface)
108         throws javax.naming.NamingException JavaDoc {
109
110     Context ic = new InitialContext();
111     java.lang.Object JavaDoc objRef = ic.lookup(publishedName);
112     return (java.rmi.Remote JavaDoc)
113         PortableRemoteObject.narrow(objRef, anInterface);
114     }
115
116
117     /** Unmarshal a byte array to an integer.
118     Assume the bytes are in BIGENDIAN order.
119     i.e. array[offset] is the most-significant-byte
120     and array[offset+3] is the least-significant-byte.
121     @param array The array of bytes.
122     @param offset The offset from which to start unmarshalling.
123     */

124     public static int bytesToInt(byte[] array, int offset)
125     {
126     int b1, b2, b3, b4;
127
128         b1 = (array[offset++] << 24) & 0xFF000000;
129         b2 = (array[offset++] << 16) & 0x00FF0000;
130         b3 = (array[offset++] << 8) & 0x0000FF00;
131         b4 = (array[offset++] << 0) & 0x000000FF;
132
133     return (b1 | b2 | b3 | b4);
134     }
135
136     /** Marshal an integer to a byte array.
137     The bytes are in BIGENDIAN order.
138     i.e. array[offset] is the most-significant-byte
139     and array[offset+3] is the least-significant-byte.
140     @param array The array of bytes.
141     @param offset The offset from which to start marshalling.
142     */

143     public static void intToBytes(int value, byte[] array, int offset)
144     {
145         array[offset++] = (byte)((value >>> 24) & 0xFF);
146         array[offset++] = (byte)((value >>> 16) & 0xFF);
147         array[offset++] = (byte)((value >>> 8) & 0xFF);
148         array[offset++] = (byte)((value >>> 0) & 0xFF);
149     }
150
151     /** Unmarshal a byte array to an long.
152     Assume the bytes are in BIGENDIAN order.
153     i.e. array[offset] is the most-significant-byte
154     and array[offset+7] is the least-significant-byte.
155     @param array The array of bytes.
156     @param offset The offset from which to start unmarshalling.
157     */

158     public static long bytesToLong(byte[] array, int offset)
159     {
160     long l1, l2;
161
162     l1 = (long)bytesToInt(array, offset) << 32;
163     l2 = (long)bytesToInt(array, offset+4) & 0xFFFFFFFFL;
164
165     return (l1 | l2);
166     }
167
168     /** Marshal an long to a byte array.
169     The bytes are in BIGENDIAN order.
170     i.e. array[offset] is the most-significant-byte
171     and array[offset+7] is the least-significant-byte.
172     @param array The array of bytes.
173     @param offset The offset from which to start marshalling.
174     */

175     public static void longToBytes(long value, byte[] array, int offset)
176     {
177         array[offset++] = (byte)((value >>> 56) & 0xFF);
178         array[offset++] = (byte)((value >>> 48) & 0xFF);
179         array[offset++] = (byte)((value >>> 40) & 0xFF);
180         array[offset++] = (byte)((value >>> 32) & 0xFF);
181         array[offset++] = (byte)((value >>> 24) & 0xFF);
182         array[offset++] = (byte)((value >>> 16) & 0xFF);
183         array[offset++] = (byte)((value >>> 8) & 0xFF);
184         array[offset++] = (byte)((value >>> 0) & 0xFF);
185     }
186
187     /**
188      * Verify and invoke main if present in the specified class.
189      */

190     public static void invokeApplicationMain(Class JavaDoc mainClass, String JavaDoc[] args)
191     throws InvocationTargetException, IllegalAccessException JavaDoc,
192         ClassNotFoundException JavaDoc
193     {
194         String JavaDoc err = localStrings.getLocalString ("utility.no.main", "",
195                      new Object JavaDoc[] {mainClass});
196
197         // determine the main method using reflection
198
// verify that it is public static void and takes
199
// String[] as the only argument
200
Method mainMethod = null;
201         try {
202             mainMethod = mainClass.getMethod("main",
203             new Class JavaDoc[] { String JavaDoc[].class } );
204         } catch(NoSuchMethodException JavaDoc msme) {
205         _logger.log(Level.SEVERE,"enterprise_util.excep_in_utility",msme);
206         throw new ClassNotFoundException JavaDoc(err);
207         }
208
209         // check modifiers: public static
210
int modifiers = mainMethod.getModifiers ();
211         if (!Modifier.isPublic (modifiers) ||
212         !Modifier.isStatic (modifiers)) {
213             err = localStrings.getLocalString(
214             "utility.main.notpublicorstatic",
215             "The main method is either not public or not static");
216             _logger.log(Level.SEVERE,"enterprise_util.excep_in_utility_main.notpublicorstatic");
217                 throw new ClassNotFoundException JavaDoc(err);
218         }
219
220         // check return type and exceptions
221
if (!mainMethod.getReturnType().equals (Void.TYPE)) {
222         err = localStrings.getLocalString(
223             "utility.main.notvoid",
224             "The main method's return type is not void ");
225         _logger.log(Level.SEVERE,"enterprise_util.excep_in_utility_main.notvoid");
226         throw new ClassNotFoundException JavaDoc(err);
227         }
228
229         // build args to the main and call it
230
Object JavaDoc params [] = new Object JavaDoc [1];
231         params[0] = args;
232         mainMethod.invoke(null, params);
233
234     }
235
236     public static void invokeSetMethod(Object JavaDoc obj, String JavaDoc prop, String JavaDoc value)
237         throws NoSuchMethodException JavaDoc, InvocationTargetException,
238         IllegalAccessException JavaDoc
239     {
240         Class JavaDoc cl = obj.getClass();
241         // change first letter to uppercase
242
String JavaDoc setMeth = "set" + prop.substring(0,1).toUpperCase() +
243             prop.substring(1);
244
245         // try string method
246
try {
247             Class JavaDoc[] cldef = {String JavaDoc.class};
248             Method meth = cl.getMethod(setMeth, cldef);
249             Object JavaDoc[] params = {value};
250             meth.invoke(obj, params);
251             return;
252         } catch (NoSuchMethodException JavaDoc ex) {
253             try {
254                 // try int method
255
Class JavaDoc[] cldef = {Integer.TYPE};
256                 Method meth = cl.getMethod(setMeth, cldef);
257                 Object JavaDoc[] params = {Integer.valueOf(value)};
258                 meth.invoke(obj, params);
259                 return;
260             } catch(NoSuchMethodException JavaDoc nsmex) {
261                 // try boolean method
262
Class JavaDoc[] cldef = {Boolean.TYPE};
263                 Method meth = cl.getMethod(setMeth, cldef);
264                 Object JavaDoc[] params = {Boolean.valueOf(value)};
265                 meth.invoke(obj, params);
266                 return;
267             }
268         }
269     }
270
271
272     public static void invokeSetMethodCaseInsensitive(Object JavaDoc obj, String JavaDoc prop, String JavaDoc value)
273         throws NoSuchMethodException JavaDoc, InvocationTargetException,
274         IllegalAccessException JavaDoc
275     {
276             String JavaDoc alternateMethodName = null;
277             Class JavaDoc cl = obj.getClass();
278
279             String JavaDoc setMeth = "set" + prop;
280
281
282             Method[] methodsList = cl.getMethods();
283             boolean methodFound = false;
284             int i=0;
285             for (i =0; i<methodsList.length; ++i)
286             {
287                 if(methodsList[i].getName().equalsIgnoreCase(setMeth) == true)
288                 {
289                   Class JavaDoc[] parameterTypes = methodsList[i].getParameterTypes();
290                   if(parameterTypes.length == 1 )
291                   {
292                        if(parameterTypes[0].getName().equals("java.lang.String"))
293                        {
294                            methodFound = true;
295                            break;
296                        }
297                        else
298                            alternateMethodName = methodsList[i].getName();
299                    }
300                   
301                 }
302             }
303             if(methodFound == true)
304             {
305                 Object JavaDoc[] params = {value};
306                 methodsList[i].invoke(obj, params);
307                 return;
308             }
309             if(alternateMethodName != null)
310             {
311                  try
312                  {
313                 // try int method
314
Class JavaDoc[] cldef = {Integer.TYPE};
315                     Method meth = cl.getMethod(alternateMethodName, cldef);
316                     Object JavaDoc[] params = {Integer.valueOf(value)};
317                     meth.invoke(obj, params);
318                     return;
319                  }
320                  catch(NoSuchMethodException JavaDoc nsmex)
321                  {
322                     // try boolean method
323
Class JavaDoc[] cldef = {Boolean.TYPE};
324                     Method meth = cl.getMethod(alternateMethodName, cldef);
325                     Object JavaDoc[] params = {Boolean.valueOf(value)};
326                     meth.invoke(obj, params);
327                     return;
328                  }
329
330             }
331             else
332                  throw new NoSuchMethodException JavaDoc(setMeth);
333     }
334
335
336   // Ports are marshalled as shorts on the wire. The IDL
337
// type is unsigned short, which lacks a convenient representation
338
// in Java in the 32768-65536 range. So, we treat ports as
339
// ints throught this code, except that marshalling requires a
340
// scaling conversion. intToShort and shortToInt are provided
341
// for this purpose.
342

343     public static short intToShort(int value)
344     {
345     if (value > 32767)
346             return (short)(value - 65536) ;
347     return (short)value ;
348     }
349
350     public static int shortToInt(short value)
351     {
352         if (value < 0)
353             return value + 65536 ;
354     return value ;
355     }
356
357     /**
358      * Get the current thread's context class loader which is set to
359      * the CommonClassLoader by ApplicationServer
360      * @return the thread's context classloader if it exists;
361      * else the system class loader.
362      */

363     public static ClassLoader JavaDoc getClassLoader() {
364     if (Thread.currentThread().getContextClassLoader() != null) {
365         return Thread.currentThread().getContextClassLoader();
366     } else {
367         return ClassLoader.getSystemClassLoader();
368     }
369     }
370
371     /**
372      * Loads the class with the common class loader.
373      * @param the class name
374      * @return the loaded class
375      * @exception if the class is not found.
376      * @see getClassLoader()
377      */

378     public static Class JavaDoc loadClass(String JavaDoc className) throws ClassNotFoundException JavaDoc {
379     return getClassLoader().loadClass(className);
380     }
381
382     /**
383      * Utility routine for setting the context class loader.
384      * Returns previous class loader.
385      */

386     public static ClassLoader JavaDoc setContextClassLoader(ClassLoader JavaDoc newClassLoader)
387     {
388
389         // Can only reference final local variables from dopriveleged block
390
final ClassLoader JavaDoc classLoaderToSet = newClassLoader;
391
392         final Thread JavaDoc currentThread = Thread.currentThread();
393         ClassLoader JavaDoc originalClassLoader =
394             currentThread.getContextClassLoader();
395
396         java.security.AccessController.doPrivileged
397             (new java.security.PrivilegedAction JavaDoc() {
398         public java.lang.Object JavaDoc run() {
399         currentThread.setContextClassLoader(classLoaderToSet);
400         return null;
401         }
402     });
403         return originalClassLoader;
404     }
405
406     public static void setDataDirectProperty() {
407         Environment e = Environment.obtain();
408         if (e.getEnvironmentStatus() == Environment.CLOSED) {
409             return;
410         } else {
411             e.unlock();
412         }
413     }
414
415 }
416
Popular Tags