FileDocCategorySizeDatePackage
PolicyUtils.javaAPI DocAndroid 1.5 API21908Wed May 06 22:41:06 BST 2009org.apache.harmony.security.fortress

PolicyUtils

public class PolicyUtils extends Object
This class consist of a number of static methods, which provide a common functionality for various policy and configuration providers.

Fields Summary
public static final String
POLICY_ALLOW_DYNAMIC
A key to security properties, deciding whether usage of dynamic policy location via system properties is allowed.
public static final String
POLICY_EXPAND
A key to security properties, deciding whether expansion of system properties is allowed (in security properties values, policy files, etc).
public static final String
TRUE
Positive value of switching properties.
public static final String
FALSE
Negative value of switching properties.
private static final Class[]
NO_ARGS
private static final Class[]
ONE_ARGS
private static final Class[]
TWO_ARGS
Constructors Summary
private PolicyUtils()

Methods Summary
public static booleancanExpandProperties()
Returns false if current security settings disable to perform properties expansion, true otherwise.

see
#expand(String, Properties)

 //$NON-NLS-1$

                             
        
        return !FALSE.equalsIgnoreCase(AccessController
                .doPrivileged(new SecurityPropertyAccessor(POLICY_EXPAND)));
    
public static java.lang.Stringexpand(java.lang.String str, java.util.Properties properties)
Substitutes all entries like ${some.key}, found in specified string, for specified values. If some key is unknown, throws ExpansionFailedException.

param
str the string to be expanded
param
properties available key-value mappings
return
expanded string
throws
ExpansionFailedException

        final String START_MARK = "${"; //$NON-NLS-1$
        final String END_MARK = "}"; //$NON-NLS-1$
        final int START_OFFSET = START_MARK.length();
        final int END_OFFSET = END_MARK.length();

        StringBuilder result = new StringBuilder(str);
        int start = result.indexOf(START_MARK);
        while (start >= 0) {
            int end = result.indexOf(END_MARK, start);
            if (end >= 0) {
                String key = result.substring(start + START_OFFSET, end);
                String value = properties.getProperty(key);
                if (value != null) {
                    result.replace(start, end + END_OFFSET, value);
                    start += value.length();
                } else {
                    throw new ExpansionFailedException(Messages.getString("security.14F", key)); //$NON-NLS-1$
                }
            }
            start = result.indexOf(START_MARK, start);
        }
        return result.toString();
    
public static java.lang.StringexpandGeneral(java.lang.String str, org.apache.harmony.security.fortress.PolicyUtils$GeneralExpansionHandler handler)
Substitutes all entries like ${{protocol:data}}, found in specified string, for values resolved by passed handler. The data part may be empty, and in this case expression may have simplified form, as ${{protocol}}. If some entry cannot be resolved, throws ExpansionFailedException;

