source: mauRepo/newmoonProject/trunk/project/xmi2rdbms/src/main/resources/ascore/asunion.py @ 8174

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/newmoonProject/trunk/project/xmi2rdbms/src/main/resources/ascore/asunion.py@8174
Revision 8174, 3.9 KB checked in by mnagni, 8 years ago (diff)
Line 
1'''
2Created on Nov 25, 2011
3
4@author: mnagni
5'''
6import inspect
7from copy import deepcopy
8
9class UnionMeta(type):
10
11    def __init__(cls, classname, bases, dict_):
12        for k, v in dict_.items():
13            if k.startswith('_'):
14                continue
15           
16            if isinstance(v, dict):
17                values = {}
18                for attrName, attrType in v.items():         
19                    if not inspect.isclass(attrType):
20                        raise Exception("Types %s in not a class" % (attrType))
21                    else:
22                        values[attrName] = None
23                setattr(cls, '_values', values)
24                setattr(cls, '_typesDictionary', v)
25        return type.__init__(cls, classname, bases, dict_)
26
27class ASUnion(object):
28    __metaclass__ = UnionMeta
29   
30    '''
31        Implements the GML <<Union>> stereotype.
32        Extract from the OGC 07-036:
33            <<Union>> is a set of properties.
34            The semantics is that only one of the properties may be present at any time.
35
36        Because of this this class has two inner dictionaries,
37            - a dictionary of pairs attributeName:classType
38            - a dictionary of pairs attributeName:value
39           
40        The attributes are managed by one get/set method for the actual value
41        and one getTypes() to enlist which kind of instances are accepted by the class
42    '''   
43   
44    def getValue(self, attributeName):
45        '''
46        @param attributeName: the name of the attribute to get
47        @raise KeyError: if the given attributeName does not exist
48        '''       
49        self._attributeHasType (attributeName)
50        return self._values[attributeName]
51       
52    def setValue(self, attributeName, value):
53        '''
54        @param attributeName: the name of the attribute to set       
55        @param value: the new instance value
56        @raise KeyError: if the given attributeName does not exist
57        @raise TypeError: if the given value does not match the attribute type
58        '''
59       
60        attrType = self._attributeHasType (attributeName)
61       
62        if value is None:
63            self._values[attributeName] = value
64           
65        #check that the given value is
66        try:
67            self._checkValues(value, attrType)
68        except TypeError :
69            raise TypeError("The value (or values) type does not match the attribute %s type" % (attributeName))
70               
71        self._values[attributeName] = value
72   
73    def getAttributesDictionary(self):
74        return deepcopy(self._typesDictionary)
75
76    def _attributeHasType(self, attributeName):
77        '''
78        @param attributeName: the name of the attribute to get
79        @raise KeyError: if the given attributeName does not exist
80        '''         
81        try:
82            attrType = self._typesDictionary[attributeName]   
83        except Exception as ex:
84            raise KeyError("The attribute named %s does not exist" % (attributeName))
85        return attrType
86   
87    def _checkValues(self, value, type):
88        if isinstance(value, list):
89            for v in value:
90                self._checkType(v, type)
91        else:
92            self._checkType(value, type)
93   
94    def _checkType(self, value, innerType):
95        if type(value) != innerType:
96            raise TypeError("The value type does not match the attribute type %s" % (type))
97'''   
98class MyUnion(ASUnion):
99    test = {'attr1': AssertionError, 'attr2': ArithmeticError}
100       
101mu = MyUnion()
102print(mu.getAttributesDictionary())
103
104#Raises exception
105try:
106    mu.setValue('attr1', TypeError('NOK'))
107except Exception as ex:
108    print ex
109
110#Raises exception
111try:
112    mu.setValue('attr6', TypeError('NOK'))
113except Exception as ex:
114    print ex
115
116#Does NOT raise exception
117mu.setValue('attr1', AssertionError('OK'))
118
119#Raises exception
120try:
121    print(mu.getValue('attr5'))
122except Exception as ex:
123    print ex
124   
125val = mu.getValue('attr1')
126print(val)
127'''
Note: See TracBrowser for help on using the repository browser.