[Mobies-commit] [commit] r4253 - in UDM/trunk: lib src/Udm/PythonAPIGen src/UdmPython tests/test_UdmPythonDS

endre at redhat3.isis.vanderbilt.edu endre at redhat3.isis.vanderbilt.edu
Mon Feb 17 00:09:32 CST 2014


Author: endre
Date: Mon Feb 17 00:09:32 2014
New Revision: 4253

Log:
Python domain specific API (Metaobjects, Array Attribute handling, parent property )

Modified:
   UDM/trunk/lib/UdmPython.py
   UDM/trunk/src/Udm/PythonAPIGen/PythonAPIGen.cpp
   UDM/trunk/src/UdmPython/UdmPython.cpp
   UDM/trunk/tests/test_UdmPythonDS/test.py

Modified: UDM/trunk/lib/UdmPython.py
==============================================================================
--- UDM/trunk/lib/UdmPython.py	Mon Feb 10 01:19:52 2014	(r4252)
+++ UDM/trunk/lib/UdmPython.py	Mon Feb 17 00:09:32 2014	(r4253)
@@ -4,11 +4,22 @@
 		indent += "\t";
 	return indent
 
-class UdmPython:
+class UdmPython(object):
+	@property
+	def parent(self):
+		return UdmPython(self.impl.parent)
+
 	def __init__(self, impl):
-		self.__dict__['impl'] = impl
-		self.__dict__['id'] = impl.id
-		self.__dict__['indent'] = 0
+		if isinstance(impl, UdmPython):
+			#"copy constructor"... 
+			self.__dict__['impl'] = impl.impl
+			self.__dict__['id'] = impl.impl.id
+			self.__dict__['indent'] = 0
+		else:
+			#construction from udm.Object
+			self.__dict__['impl'] = impl
+			self.__dict__['id'] = impl.id
+			self.__dict__['indent'] = 0
 
 	def is_lib_root(self):
 		return self.impl.is_lib_root
@@ -20,13 +31,17 @@
 		return Uml.Class.cast(self.impl.type)
 
 	def children(self,child_role=None, parent_role=None, child_type=None):
+		#child_type could be either Udm.Object or UdmPython (or descendants)
 		ret = []
-		for child in self.impl.children(child_role, parent_role, child_type):
-			ret.append(UdmPython(child))
-		return ret
+		if isinstance(child_type, UdmPython):
+			for child in self.impl.children(child_role, parent_role, child_type.impl):
+				ret.append(UdmPython(child))
+			return ret
+		else:
+			for child in self.impl.children(child_role, parent_role, child_type):
+				ret.append(UdmPython(child))
+			return ret
 
-	def __impl(self):
-		return self.__dict__['impl']
 	def __eq__(self, other):
 		return self.__dict__['impl'] == other.__dict__['impl']
 	def __ne__(self, other):
@@ -61,7 +76,7 @@
                 		elif attr.type == "String":
 					line += indent(indent_tabs) + "attribute name: " + attr.name + ", value:" + attr_value + "\n"
             		else:
-				a_attr = ArrayAttr(self.impl, attr)
+				a_attr = ArrayAttr(self, attr)
 				a_attr.setIndent(indent_tabs)
 				line += a_attr.__str__() + "\n"
 		return line
@@ -74,7 +89,20 @@
 		return self.impl.__nonzero__();
 
 class ArrayAttr(object):
+	@property
+	def array(self):
+		attr_value=self.obj.get_attribute(self.attr.impl)
+		return ArrayAttr.escaped_split(str(attr_value), ';')
 
+	@array.setter
+	def array(self, val):
+		if type(val) != type([]):
+			raise Exception("ArrayAttr.array.setter: expected array")
+		new_arr = []
+		for val_item in val:
+			new_arr.append(str(val_item))#this will work for any type
+		arr_str = ArrayAttr.escaped_combine(new_arr, ';')
+        	self.obj.set_attribute(self.attr.impl, arr_str)
 
 	@staticmethod
 	def escaped_split(s, delim):
@@ -85,7 +113,7 @@
 			if ch == '\\':
 				try:
                 			# skip the next character; it has been escaped!
-                			current.append('\\')
+                			#current.append('\\')
                 			current.append(itr.next())
             			except StopIteration:
                 			pass
@@ -97,6 +125,20 @@
             			current.append(ch)
     		ret.append(''.join(current))
     		return ret
+	@staticmethod
+	def escaped_combine(s, delim):
+		ret = ""
+		first = True
+		for s_i in s:
+			if not first: ret += delim
+			first = False
+			itr = iter(s_i)
+			for ch in itr:
+				if ch == '\\' or ch == delim:
+					ret += '\\'
+				ret += ch
+		return ret;
+
 
 	def __init__(self, obj, attr):
 		import Uml
