/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.generic;

import java.security.AccessController;
import java.security.PrivilegedAction;
import net.ranides.assira.reflection.inspect.ClassInspector;
import net.ranides.assira.reflection.inspect.FieldInspector;

/**
 *
 * @author ranides
 */
public final class PrivilegedActions {
    
    private PrivilegedActions() {
        // utility class
    }

    /**
     * Gets the system property indicated by the specified key.
     * @param key the name of the system property.
     * @return the string value of the system property,
     *         or the default value if there is no property with that key.
     * @see System#getProperty(String,String) 
     */
    public static String getProperty(final String key) {
        return AccessController.doPrivileged(new PrivilegedAction<String>(){
            @Override
            public String run() {
                return System.getProperty(key);
            }
        });
    }
    
    /**
     *
     * @param  key the name of the system property.
     * @param  ddefault a default value.
     * @return the string value of the system property,
     *         or the default value if there is no property with that key.
     */
    public static String getProperty(final String key, final String ddefault) {
        return AccessController.doPrivileged(new PrivilegedAction<String>(){
            @Override
            public String run() {
                return System.getProperty(key, ddefault);
            }
        });
    }
    
    /**
     *
     * @return
     */
    public static ClassLoader getContextClassLoader() {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>(){
            @Override
            public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
            }
        });
    }
    
    public static Object getStaticField(final Class<?> clazz, final String field) {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override 
            public Object run() {
                return FieldInspector.find(clazz, field).get(null);
            }
        });
    }
    
    public static Object getStaticField(final String clazz, final String field) {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override 
            public Object run() {
                return FieldInspector.find(ClassInspector.forName(clazz), field).get(null);
            }
        });
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T $getStaticField(final String clazz, final String field) {
        return (T)getStaticField(clazz, field);
    }
    
}
