001    package de.deepamehta.plugins.accesscontrol.model;
002    
003    import org.codehaus.jettison.json.JSONArray;
004    import org.codehaus.jettison.json.JSONObject;
005    
006    import java.util.HashMap;
007    import java.util.Iterator;
008    import java.util.Map;
009    import static java.util.Arrays.asList;
010    
011    
012    
013    public class AccessControlList {
014    
015        // ---------------------------------------------------------------------------------------------- Instance Variables
016    
017        private Map<Operation, UserRole[]> acl = new HashMap<Operation, UserRole[]>();
018    
019        // ---------------------------------------------------------------------------------------------------- Constructors
020    
021        public AccessControlList(ACLEntry... aclEntries) {
022            for (ACLEntry aclEntry : aclEntries) {
023                addEntry(aclEntry);
024            }
025        }
026    
027        public AccessControlList(JSONObject acl) {
028            try {
029                Iterator i = acl.keys();
030                while (i.hasNext()) {
031                    Operation operation = Operation.valueOf((String) i.next());
032                    JSONArray a = acl.getJSONArray(operation.name());
033                    int len = a.length();
034                    UserRole[] userRoles = new UserRole[len];
035                    for (int j = 0; j < len; j++) {
036                        userRoles[j] = UserRole.valueOf(a.getString(j));
037                    }
038                    addEntry(new ACLEntry(operation, userRoles));
039                }
040            } catch (Exception e) {
041                throw new RuntimeException("Parsing AccessControlList failed (JSONObject=" + acl + ")", e);
042            }
043        }
044    
045        // -------------------------------------------------------------------------------------------------- Public Methods
046    
047        public UserRole[] getUserRoles(Operation operation) {
048            UserRole[] userRoles = acl.get(operation);
049            return userRoles != null ? userRoles : new UserRole[0];
050        }
051    
052        public AccessControlList addEntry(ACLEntry aclEntry) {
053            acl.put(aclEntry.getOperation(), aclEntry.getUserRoles());
054            return this;
055        }
056    
057        // ---
058    
059        // Note: we do not implement JSONEnabled. An AccessControlList is never send through the wire.
060        public JSONObject toJSON() {
061            try {
062                JSONObject json = new JSONObject();
063                for (Operation operation : acl.keySet()) {
064                    json.put(operation.name(), asList(getUserRoles(operation)));
065                }
066                return json;
067            } catch (Exception e) {
068                throw new RuntimeException("Serialization failed (" + this + ")", e);
069            }
070        }
071    }