@@ -104,7 +146,7 @@
 			raise ("Attribute is not an array")
 		
 		self.attr = attr
-		self.obj = obj
+		self.obj = obj.impl
 		self.indent = 0
 
 	def setIndent(self,i):
@@ -124,9 +166,29 @@
 		return lines
 
 	def __getitem__(self,index):
-		attr_value=obj.get_attribute(attr.impl)
+		attr_value=self.obj.get_attribute(self.attr.impl)
 		str_array = ArrayAttr.escaped_split(str(attr_value), ';')
-		return self.str_array[index]
+		if index > len(str_array):
+			raise Exception("Index out of array boundaries")
+		return str_array[index]
+
+	def __setitem__(self, index, value):
+
+		attr_value=self.obj.get_attribute(self.attr.impl)
+		str_array = ArrayAttr.escaped_split(str(attr_value), ';')
+		if index > len(str_array):
+			raise Exception("Index out of array boundaries")
+		str_array_new = []
+		i=0;
+		for str_array_i in str_array:
+			if i == index:
+				str_array_new.append(str(value))
+			else:
+				str_array_new.append(str_array_i)
+			i=i+1
+		arr_str = ArrayAttr.escaped_combine(str_array_new, ';')
+        	self.obj.set_attribute(self.attr.impl, arr_str)
+
 
 class StrArrayAttr(ArrayAttr):
 
@@ -139,6 +201,13 @@
 
 			
 class IntArrayAttr(ArrayAttr):
+	@property
+	def array(self):
+		str_array = super(IntArrayAttr, IntArrayAttr).array.fget(self)
+		ret = []
+		for str_i in str_array:
+			ret.append(int(str_i))
+		return ret
 
 	def __init__(self, obj, attr):
 		import Uml
@@ -147,9 +216,17 @@
 		super(StrArrayAttr, self).__init__(obj, attr)
 
 	def __getitem__(self,index):
-		return int(super(IntArrayAttr, self).__getitem__[index])
+		return int(super(IntArrayAttr, self).__getitem__(index))
+
 
 class RealArrayAttr(ArrayAttr):
+	@property
+	def array(self):
+		str_array = super(IntArrayAttr, IntArrayAttr).array.fget(self)
+		ret = []
+		for str_i in str_array:
+			ret.append(float(str_i))
+		return ret
 
 	def __init__(self, obj, attr):
 		import Uml
@@ -158,10 +235,19 @@
 		super(StrArrayAttr, self).__init__(obj, attr)
 
 	def __getitem__(self,index):
-		return int(super(RealArrayAttr, self).__getitem__[index])
+		return float(super(RealArrayAttr, self).__getitem__(index))
+
 
-class BooleanArrayAttr(ArrayAttr):
 
+class BooleanArrayAttr(ArrayAttr):
+	@property
+	def array(self):
+		str_array = super(IntArrayAttr, IntArrayAttr).array.fget(self)
+		ret = []
+		for str_i in str_array:
+			ret.append(lower(str_i) == "true")
+		return ret
+	
 	def __init__(self, obj, attr):
 		import Uml
 		if attr.type != "Boolean":
@@ -169,7 +255,7 @@
 		super(StrArrayAttr, self).__init__(obj, attr)
 
 	def __getitem__(self,index):
-		value = super(RealArrayAttr, self).__getitem__[index]
+		value = super(RealArrayAttr, self).__getitem__(index)
 		return value.lower()=="true" 
 			
 		

Modified: UDM/trunk/src/Udm/PythonAPIGen/PythonAPIGen.cpp
==============================================================================
--- UDM/trunk/src/Udm/PythonAPIGen/PythonAPIGen.cpp	Mon Feb 10 01:19:52 2014	(r4252)
+++ UDM/trunk/src/Udm/PythonAPIGen/PythonAPIGen.cpp	Mon Feb 17 00:09:32 2014	(r4253)
@@ -64,15 +64,6 @@
 
   /*INITIALIZE THE META STATIC VARIABLES*/
   
-  m_output << endl;
-  m_output << "def init_meta(meta_map):" << endl;
-  
-  for( set< ::Uml::Class>::iterator uc_i = uml_classes.begin(); uc_i != uml_classes.end(); uc_i++ )
-  {
-	  ::Uml::Class currCls = *uc_i;
-	   set<Uml::Class> bases = currCls .baseTypes();
-	  m_output << "\t" << currCls.name() << ".meta = meta_map." << currCls.name() << endl;
-  }
   
     m_output << endl;
     m_output << "def init_classes(diagram):" << endl;
