KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > oracle > toplink > essentials > internal > security > PrivilegedAccessHelper


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
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
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 in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21 // Copyright (c) 1998, 2006, Oracle. All rights reserved.
22
package oracle.toplink.essentials.internal.security;
23
24 import java.security.*;
25 import java.lang.reflect.*;
26
27 /**
28  * INTERNAL:
29  * Privileged Access Helper provides a utility so all calls that require privileged access can use the same code
30  *
31  * For users that wish to use a security manager and disable the use of doPrivileged, users can
32  * set one of two system flags (through the java -Dxxxxx option):
33  *
34  * oracle.j2ee.toplink.security.usedoprivileged=false
35  * oracle.j2ee.security.usedoprivileged=false
36  */

37 public class PrivilegedAccessHelper {
38     private static boolean shouldUsePrivilegedAccess = false;
39     private static boolean shouldSecurityManagerBeChecked = true;
40
41     /**
42      * Finding a field within a class potentially has to navigate through it's superclasses to eventually
43      * find the field. This method is called by the public getDeclaredField() method and does a recursive
44      * search for the named field in the given classes or it's superclasses.
45      */

46     private static Field findDeclaredField(Class JavaDoc javaClass, String JavaDoc fieldName) throws NoSuchFieldException JavaDoc {
47         try {
48             return javaClass.getDeclaredField(fieldName);
49         } catch (NoSuchFieldException JavaDoc ex) {
50             Class JavaDoc superclass = javaClass.getSuperclass();
51             if (superclass == null) {
52                 throw ex;
53             } else {
54                 return findDeclaredField(superclass, fieldName);
55             }
56         }
57     }
58
59     /**
60      * Finding a method within a class potentially has to navigate through it's superclasses to eventually
61      * find the method. This method is called by the public getDeclaredMethod() method and does a recursive
62      * search for the named method in the given classes or it's superclasses.
63      */

64     private static Method findMethod(Class JavaDoc javaClass, String JavaDoc methodName, Class JavaDoc[] methodParameterTypes) throws NoSuchMethodException JavaDoc {
65         try {
66             return javaClass.getDeclaredMethod(methodName, methodParameterTypes);
67         } catch (NoSuchMethodException JavaDoc ex) {
68             Class JavaDoc superclass = javaClass.getSuperclass();
69             if (superclass == null) {
70                 throw ex;
71             } else {
72                 try{
73                     return findMethod(superclass, methodName, methodParameterTypes);
74                 }catch (NoSuchMethodException JavaDoc lastEx){
75                     throw ex;
76                 }
77             }
78         }
79     }
80
81     /**
82      * Execute a java Class.forName(). Wrap the call in a doPrivileged block if necessary.
83      * @param className
84      */

85     public static Class JavaDoc getClassForName(final String JavaDoc className) throws ClassNotFoundException JavaDoc {
86         return Class.forName(className);
87     }
88
89     /**
90      * Execute a java Class.forName() wrap the call in a doPrivileged block if necessary.
91      * @param className
92      * @param initialize
93      * @param loader
94      * @throws java.lang.ClassNotFoundException
95      */

96     public static Class JavaDoc getClassForName(final String JavaDoc className, final boolean initialize, final ClassLoader JavaDoc loader) throws ClassNotFoundException JavaDoc {
97         return Class.forName(className, initialize, loader);
98     }
99
100     /**
101      * Gets the class loader for a given class. Wraps the call in a privileged block if necessary
102      */

103     public static ClassLoader JavaDoc getClassLoaderForClass(final Class JavaDoc clazz) {
104         return clazz.getClassLoader();
105     }
106
107     /**
108      * Get the public constructor for the given class and given arguments and wrap it in doPrivileged if
109      * necessary. The shouldSetAccessible parameter allows the the setAccessible API to be called as well.
110      * This option was added to avoid making multiple doPrivileged calls within InstantiationPolicy.
111      * @param javaClass The class to get the Constructor for
112      * @param args An array of classes representing the argument types of the constructor
113      * @param shouldSetAccessible whether or not to call the setAccessible API
114      * @throws java.lang.NoSuchMethodException
115      */

116     public static Constructor getConstructorFor(final Class JavaDoc javaClass, final Class JavaDoc[] args, final boolean shouldSetAccessible) throws NoSuchMethodException JavaDoc {
117         Constructor result = javaClass.getConstructor(args);
118         if (shouldSetAccessible) {
119             result.setAccessible(true);
120         }
121         return result;
122     }
123
124     /**
125      * Get the context ClassLoader for a thread. Wrap the call in a doPrivileged block if necessary.
126      */

127     public static ClassLoader JavaDoc getContextClassLoader(final Thread JavaDoc thread) {
128         return thread.getContextClassLoader();
129     }
130
131     /**
132      * Get the constructor for the given class and given arguments (regardless of whether it is public
133      * or private))and wrap it in doPrivileged if necessary. The shouldSetAccessible parameter allows
134      * the the setAccessible API to be called as well. This option was added to avoid making multiple
135      * doPrivileged calls within InstantiationPolicy.
136      * @param javaClass The class to get the Constructor for
137      * @param args An array of classes representing the argument types of the constructor
138      * @param shouldSetAccessible whether or not to call the setAccessible API
139      * @throws java.lang.NoSuchMethodException
140      */

141     public static Constructor getDeclaredConstructorFor(final Class JavaDoc javaClass, final Class JavaDoc[] args, final boolean shouldSetAccessible) throws NoSuchMethodException JavaDoc {
142         Constructor result = javaClass.getDeclaredConstructor(args);
143         if (shouldSetAccessible) {
144             result.setAccessible(true);
145         }
146         return result;
147     }
148
149     /**
150      * Get a field in a class or its superclasses and wrap the call in doPrivileged if necessary.
151      * The shouldSetAccessible parameter allows the the setAccessible API to be called as well.
152      * This option was added to avoid making multiple doPrivileged calls within InstanceVariableAttributeAccessor.
153      * @param javaClass The class to get the field from
154      * @param fieldName The name of the field
155      * @param shouldSetAccessible whether or not to call the setAccessible API
156      * @throws java.lang.NoSuchFieldException
157      */

158     public static Field getField(final Class JavaDoc javaClass, final String JavaDoc fieldName, final boolean shouldSetAccessible) throws NoSuchFieldException JavaDoc {
159         Field field = (Field)findDeclaredField(javaClass, fieldName);
160         if (shouldSetAccessible) {
161             field.setAccessible(true);
162         }
163             return field;
164     }
165
166     /**
167      * Get a field actually declared in a class and wrap the call in doPrivileged if necessary.
168      * The shouldSetAccessible parameter allows the the setAccessible API to be called as well.
169      * This option was added to avoid making multiple doPrivileged calls within InstanceVariableAttributeAccessor.
170      * @param javaClass The class to get the field from
171      * @param fieldName The name of the field
172      * @param shouldSetAccessible whether or not to call the setAccessible API
173      * @throws java.lang.NoSuchFieldException
174      */

175     public static Field getDeclaredField(final Class JavaDoc javaClass, final String JavaDoc fieldName, final boolean shouldSetAccessible) throws NoSuchFieldException JavaDoc {
176         Field field = javaClass.getDeclaredField(fieldName);
177         if (shouldSetAccessible) {
178             field.setAccessible(true);
179         }
180         return field;
181     }
182
183     /**
184      * Get the list of fields in a class. Wrap the call in doPrivileged if necessary
185      * Excludes inherited fields.
186      * @param clazz the class to get the fields from.
187      */

188     public static Field[] getDeclaredFields(final Class JavaDoc clazz) {
189         return clazz.getDeclaredFields();
190     }
191
192     /**
193      * Return a method on a given class with the given method name and parameter
194      * types. This call will NOT traverse the superclasses. Wrap the call in
195      * doPrivileged if necessary.
196      * @param method the class to get the method from
197      * @param methodName the name of the method to get
198      * @param methodParameters a list of classes representing the classes of the
199      * parameters of the method.
200      */

201     public static Method getDeclaredMethod(final Class JavaDoc clazz, final String JavaDoc methodName, final Class JavaDoc[] methodParameterTypes) throws NoSuchMethodException JavaDoc {
202          return clazz.getDeclaredMethod(methodName, methodParameterTypes);
203     }
204     
205     /**
206      * Get a method declared in the given class. Wrap the call in doPrivileged
207      * if necessary. This call will traver the superclasses. The
208      * shouldSetAccessible parameter allows the the setAccessible API to be
209      * called as well. This option was added to avoid making multiple
210      * doPrivileged calls within MethodBasedAttributeAccessor.
211      * @param javaClass The class to get the method from
212      * @param methodName The name of the method to get
213      * @param methodParameterTypes A list of classes representing the classes of the parameters of the mthod
214      * @param shouldSetAccessible whether or not to call the setAccessible API
215      * @throws java.lang.NoSuchMethodException
216      */

217     public static Method getMethod(final Class JavaDoc javaClass, final String JavaDoc methodName, final Class JavaDoc[] methodParameterTypes, final boolean shouldSetAccessible) throws NoSuchMethodException JavaDoc {
218         Method method = findMethod(javaClass, methodName, methodParameterTypes);
219         if (shouldSetAccessible) {
220             method.setAccessible(true);
221         }
222         return method;
223     }
224     
225     /**
226      * Get the list of methods in a class. Wrap the call in doPrivileged if
227      * necessary. Excludes inherited methods.
228      * @param clazz the class to get the methods from.
229      */

230     public static Method[] getDeclaredMethods(final Class JavaDoc clazz) {
231         return clazz.getDeclaredMethods();
232     }
233     
234     /**
235      * Get the return type for a given method. Wrap the call in doPrivileged if necessary.
236      * @param field
237      */

238     public static Class JavaDoc getFieldType(final Field field) {
239         return field.getType();
240     }
241
242     /**
243      * Get the line separator character.
244      * Previous versions of TopLink always did this in a privileged block so we will continue to do so.
245      */

246     public static String JavaDoc getLineSeparator() {
247         if (shouldUsePrivilegedAccess()) {
248             return (String JavaDoc)AccessController.doPrivileged(new PrivilegedAction() {
249                     public Object JavaDoc run() {
250                         return System.getProperty("file.separator");
251                     }
252                 });
253         } else {
254             return oracle.toplink.essentials.internal.helper.Helper.cr();
255         }
256     }
257
258     /**
259      * Get the list of parameter types for a given method. Wrap the call in doPrivileged if necessary.
260      * @param method The method to get the parameter types of
261      */

262     public static Class JavaDoc[] getMethodParameterTypes(final Method method) {
263         return method.getParameterTypes();
264     }
265
266     /**
267      * Get the return type for a given method. Wrap the call in doPrivileged if necessary.
268      * @param method
269      */

270     public static Class JavaDoc getMethodReturnType(final Method method) {
271         return method.getReturnType();
272     }
273     
274     /**
275      * Get the list of methods in a class. Wrap the call in doPrivileged if
276      * necessary. This call will traver the superclasses.
277      * @param clazz the class to get the methods from.
278      */

279     public static Method[] getMethods(final Class JavaDoc clazz) {
280         return clazz.getMethods();
281     }
282     
283     /**
284      * Get the value of the given field in the given object.
285      */

286     public static Object JavaDoc getValueFromField(final Field field, final Object JavaDoc object) throws IllegalAccessException JavaDoc {
287         return field.get(object);
288     }
289
290     /**
291      * Construct an object with the given Constructor and the given array of arguments. Wrap the call in a
292      * doPrivileged block if necessary.
293      */

294     public static Object JavaDoc invokeConstructor(final Constructor constructor, final Object JavaDoc[] args) throws IllegalAccessException JavaDoc, InvocationTargetException, InstantiationException JavaDoc {
295         return constructor.newInstance(args);
296     }
297
298     /**
299      * Invoke the givenMethod on a givenObject using the array of parameters given. Wrap in a doPrivileged block
300      * if necessary.
301      */

302     public static Object JavaDoc invokeMethod(final Method method, final Object JavaDoc object, final Object JavaDoc[] parameters) throws IllegalAccessException JavaDoc, InvocationTargetException {
303         // Ensure the method is accessible.
304
if (!method.isAccessible()) {
305             method.setAccessible(true);
306         }
307         return method.invoke(object, parameters);
308     }
309
310     /**
311      * Get a new instance of a class using the default constructor. Wrap the call in a privileged block
312      * if necessary.
313      */

314     public static Object JavaDoc newInstanceFromClass(final Class JavaDoc clazz) throws IllegalAccessException JavaDoc, InstantiationException JavaDoc {
315         return clazz.newInstance();
316     }
317
318     /**
319      * Set the value of a given field in the given object with the value given. Wrap the call in a privileged block
320      * if necessary.
321      */

322     public static void setValueInField(final Field field, final Object JavaDoc object, final Object JavaDoc value) throws IllegalAccessException JavaDoc {
323         field.set(object, value);
324     }
325
326     /**
327      * This method checks to see if calls should be made to doPrivileged.
328      * In general, if a security manager is enabled, it will return true and if one
329      * is not enabled, it will return false.
330      * It will, however, always return false if either of the following two java properties is
331      * set.
332      * oracle.j2ee.toplink.security.usedoprivileged=false
333      * oracle.j2ee.security.usedoprivileged=false
334      * Note: it is not possible to run TopLink using doPrivileged blocks when there is no SecurityManager
335      * enabled.
336      */

337     public static boolean shouldUsePrivilegedAccess() {
338         // We will only detect whether to use doPrivileged once.
339
if (shouldSecurityManagerBeChecked) {
340             shouldSecurityManagerBeChecked = false;
341
342             Boolean JavaDoc privilegedPropertySet = (Boolean JavaDoc)AccessController.doPrivileged(new PrivilegedAction() {
343                     public Object JavaDoc run() {
344                         boolean propertySet;
345
346                         // check TopLink and OC4j doPrivileged flag.
347
String JavaDoc usePrivileged = System.getProperty("oracle.j2ee.toplink.security.usedoprivileged");
348                         String JavaDoc oc4jUsePrivileged = System.getProperty("oracle.j2ee.security.usedoprivileged");
349                         propertySet = (((usePrivileged != null) && usePrivileged.equalsIgnoreCase("false")) || ((oc4jUsePrivileged != null) && oc4jUsePrivileged.equalsIgnoreCase("false")));
350                         return new Boolean JavaDoc(propertySet);
351                     }
352                 });
353             if (privilegedPropertySet.booleanValue()) {
354                 shouldUsePrivilegedAccess = false;
355             } else {
356                 shouldUsePrivilegedAccess = (System.getSecurityManager() != null);
357             }
358         }
359         return shouldUsePrivilegedAccess;
360     }
361 }
362
Popular Tags