cosmetic
[plcapi.git] / PLC / Namespace.py
1 URN_PREFIX = "urn:publicid:IDN"
2
3 def get_leaf(hrn):
4     parts = hrn.split(".")
5     return ".".join(parts[-1:])
6
7 def get_authority(hrn):
8     parts = hrn.split(".")
9     return ".".join(parts[:-1])
10
11 def hrn_to_pl_slicename(hrn):
12     parts = hrn.split(".")
13     return parts[-2] + "_" + parts[-1]
14
15 # assuming hrn is the hrn of an authority, return the plc authority name
16 def hrn_to_pl_authname(hrn):
17     parts = hrn.split(".")
18     return parts[-1]
19
20 # assuming hrn is the hrn of an authority, return the plc login_base
21 def hrn_to_pl_login_base(hrn):
22     return hrn_to_pl_authname(hrn)
23
24 def hostname_to_hrn(auth_hrn, login_base, hostname):
25     """
26     Convert hrn to planetlab name.
27     """
28     sfa_hostname = ".".join([auth_hrn, login_base, hostname.split(".")[0]])
29     return sfa_hostname
30
31 def slicename_to_hrn(auth_hrn, slicename):
32     """
33     Convert hrn to planetlab name.
34     """
35     parts = slicename.split("_")
36     slice_hrn = ".".join([auth_hrn, parts[0]]) + "." + "_".join(parts[1:])
37
38     return slice_hrn
39
40 def email_to_hrn(auth_hrn, email):
41     parts = email.split("@")
42     username = parts[0]
43     username = username.replace(".", "_")
44     person_hrn = ".".join([auth_hrn, username])
45
46     return person_hrn
47
48 def urn_to_hrn(urn):
49     """
50     convert a urn to hrn
51     return a tuple (hrn, type)
52     """
53
54     # if this is already a hrn dont do anything
55     if not urn or not urn.startswith(URN_PREFIX):
56         return urn, None
57
58     name = urn[len(URN_PREFIX):]
59     hrn_parts = name.split("+")
60
61     # type is always the second to last element in the list
62     type = hrn_parts.pop(-2)
63
64     # convert hrn_parts (list) into hrn (str) by doing the following
65     # remove blank elements
66     # replace ':' with '.'
67     # join list elements using '.'
68     hrn = '.'.join([part.replace(':', '.') for part in hrn_parts if part])
69
70     return str(hrn), str(type)
71
72
73 def hrn_to_urn(hrn, type=None):
74     """
75     convert an hrn and type to a urn string
76     """
77     # if  this is already a urn dont do anything
78     if not hrn or hrn.startswith(URN_PREFIX):
79         return hrn
80
81     authority = get_authority(hrn)
82     name = get_leaf(hrn)
83     urn = "+".join([unicode(part).replace('.', ':') \
84                     for part in ['',authority,type,name]])
85
86     return URN_PREFIX + urn