param
str the string to be expanded
param
handler the handler to resolve data denoted by protocol
return
expanded string
throws
ExpansionFailedException

        final String START_MARK = "${{"; //$NON-NLS-1$
        final String END_MARK = "}}"; //$NON-NLS-1$
        final int START_OFFSET = START_MARK.length();
        final int END_OFFSET = END_MARK.length();

        StringBuilder result = new StringBuilder(str);
        int start = result.indexOf(START_MARK);
        while (start >= 0) {
            int end = result.indexOf(END_MARK, start);
            if (end >= 0) {
                String key = result.substring(start + START_OFFSET, end);
                int separator = key.indexOf(':");
                String protocol = (separator >= 0) ? key
                        .substring(0, separator) : key;
                String data = (separator >= 0) ? key.substring(separator + 1)
                        : null;
                String value = handler.resolve(protocol, data);
                result.replace(start, end + END_OFFSET, value);
                start += value.length();
            }
            start = result.indexOf(START_MARK, start);
        }
        return result.toString();
    
public static java.lang.StringexpandURL(java.lang.String str, java.util.Properties properties)
Handy shortcut for expand(str, properties).replace(File.separatorChar, '/').

see
#expand(String, Properties)

        return expand(str, properties).replace(File.separatorChar, '/");
    
public static java.net.URL[]getPolicyURLs(java.util.Properties system, java.lang.String systemUrlKey, java.lang.String securityUrlPrefix)
Obtains a list of locations for a policy or configuration provider. The search algorithm is as follows:
  1. Look in security properties for keys of form prefix + n, where n is an integer and prefix is a passed parameter. Sequence starts with n=1, and keeps incrementing n until next key is not found.
    For each obtained key, try to construct an URL instance. On success, add the URL to the list; otherwise ignore it.
  2. If security settings do not prohibit (through {@link #POLICY_ALLOW_DYNAMIC the "policy.allowSystemProperty" property}) to use additional policy location, read the system property under the passed key parameter. If property exists, it may designate a file or an absolute URL. Thus, first check if there is a file with that name, and if so, convert the pathname to URL. Otherwise, try to instantiate an URL directly. If succeeded, append the URL to the list
  3. If the additional location from the step above was specified to the system via "==" (i.e. starts with '='), discard all URLs above and use this only URL.
Note: all property values (both security and system) related to URLs are subject to {@link #expand(String, Properties) property expansion}, regardless of the "policy.expandProperties" security setting.

param
system system properties
param
systemUrlKey key to additional policy location
param
securityUrlPrefix prefix to numbered locations in security properties
return
array of URLs to provider's configuration files, may be empty.


        final SecurityPropertyAccessor security = new SecurityPropertyAccessor(
                null);
        final List<URL> urls = new ArrayList<URL>();
        boolean dynamicOnly = false;
        URL dynamicURL = null;

        //first check if policy is set via system properties
        if (!FALSE.equalsIgnoreCase(AccessController
                .doPrivileged(security.key(POLICY_ALLOW_DYNAMIC)))) {
            String location = system.getProperty(systemUrlKey);
            if (location != null) {
                if (location.startsWith("=")) { //$NON-NLS-1$
                    //overrides all other urls
                    dynamicOnly = true;
                    location = location.substring(1);
                }
                try {
                    location = expandURL(location, system);
                    // location can be a file, but we need an url...
                    final File f = new File(location);
                    dynamicURL = AccessController
                            .doPrivileged(new PrivilegedExceptionAction<URL>() {

                                public URL run() throws Exception {
                                    if (f.exists()) {
                                        return f.toURI().toURL();
                                    } else {
                                        return null;
                                    }
                                }
                            });
                    if (dynamicURL == null) {
                        dynamicURL = new URL(location);
                    }
                }
                catch (Exception e) {
                    // TODO: log error
                    // System.err.println("Error detecting system policy location: "+e);
                }
            }
        }
        //next read urls from security.properties 
        if (!dynamicOnly) {
            int i = 1;
            while (true) {
                String location = AccessController
                        .doPrivileged(security.key(new StringBuilder(
                                securityUrlPrefix).append(i++).toString()));
                if (location == null) {
                    break;
                }
                try {
                    location = expandURL(location, system);
                    URL anURL = new URL(location);
                    if (anURL != null) {
                        urls.add(anURL);
                    }
                }
                catch (Exception e) {
                    // TODO: log error
                    // System.err.println("Error detecting security policy location: "+e);
                }
            }
        }
        if (dynamicURL != null) {
            urls.add(dynamicURL);
        }
        return urls.toArray(new URL[urls.size()]);
    
public static java.security.PermissioninstantiatePermission(java.lang.Class targetType, java.lang.String targetName, java.lang.String targetActions)
Tries to find a suitable constructor and instantiate a new Permission with specified parameters.

param
targetType class of expected Permission instance
param
targetName name of expected Permission instance
param
targetActions actions of expected Permission instance
return
a new Permission instance
throws
IllegalArgumentException if no suitable constructor found
throws
Exception any exception thrown by Constructor.newInstance()


                                                                 
        
                  

        // let's guess the best order for trying constructors
        Class[][] argTypes = null;
        Object[][] args = null;
        if (targetActions != null) {
            argTypes = new Class[][] { TWO_ARGS, ONE_ARGS, NO_ARGS };
            args = new Object[][] { { targetName, targetActions },
                    { targetName }, {} };
        } else if (targetName != null) {
            argTypes = new Class[][] { ONE_ARGS, TWO_ARGS, NO_ARGS };
            args = new Object[][] { { targetName },
                    { targetName, targetActions }, {} };
        } else {
            argTypes = new Class[][] { NO_ARGS, ONE_ARGS, TWO_ARGS };
            args = new Object[][] { {}, { targetName },
                    { targetName, targetActions } };
        }

        // finally try to instantiate actual permission
        for (int i = 0; i < argTypes.length; i++) {
            try {
                Constructor<?> ctor = targetType.getConstructor(argTypes[i]);
                return (Permission)ctor.newInstance(args[i]);
            }
            catch (NoSuchMethodException ignore) {}
        }
        throw new IllegalArgumentException(
                Messages.getString("security.150", targetType));//$NON-NLS-1$
    
public static booleanmatchSubset(java.lang.Object[] what, java.lang.Object[] where)
Checks whether the objects from what array are all presented in where array.

param
what first array, may be null
param
where second array, may be null
return
true if the first array is null or if each and every object (ignoring null values) from the first array has a twin in the second array; false otherwise

        if (what == null) {
            return true;
        }

        for (int i = 0; i < what.length; i++) {
            if (what[i] != null) {
                if (where == null) {
                    return false;
                }
                boolean found = false;
                for (int j = 0; j < where.length; j++) {
                    if (what[i].equals(where[j])) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    return false;
                }
            }
        }
        return true;
    
public static java.security.PermissionCollectiontoPermissionCollection(java.util.Collection perms)
Converts common-purpose collection of Permissions to PermissionCollection.

param
perms a collection containing arbitrary permissions, may be null
return
mutable heterogeneous PermissionCollection containing all Permissions from the specified collection

        Permissions pc = new Permissions();
        if (perms != null) {
            for (Iterator<Permission> iter = perms.iterator(); iter.hasNext();) {
                Permission element = iter.next();
                pc.add(element);
            }
        }
        return pc;