package org.freeplane.securegroovy;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ReflectPermission;
import java.security.AccessControlException;

import groovy.lang.GroovyObject;

class AccessPermissionChecker {

	private static final ReflectPermission REFLECT_PERMISSION = new ReflectPermission("suppressAccessChecks");

	static private void checkAccessPermission(Class<?> declaringClass, final int modifiers, boolean isAccessible, String memberType,
	                                  String name) {
		final SecurityManager securityManager = System.getSecurityManager();
		if (isAccessible && securityManager != null && (modifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0
		        && !GroovyObject.class.isAssignableFrom(declaringClass)) {
			try {
				securityManager.checkPermission(REFLECT_PERMISSION);
			}
			catch (AccessControlException ex){
				throw new IllegalArgumentException("Illegal access to " + memberType + " " + name);
			}
		}
	}

	static public void checkAccessPermission(Method method) {
		checkAccessPermission(method.getDeclaringClass(), method.getModifiers(), method.isAccessible(), "method",
				method.getName());
	}

	public static void checkAccessPermission(Field field) {
		checkAccessPermission(field.getDeclaringClass(), field.getModifiers(), field.isAccessible(),
		    "field", field.getName());
	}

}

@@ -404,24 +404,16 @@
 %09static 
-private 
 void che
@@ -523,54 +523,54 @@
 e,%0A%09
-                                  String name)
+%09%09String name) throws IllegalArgumentException
  %7B%0A%09
@@ -684,20 +684,37 @@
  != null
- && 
+) %7B%0A%09%09%09try %7B%0A%09%09%09%09if (
 (modifie
@@ -769,16 +769,12 @@
 0%0A%09%09
-        
+%09%09%09%09
 && !
@@ -825,32 +825,24 @@
 gClass)) %7B%0A%09
-%09%09try %7B%0A
 %09%09%09%09security
@@ -886,16 +886,177 @@
 SSION);%0A
+%09%09%09%09%7D%0A%09%09%09%09else if ((modifiers & (Modifier.PUBLIC)) == 0%0A%09%09%09%09%09%09&& declaringClass.equals(ClassLoader.class))%7B%0A%09%09%09%09%09securityManager.checkCreateClassLoader();%0A%09%09%09%09%7D%0A
 %09%09%09%7D%0A%09%09%09
@@ -1088,16 +1088,17 @@
 tion ex)
+ 
 %7B%0A%09%09%09%09th
@@ -1248,16 +1248,49 @@
  method)
+  throws IllegalArgumentException
  %7B%0A%09%09che
@@ -1473,16 +1473,50 @@
 d field)
+  throws IllegalArgumentException 
  %7B%0A%09%09che
@@ -1611,12 +1611,10 @@
 ,%0A%09%09
-    
+%09%09
 %22fie

Fix access permission checks