source: cows_wps/trunk/cows_wps/utils/role_handler.py @ 6869

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows_wps/trunk/cows_wps/utils/role_handler.py@6869
Revision 6869, 2.4 KB checked in by astephen, 10 years ago (diff)

Added RoleHandler? class for converting user_roles.ini file into
groups/roles that can be encoded in part of the URL for downloads
and outputs as a simple string of hexidecimal characters. Each bit
refers to a role (or dataset) so multiple roles can be encoded
efficiently (8 per 2 characters).

Line 
1"""
2role_handler.py
3===============
4
5Holds RoleHandler class for handling user roles as provided in:
6
7 user_roles.ini
8
9configuration file.
10
11"""
12
13import os
14import re
15import ConfigParser
16
17
18class RoleHandler(object):
19
20    def __init__(self, config = None):
21        if config == None:
22            self._parseConfig()
23
24    def _parseConfig(self, conf_file = "../../user_roles.ini"):
25        if not os.path.isfile(conf_file):
26            raise Exception("No such file: %s" % conf_file)
27
28        self.roles = {}
29        conf = ConfigParser.ConfigParser() 
30        conf.read(conf_file)
31
32        for indx in conf.options("roles"):
33            i = int(indx)
34            value = conf.get("roles", indx)
35            self.roles[i] = value
36
37        return self.roles
38
39    def _isBitSwitchedOnAt(self, number, position):
40        "Returns boolean of whether the particular bit at ``position`` is ON (or 1 or True) in ``number``."
41        return (number >> position) & 1
42
43    def _checkRoleString(self, role_string):
44        if not len(role_string) % 2 == 0:
45            raise Exception("Role string must be even in length, this is not: '%s'" % role_string)
46
47        if not re.match("^[a-fA-F0-9]+$", role_string):
48            raise Exception("Role string must be valid hexidecimal characters.")
49
50    def lookupRole(self, indx):
51        "Returns role name or raises exception if not matched."
52        if indx not in self.roles.keys():
53            raise Exception("Role number '%s' not known." % indx)
54
55        return self.roles[indx]
56
57    def mapRoles(self, role_string):
58        "Takes role string and returns a list of valid roles."
59        self._checkRoleString(role_string) 
60
61        rs = role_string
62        roles = []
63        indx_count = 1
64
65        while len(rs) > 0:
66            roles_code = int(rs[-2:], 16)
67
68            for i in range(8):
69                if self._isBitSwitchedOnAt(roles_code, i):
70                    role = self.lookupRole(indx_count)
71                    roles.append(role)
72#                    print roles_code, rs, i, role
73                   
74
75                indx_count += 1
76
77            rs = rs[:-2]
78
79        return roles
80
81
82if __name__ == "__main__":
83
84    rh = RoleHandler()
85    for i in ("aa", "00", "03", "ff", "fa", "80", "02fa", "05ff"):
86         print "Code: %s (%d) -> %s" % (i, int(i, 16),  " ".join(rh.mapRoles(i))) 
87
88    try: 
89        print rh.mapRoles("ffff")
90    except:
91        print "Failed to map excess roles which is good!"
Note: See TracBrowser for help on using the repository browser.