@@ -87,7 +78,7 @@
     {
         set< ::Uml::Attribute> attrs = uc_i->attributes();
         for( set< ::Uml::Attribute>::iterator attrs_i = attrs.begin(); attrs_i != attrs.end(); attrs_i++)
-                m_output << "\t" << uc_i->name() << ".meta_" << attrs_i->name() << " = GetUmlAttributeByName(Uml.Class(" << uc_i->name() << ".meta), \"" << attrs_i->name() << "\")"<< endl;
+                m_output << "\t" << uc_i->name() << ".meta_" << attrs_i->name() << " = GetUmlAttributeByName(" << uc_i->name() << ".Meta, \"" << attrs_i->name() << "\")"<< endl;
     }
 		
 
@@ -101,8 +92,10 @@
   m_output << "\t" << "except NameError:" << endl;
   m_output << "\t\t" << "if sys.modules[__name__] != Uml:" << endl;
   m_output << "\t\t\t" << "Uml.initialize(udm.uml_diagram())" << endl;
-  m_output << "\t\t" << "meta_map = udm.map_uml_names(diagram)" << endl;
-  m_output << "\t\t" << "init_meta(meta_map)" << endl;
+  m_output << "\t\t" << "if sys.modules[__name__] == Uml:" << endl;
+  m_output << "\t\t\t" << "meta_map = udm.map_uml_names(diagram)" << endl;
+  m_output << "\t\t\t" << "#the only meta-object needed to bootstrap" << endl;
+  m_output << "\t\t\t" << "Class.Meta = meta_map.Class" << endl;
   m_output << "\t\t" << "init_classes(Uml.Diagram(diagram))" << endl;
   m_output << "\t\t" << "init_attributes()" << endl;
   m_output << "\t\t" << "module_initialized = True" << endl;
@@ -130,6 +123,10 @@
 {
 	m_output << "class " << cls.name() << "(UdmPython):" << endl;
    	m_output << "\t\"\"\"Generated\"\"\"" << endl;
+    m_output << "\t at property" << endl;
+    m_output << "\tdef parent(self):" << endl;
+    m_output << "\t\tparent_o = super(" << cls.name() << ", self).parent" << endl;
+    m_output << "\t\treturn globals()[parent_o._type().name](parent_o) " << endl;
 
 	generateAttributes(cls);
 	
@@ -158,10 +155,20 @@
 	for ( set< ::Uml::Attribute>::iterator atts_i = atts.begin(); atts_i != atts.end(); atts_i++ )
 	{
 		string att_name = atts_i->name();
-
-		// name of the attribute
-		m_output << "\t#" << att_name << " = \"" << att_name << "\";" << endl;
-		m_output << endl;
+        if ((atts_i->max() > 1) || (atts_i->max() == -1) )
+		{
+            m_output << "\tdef " << att_name << "(self):" << endl;
+            
+            if (atts_i->type() == "String" )
+                m_output << "\t\t return StrArrayAttr(self, " << cls.name() << ".meta_" <<  atts_i->name() << ")"<< endl;
+            if (atts_i->type() == "Real" )
+                m_output << "\t\t return RealArrayAttr(self, " << cls.name() << ".meta_" <<  atts_i->name() <<")"<<  endl;
+            if (atts_i->type() == "Boolean" )
+                m_output << "\t\t return BooleanArrayAttr(self, " << cls.name() << ".meta_" <<  atts_i->name() <<")"<<  endl;
+            if (atts_i->type() == "Integer" )
+                m_output << "\t\t return IntArrayAttr(self, " << cls.name() << ".meta_" <<  atts_i->name() << ")"<< endl;
+            m_output << endl;
+        }
 	}
 }
 
@@ -203,7 +210,7 @@
 		  m_output << "\t\t at return  The children in a lisst" << endl;
 		  m_output << "\t\t\"\"\"" << endl;
 
-		  m_output << "\t\tchilds = self.impl.children(child_type=" << c_i_name << ".meta)" << endl;
+		  m_output << "\t\tchilds = self.children(child_type=" << c_i_name << ".Meta)" << endl;
 		  m_output << "\t\tlist = []" << endl;
 		  m_output << "\t\t" << "for i in childs:" << endl;
 		  m_output << "\t\t\t" << "list.append(" << c_i_name << "(i))" << endl;

Modified: UDM/trunk/src/UdmPython/UdmPython.cpp
==============================================================================
--- UDM/trunk/src/UdmPython/UdmPython.cpp	Mon Feb 10 01:19:52 2014	(r4252)
+++ UDM/trunk/src/UdmPython/UdmPython.cpp	Mon Feb 17 00:09:32 2014	(r4253)
@@ -200,6 +200,31 @@
 	throw std::runtime_error(std::string("Unsupported attribute type '") + static_cast<string>(attr.type()) + "' for class '" + static_cast<string>(self.type().name()) + "'");
 }
 
