KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jacorb > util > ObjectUtil


1 package org.jacorb.util;
2
3 /*
4  * JacORB - a free Java ORB
5  *
6  * Copyright (C) 1997-2004 Gerald Brose.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the Free
20  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */

22
23 import java.util.*;
24
25 /**
26  * @author Gerald Brose, FU Berlin
27  * @version $Id: ObjectUtil.java,v 1.16 2004/05/06 22:34:32 phil.mesnier Exp $
28  */

29
30 public class ObjectUtil
31 {
32     private static Class JavaDoc identityHashMapClass = null;
33     //for byte -> hexchar
34
private static final char[] lookup =
35         new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
36     /**
37      * @return the contents of the resource as a string, or null
38      * if the contents of the resource could not be located using url
39      */

40     public static final String JavaDoc readURL( String JavaDoc url )
41         throws java.io.IOException JavaDoc
42     {
43         String JavaDoc token = "file://";
44         String JavaDoc line = "";
45         java.io.InputStreamReader JavaDoc isr = null;
46         if (url.startsWith (token))
47             try
48             {
49                 isr = new java.io.FileReader JavaDoc (url.substring(token.length()));
50             }
51             catch (Exception JavaDoc e)
52             {
53                 System.out.println ("Tried and failed to open file: " +
54                                     url.substring(token.length()));
55                 // no worries, let the URL handle it
56
}
57         if (isr == null)
58         {
59             java.net.URL JavaDoc u = new java.net.URL JavaDoc(url);
60             isr = new java.io.InputStreamReader JavaDoc(u.openStream());
61         }
62
63         java.io.BufferedReader JavaDoc in = new java.io.BufferedReader JavaDoc(isr);
64         line = in.readLine();
65
66         in.close();
67         return line;
68     }
69
70     /**
71      * Returns the <code>Class</code> object for the class or interface
72      * with the given string name. This method is a replacement for
73      * <code>Class.forName(String name)</code>. Unlike
74      * <code>Class.forName(String name)</code> (which always uses the
75      * caller's loader or one of its ancestors), <code>classForName</code>
76      * uses a thread-specific loader that has no delegation relationship
77      * with the caller's loader. It attempts the load the desired class
78      * with the thread-specific context class loader and falls back to
79      * <code>Class.forName(String name)</code> only if the context class
80      * loader cannot load the class.
81      * <p>
82      * Loading a class with a loader that is not necessarily an ancestor
83      * of the caller's loader is a crucial thing in many scenarios. As an
84      * example, assume that JacORB was loaded by the boot class loader,
85      * and suppose that some code in JacORB contains a call
86      * <code>Class.forName(someUserClass)</code>. Such usage of
87      * <code>Class.forName</code> effectively forces the user to place
88      * <code>someUserClass</code> in the boot class path. If
89      * <code>classForName(someUserClass)</code> were used instead, the user
90      * class would be loaded by the context class loader, which by default
91      * is set to the system (CLASSPATH) classloader.
92      * <p>
93      * In this simple example above, the default setting of the context class
94      * loader allows classes in the boot classpath to reach classes in the
95      * system classpath. In other scenarios, the context class loader might
96      * be different from the system classloader. Middleware systems like
97      * servlet containers or EJB containers set the context class loader so
98      * that a given thread can reach user-provided classes that are not in
99      * the system classpath.
100      * <p>
101      * For maximum flexibility, <code>classForName</code> should replace
102      * <code>Class.forName(String name)</code> in nearly all cases.
103      *
104      * @param name the fully qualified name of a class
105      *
106      * @return the Class object for that class
107      *
108      * @throws IllegalArgumentException if <code>name</code> is null
109      * @throws ClassNotFoundException if the named class cannot be found
110      * @throws LinkageError if the linkage fails
111      * @throws ExceptionInInitializerError if the class initialization fails
112      */

113
114     public static Class JavaDoc classForName(String JavaDoc name)
115         throws ClassNotFoundException JavaDoc, IllegalArgumentException JavaDoc
116     {
117         if (name == null)
118             throw new IllegalArgumentException JavaDoc("Class name must not be null!");
119         try
120         {
121             // Here we prefer classLoader.loadClass() over the three-argument
122
// form of Class.forName(), as the latter is reported to cause
123
// caching of stale Class instances (due to a buggy cache of
124
// loaded classes).
125
return Thread.currentThread().getContextClassLoader().loadClass(name);
126         }
127         catch (Exception JavaDoc e)
128         {
129             // As a fallback, we prefer Class.forName(name) because it loads
130
// array classes (i.e., it handles arguments like
131
// "[Lsome.class.Name;" or "[[I;", which classLoader.loadClass()
132
// does not handle).
133
return Class.forName(name);
134         }
135     }
136
137     /**
138      * Creates an IdentityHashMap, using either the JDK 1.4 class or
139      * JacORB's drop-in replacement class if the former is not available.
140      *
141      * @return a newly created IdentityHashMap instance
142      */

143     public static Map createIdentityHashMap()
144     {
145         if (identityHashMapClass == null)
146         {
147             try
148             {
149                 identityHashMapClass =
150                     ObjectUtil.classForName("java.util.IdentityHashMap");
151             }
152             catch (ClassNotFoundException JavaDoc ex)
153             {
154                 try
155                 {
156                     identityHashMapClass =
157                         ObjectUtil.classForName("org.jacorb.util.IdentityHashMap");
158                 }
159                 catch (ClassNotFoundException JavaDoc e)
160                 {
161                     throw new RuntimeException JavaDoc(e.toString());
162                 }
163             }
164         }
165         try
166         {
167             return (Map)identityHashMapClass.newInstance();
168         }
169         catch (Exception JavaDoc exc)
170         {
171             throw new RuntimeException JavaDoc(exc.toString());
172         }
173     }
174
175     public static synchronized String JavaDoc bufToString( byte bs[],
176                                                    int start,
177                                                    int len)
178     {
179         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
180         StringBuffer JavaDoc chars = new StringBuffer JavaDoc();
181
182         for ( int i = start; i < (start + len); i++ )
183         {
184             if ((i % 16 ) == 0)
185             {
186                 result.append( chars.toString() );
187                 chars = new StringBuffer JavaDoc();
188             }
189
190             chars.append( toAscii( bs[i] ));
191             result.append( toHex( bs[i] ));
192
193             if ( (i % 4) == 3 )
194             {
195                 chars.append( ' ' );
196                 result.append( ' ' );
197             }
198         }
199
200         if ( len % 16 != 0 )
201         {
202             int pad = 0;
203             int delta_bytes = 16 - (len % 16);
204
205             //rest of line (no of bytes)
206
//each byte takes two chars plus one ws
207
pad = delta_bytes * 3;
208
209             //additional whitespaces after four bytes
210
pad += (delta_bytes / 4);
211
212             for ( int i = 0; i < pad; i++ )
213             {
214                 chars.insert( 0, ' ' );
215             }
216         }
217
218         result.append( chars.toString());
219         return result.toString();
220     }
221
222
223     /**
224      * <code>toHex</code> converts a byte into a readable string.
225      *
226      * @param b a <code>byte</code> value
227      * @return a <code>String</code> value
228      */

229
230     public static final String JavaDoc toHex(byte b)
231     {
232         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
233
234         int upper = (b >> 4) & 0x0F;
235         sb.append( lookup[upper] );
236
237         int lower = b & 0x0F;
238         sb.append( lookup[lower] );
239
240         sb.append( ' ' );
241
242         return sb.toString();
243     }
244
245
246     public static final char toAscii(byte b)
247     {
248         if ( b > (byte) 31 && b < (byte) 127)
249         {
250             return (char) b;
251         }
252         else
253         {
254             return '.';
255         }
256     }
257
258     /**
259      * Convenience method to parse an argument vector (typically from
260      * the command line) and sets any arguments of the form "-Dy=x"
261      * as values in a properties object.
262      */

263
264     public static java.util.Properties JavaDoc argsToProps(String JavaDoc[] args)
265     {
266         java.util.Properties JavaDoc props = new java.util.Properties JavaDoc();
267
268         for( int i = 0; i < args.length; i++ )
269         {
270             if (args[i].startsWith("-D"))
271             {
272                 int idx = args[i].indexOf('=');
273                 if (idx < 3 )
274                     continue;
275                 String JavaDoc key = args[i].substring(2,idx);
276
277                 System.out.println("putting: " + key + "," + args[i].substring(idx+1));
278                 props.put(key, args[i].substring(idx+1));
279             }
280         }
281         return props;
282     }
283
284
285
286
287 }
288
Popular Tags