Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) OSGi Alliance (2004, 2011). All Rights Reserved.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.osgi.service.dmt;
 
 import java.util.Map;
Acl is an immutable class representing structured access to DMT ACLs. Under OMA DM the ACLs are defined as strings with an internal syntax.

The methods of this class taking a principal as parameter accept remote server IDs (as passed to DmtAdmin.getSession), as well as " * " indicating any principal.

The syntax for valid remote server IDs:
<server-identifier> ::= All printable characters except '=', '&amp;', '*', '+' or white-space characters.

Version:
$Id: 28457c6c47cdd5ba09f13d8a4ef36403048990b7 $
 
 public final class Acl {
 
     // ----- Public constants -----//
 
    
Principals holding this permission can issue GET command on the node having this ACL.
 
     public static final int GET = 1;

    
Principals holding this permission can issue ADD commands on the node having this ACL.
 
     public static final int ADD = 2;

    
Principals holding this permission can issue REPLACE commands on the node having this ACL.
 
     public static final int REPLACE = 4;

    
Principals holding this permission can issue DELETE commands on the node having this ACL.
 
     public static final int DELETE = 8;

    
Principals holding this permission can issue EXEC commands on the node having this ACL.
 
     public static final int EXEC = 16;

    
Principals holding this permission can issue any command on the node having this ACL. This permission is the logical OR of ADD, DELETE, EXEC, GET and REPLACE permissions.
 
     public static final int ALL_PERMISSION =  |  |  | 
             | ;
 
     // ----- Private constants -----//
 
     private static final int[] PERMISSION_CODES = new int[] { ,
              };
 
     private static final String[] PERMISSION_NAMES = new String[] { "Add",
             "Delete""Exec""Get""Replace" };
 
     private static final String ALL_PRINCIPALS = "*";
 
     // ----- Private fields -----//
 
     // the implementation takes advantage of this being a sorted map
     private final TreeMap principalPermissions;
 
     private final int globalPermissions;
 
    // ----- Public constructors -----//

    
Create an instance of the ACL from its canonical string representation.

Parameters:
acl The string representation of the ACL as defined in OMA DM. If null or empty then it represents an empty list of principals with no permissions.
Throws:
java.lang.IllegalArgumentException if acl is not a valid OMA DM ACL string
    public Acl(String acl) {
        if (acl == null || acl.equals("")) { // empty permission set
             = new TreeMap();
             = 0;
            return;
        }
        TreeMap tempPrincipalPermissions = new TreeMap();
        int tempGlobalPermissions = 0;
        String[] aclEntries = split(acl'&', -1);
        for (int i = 0; i < aclEntries.lengthi++) {
            if (aclEntries[i].length() == 0)
                throw new IllegalArgumentException(
                        "Invalid ACL string: empty ACL entry.");
            String[] entryParts = split(aclEntries[i], '=', 2);
            if (entryParts.length == 1)
                throw new IllegalArgumentException(
                        "Invalid ACL string: no '=' in ACL entry.");
            if (entryParts[1].length() == 0)
                throw new IllegalArgumentException(
                        "Invalid ACL string: no server identifiers in ACL entry.");
            int command = parseCommand(entryParts[0]);
            String[] serverIds = split(entryParts[1], '+', -1);
            for (int j = 0; j < serverIds.lengthj++) {
                if (serverIds[j].length() == 0)
                    throw new IllegalArgumentException(
                            "Invalid ACL string: empty server identifier.");
                if (serverIds[j].equals())
                    tempGlobalPermissions |= command;
                else {
                    checkServerId(serverIds[j], "Invalid ACL string: "
                            + "server ID contains illegal character");
                    Integer n = (IntegertempPrincipalPermissions
                            .get(serverIds[j]);
                    int oldPermission = (n != null) ? n.intValue() : 0;
                    tempPrincipalPermissions.put(serverIds[j], new Integer(
                            oldPermission | command));
                }
            }
        }
         = tempPrincipalPermissions;
         = tempGlobalPermissions;
    }

    
Creates an instance with a specified list of principals and the permissions they hold. The two arrays run in parallel, that is principals[i] will hold permissions[i] in the ACL.

A principal name may not appear multiple times in the 'principals' argument. If the "*" principal appears in the array, the corresponding permissions will be granted to all principals (regardless of whether they appear in the array or not).

Parameters:
principals The array of principals
permissions The array of permissions
Throws:
java.lang.IllegalArgumentException if the length of the two arrays are not the same, if any array element is invalid, or if a principal appears multiple times in the principals array
    public Acl(String[] principalsint[] permissions) {
        if (principals.length != permissions.length)
            throw new IllegalArgumentException(
                    "The lengths of the principal and permission arrays are not the same.");
        TreeMap tempPrincipalPermissions = new TreeMap();
        int tempGlobalPermissions = 0;
        for (int i = 0; i < principals.lengthi++) {
            // allow one * in 'principals' array, remove after loop
            if (!.equals(principals[i]))
                checkPrincipal(principals[i]);
            checkPermissions(permissions[i]);
            Integer permInt = new Integer(permissions[i]);
            Object old = tempPrincipalPermissions.put(principals[i], permInt);
            if (old != null)
                throw new IllegalArgumentException("Principal '"
                        + principals[i]
                        + "' appears multiple times in the principal array.");
        }
        // set the global permissions if there was a * in the array
        Object globalPermObj = tempPrincipalPermissions.remove();
        if (globalPermObj != null)
            tempGlobalPermissions = ((IntegerglobalPermObj).intValue();
         = tempPrincipalPermissions;
         = tempGlobalPermissions;
    }
    // ----- Private constructors -----//

    
Creates an instance identical to the base ACL except for the permissions of the given principal, which are overwritten with the given permissions.

Assumes that the permissions parameter has been checked. All modifications of an Acl (add, delete, set) are done through this method.

Parameters:
base The ACL that provides all permissions except for permissions of the given principal.
principal The entity to which permission should be granted.
permissions The set of permissions to be given. The parameter can be a logical or of the permission constants defined in this class.
    private Acl(Acl baseString principalint permissions) {
        // make a shallow copy of the permission table, the keys (String) and
        // values (Integer) are immutable anyway
        TreeMap tempPrincipalPermissions = (TreeMapbase.principalPermissions
                .clone();
        int tempGlobalPermissions = base.globalPermissions;
        int deletedGlobalPerm = tempGlobalPermissions & ~permissions;
        if (.equals(principal)) {
            deleteFromAll(tempPrincipalPermissionsdeletedGlobalPerm);
            tempGlobalPermissions = permissions;
        } else {
            checkPrincipal(principal);
            if (deletedGlobalPerm != 0)
                throw new IllegalArgumentException(
                        "Cannot revoke globally set permissions ("
                                + writeCommands(deletedGlobalPerm)
                                + ") from a specific principal (" + principal
                                + ").");
            setPrincipalPermission(tempPrincipalPermissionsprincipal,
                    permissions);
        }
         = tempPrincipalPermissions;
         = tempGlobalPermissions;
    }
    // ----- Public methods -----//

    
Checks whether the given object is equal to this Acl instance. Two Acl instances are equal if they allow the same set of permissions for the same set of principals.

Parameters:
obj the object to compare with this Acl instance
Returns:
true if the parameter represents the same ACL as this instance
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!(obj instanceof Acl))
            return false;
        Acl other = (Aclobj;
        if ( != other.globalPermissions
                || .size() != other.principalPermissions
                        .size())
            return false;
        // principalPermissions sets cannot be easily compared, because they are
        // not canonical: the global permissions may or may not be present for
        // each principal, without changing the meaning of the Acl object.
        // Compare canonical string representations, inefficient but simple.
        return toString().equals(other.toString());
    }

Returns the hash code for this ACL instance. If two Acl instances are equal according to the equals(java.lang.Object) method, then calling this method on each of them must produce the same integer result.

Returns:
hash code for this ACL
	public int hashCode() {
        // Using the hash code of the canonical string representation, because
        // the principalPermissions set is not canonical (see above).
        return toString().hashCode();
    }

    
Create a new Acl instance from this Acl with the given permission added for the given principal. The already existing permissions of the principal are not affected.

Parameters:
principal The entity to which permissions should be granted, or "*" to grant permissions to all principals.
permissions The permissions to be given. The parameter can be a logical or of more permission constants defined in this class.
Returns:
a new Acl instance
Throws:
java.lang.IllegalArgumentException if principal is not a valid principal name or if permissions is not a valid combination of the permission constants defined in this class
    public synchronized Acl addPermission(String principalint permissions) {
        checkPermissions(permissions);
        int oldPermissions = getPermissions(principal);
        return setPermission(principaloldPermissions | permissions);
    }

    
Create a new Acl instance from this Acl with the given permission revoked from the given principal. Other permissions of the principal are not affected.

Note, that it is not valid to revoke a permission from a specific principal if that permission is granted globally to all principals.

Parameters:
principal The entity from which permissions should be revoked, or "*" to revoke permissions from all principals.
permissions The permissions to be revoked. The parameter can be a logical or of more permission constants defined in this class.
Returns:
a new Acl instance
Throws:
java.lang.IllegalArgumentException if principal is not a valid principal name, if permissions is not a valid combination of the permission constants defined in this class, or if a globally granted permission would have been revoked from a specific principal
    public synchronized Acl deletePermission(String principalint permissions) {
        checkPermissions(permissions);
        int oldPermissions = getPermissions(principal);
        return setPermission(principaloldPermissions & ~permissions);
    }

    
Get the permissions associated to a given principal.

Parameters:
principal The entity whose permissions to query, or "*" to query the permissions that are granted globally, to all principals
Returns:
The permissions of the given principal. The returned int is a bitmask of the permission constants defined in this class
Throws:
java.lang.IllegalArgumentException if principal is not a valid principal name
    public synchronized int getPermissions(String principal) {
        int permissions = 0;
        if (!(.equals(principal))) {
            checkPrincipal(principal);
            Object po = .get(principal);
            if (po != null)
                permissions = ((Integerpo).intValue();
        }
        return permissions | ;
    }

    
Check whether the given permissions are granted to a certain principal. The requested permissions are specified as a bitfield, for example (Acl.ADD | Acl.DELETE | Acl.GET).

Parameters:
principal The entity to check, or "*" to check whether the given permissions are granted to all principals globally
permissions The permissions to check
Returns:
true if the principal holds all the given permissions
Throws:
java.lang.IllegalArgumentException if principal is not a valid principal name or if permissions is not a valid combination of the permission constants defined in this class
    public synchronized boolean isPermitted(String principalint permissions) {
        checkPermissions(permissions);
        int hasPermissions = getPermissions(principal);
        return (permissions & hasPermissions) == permissions;
    }

    
Create a new Acl instance from this Acl where all permissions for the given principal are overwritten with the given permissions.

Note, that when changing the permissions of a specific principal, it is not allowed to specify a set of permissions stricter than the global set of permissions (that apply to all principals).

Parameters:
principal The entity to which permissions should be granted, or "*" to globally grant permissions to all principals.
permissions The set of permissions to be given. The parameter is a bitmask of the permission constants defined in this class.
Returns:
a new Acl instance
Throws:
java.lang.IllegalArgumentException if principal is not a valid principal name, if permissions is not a valid combination of the permission constants defined in this class, or if a globally granted permission would have been revoked from a specific principal
    public synchronized Acl setPermission(String principalint permissions) {
        checkPermissions(permissions);
        Acl newPermission = new Acl(thisprincipalpermissions);
        return newPermission;
    }

    
Get the list of principals who have any kind of permissions on this node. The list only includes those principals that have been explicitly assigned permissions (so "*" is never returned), globally set permissions naturally apply to all other principals as well.

Returns:
The array of principals having permissions on this node.
    public String[] getPrincipals() {
        return (String[]) (.keySet().toArray(new String[0]));
    }

    
Give the canonical string representation of this ACL. The operations are in the following order: {Add, Delete, Exec, Get, Replace}, principal names are sorted alphabetically.

Returns:
The string representation as defined in OMA DM.
    public synchronized String toString() {
        String acl = null;
        for (int i = 0; i < .i++)
            acl = writeEntry([i], acl);
        return (acl != null) ? acl : "";
    }
    // ----- Private utility methods -----//
    private String writeEntry(int commandString acl) {
        String aclEntry = null;
        if ((command & ) > 0)
            aclEntry = ;
        else {
            // TreeMap guarantees alphabetical ordering of keys during traversal
            Iterator i = .entrySet().iterator();
            while (i.hasNext()) {
                Map.Entry entry = (Map.Entryi.next();
                if ((command & ((Integerentry.getValue()).intValue()) > 0)
                    aclEntry = appendEntry(aclEntry'+', (Stringentry
                            .getKey());
            }
        }
        if (aclEntry == null)
            return acl;
        return appendEntry(acl'&'writeCommands(command) + '=' + aclEntry);
    }
    private static void deleteFromAll(TreeMap principalPermissionsint perm) {
        Iterator i = principalPermissions.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry entry = (Map.Entryi.next();
            setPrincipalPermission(principalPermissions, (Stringentry
                    .getKey(), ((Integerentry.getValue()).intValue() & ~perm);
        }
    }
    private static void setPrincipalPermission(TreeMap principalPermissions,
            String principalint perm) {
        if (perm == 0)
            principalPermissions.remove(principal);
        else
            principalPermissions.put(principalnew Integer(perm));
    }
    private static String writeCommands(int command) {
        String commandStr = null;
        for (int i = 0; i < .i++)
            if ((command & [i]) != 0)
                commandStr = appendEntry(commandStr','[i]);
        return (commandStr != null) ? commandStr : "";
    }
    private static String appendEntry(String basechar separatorString entry) {
        return (base != null) ? base + separator + entry : entry;
    }
    private static int parseCommand(String command) {
        int i = Arrays.asList().indexOf(command);
        if (i == -1)
            throw new IllegalArgumentException(
                    "Invalid ACL string: unknown command '" + command + "'.");
        return [i];
    }
    private static void checkPermissions(int perm) {
        if ((perm & ~) != 0)
            throw new IllegalArgumentException("Invalid ACL permission value: "
                    + perm);
    }
    private static void checkPrincipal(String principal) {
        if (principal == null || principal.length() == 0 )
            throw new IllegalArgumentException("Principal is null or empty.");
        checkServerId(principal"Principal name contains illegal character");
    }
    private static void checkServerId(String serverIdString errorText) {
        char[] chars = serverId.toCharArray();
        for (int i = 0; i < chars.lengthi++)
            if ("*=+&".indexOf(chars[i]) != -1
                    || Character.isWhitespace(chars[i]))
                throw new IllegalArgumentException(errorText + " '" + chars[i]
                        + "'.");
    }
    private static String[] split(String inputchar sepint limit) {
        Vector v = new Vector();
        boolean limited = (limit > 0);
        int applied = 0;
        int index = 0;
        StringBuffer part = new StringBuffer();
        while (index < input.length()) {
            char ch = input.charAt(index);
            if (ch != sep)
                part.append(ch);
            else {
                ++applied;
                v.add(part.toString());
                part = new StringBuffer();
            }
            ++index;
            if (limited && applied == limit - 1)
                break;
        }
        while (index < input.length()) {
            char ch = input.charAt(index);
            part.append(ch);
            ++index;
        }
        v.add(part.toString());
        int last = v.size();
        if (0 == limit) {
            for (int j = v.size() - 1; j >= 0; --j) {
                String s = (Stringv.elementAt(j);
                if ("".equals(s))
                    --last;
                else
                    break;
            }
        }
        String[] ret = new String[last];
        for (int i = 0; i < last; ++i)
            ret[i] = (Stringv.elementAt(i);
        return ret;
    }
New to GrepCode? Check out our FAQ X