+object Object_set_attr_by_uml_attr(Udm::Object& self, Uml::Attribute attr, object value)
+{
+	if (!attr)
+		throw std::runtime_error(std::string("Uml::Attribute is null in Object_set_attr_by_uml_attr(Udm::Object& self, Uml::Attribute attr) "));
+
+    if (static_cast<string>(attr.type()) == "Integer") {
+		self.setIntegerAttr(attr, extract<__int64>(value));
+		return object();
+	}
+	if (static_cast<string>(attr.type()) == "String" || static_cast<string>(attr.type()) == "Text") {
+		self.setStringAttr(attr, stringtoutf8(value));
+		return object();
+	}
+	if (static_cast<string>(attr.type()) == "Real") {
+		self.setRealAttr(attr, extract<double>(value));
+		return object();
+	}
+	if (static_cast<string>(attr.type()) == "Boolean") {
+		self.setBooleanAttr(attr, extract<bool>(value));
+		return object();
+	}
+	throw std::runtime_error(std::string("Unsupported attribute type '") + static_cast<string>(attr.type()) + "' for class '" + static_cast<string>(self.type().name()) + "'");
+
+    
+}
 
 object Object_attr(Udm::Object& self, str _name) {
 	std::string name = extract<std::string>(_name);
@@ -220,6 +245,14 @@
 	
 } 
 
+object Object_set_attr_by_uml_attr_as_udm_object(Udm::Object& self, Udm::Object& attr, object value)
+{
+	if (!attr)
+		throw std::runtime_error(std::string("Uml::Attribute is null in Object_attr_by_uml_attr_as_udm_object(Udm::Object& self, Udm::Object&  attr) "));
+    
+	return Object_set_attr_by_uml_attr(self, Uml::Attribute::Cast(attr), value);
+	
+}
 object Object_set_attr(Udm::Object& self, str _name, object value) {
 	std::string name = extract<std::string>(_name);
 
@@ -227,23 +260,8 @@
 	if (!attr) {
 		throw std::runtime_error(std::string("Unknown attribute '") + name + "' for class '" + static_cast<string>(self.type().name()) + "'");
 	}
-	if (static_cast<string>(attr.type()) == "Integer") {
-		self.setIntegerAttr(attr, extract<__int64>(value));
-		return object();
-	}
-	if (static_cast<string>(attr.type()) == "String" || static_cast<string>(attr.type()) == "Text") {
-		self.setStringAttr(attr, stringtoutf8(value));
-		return object();
-	}
-	if (static_cast<string>(attr.type()) == "Real") {
-		self.setRealAttr(attr, extract<double>(value));
-		return object();
-	}
-	if (static_cast<string>(attr.type()) == "Boolean") {
-		self.setBooleanAttr(attr, extract<bool>(value));
-		return object();
-	}
-	throw std::runtime_error(std::string("Unsupported attribute type '") + static_cast<string>(attr.type()) + "' for class '" + static_cast<string>(self.type().name()) + "'");
+    return Object_set_attr_by_uml_attr(self, attr, value);
+
 }
 
 object Object_children(Udm::Object& self, object child_role, object parent_role, object _child_type) {
@@ -640,6 +658,7 @@
 		.def("_children", Object_children)
 		.def("_adjacent", Object_adjacent)
 		.def("get_attribute",&Object_attr_by_uml_attr_as_udm_object)
+		.def("set_attribute",&Object_set_attr_by_uml_attr_as_udm_object)
 		.def("attr", &Object_attr)
 		.def("set_attr", &Object_set_attr)
 		.def("__getattr__", &Object___getattr__)

Modified: UDM/trunk/tests/test_UdmPythonDS/test.py
==============================================================================
--- UDM/trunk/tests/test_UdmPythonDS/test.py	Mon Feb 10 01:19:52 2014	(r4252)
+++ UDM/trunk/tests/test_UdmPythonDS/test.py	Mon Feb 17 00:09:32 2014	(r4253)
@@ -76,10 +76,34 @@
 print lamp_1.ModelName
 lamp_1.ModelName = "test_python"
 print lamp_1.ModelName
-print lamp_1.meta.name
+print lamp_1.Meta.name
 
 print LampDiagram.Lamp.meta_ModelName
 print Uml.Class.meta_name
 
+o = lamp_1.ArrayStr()
+print o
+print o[2]
+o[2] = "hello python"
+print o
+print o[2]
+print lamp_1.ArrayStr()[3]
+
+print o.array
+
+o.array = ["alma", "korte", "szilva"]
+print o.array
+print len(o.array)
+print o[2]
+
+rf = lamp_1.parent
+print isinstance(rf, LampDiagram.RootFolder)
+#lamp_1.parent = rf
+
+#print lamp1.parent == rf
+
+
+
+
 dn.close_no_update()
 pdn.close_no_update()


More information about the Mobies-commit mailing list