[MOBY-guts] biomoby commit
Yan Wong
yanwong at pub.open-bio.org
Tue Jan 18 13:37:15 UTC 2005
yanwong
Tue Jan 18 08:46:22 EST 2005
Update of /home/repository/moby/moby-live/Python/bioMoby
In directory pub.open-bio.org:/tmp/cvs-serv20853
Modified Files:
__init__.py mobyClient.py mobyDataTypes.py mobyExceptions.py
mobyMarshal.py mobyRegister.py mobyService.py
Log Message:
moby-live/Python/bioMoby __init__.py,1.1,1.2 mobyClient.py,1.1,1.2 mobyDataTypes.py,1.1,1.2 mobyExceptions.py,1.1,1.2 mobyMarshal.py,1.1,1.2 mobyRegister.py,1.1,1.2 mobyService.py,1.1,1.2
===================================================================
RCS file: /home/repository/moby/moby-live/Python/bioMoby/__init__.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- /home/repository/moby/moby-live/Python/bioMoby/__init__.py 2004/12/08 11:26:01 1.1
+++ /home/repository/moby/moby-live/Python/bioMoby/__init__.py 2005/01/18 13:46:22 1.2
@@ -1,5 +1,7 @@
-#Author: Yan Wong
-#All modules are declared here
+""" bioMoby Python API
+"""
+
+#Author Yan Wong
from mobyClient import *
from mobyDataTypes import *
@@ -9,4 +11,3 @@
from mobyMarshal import *
from webservice import *
from ontology import *
-
===================================================================
RCS file: /home/repository/moby/moby-live/Python/bioMoby/mobyClient.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- /home/repository/moby/moby-live/Python/bioMoby/mobyClient.py 2004/12/08 11:26:01 1.1
+++ /home/repository/moby/moby-live/Python/bioMoby/mobyClient.py 2005/01/18 13:46:22 1.2
@@ -1,8 +1,15 @@
-#Date: 13th of April 2004
-#Author: Wong Yan
-#
-# The Client class inherits from Central class
-# It implements all necessary methods to communicate with a Moby server
+""" Classes and methods that communicate with a Moby directory
+"""
+
+"""
+ Date: 13th of April 2004
+ Author: Wong Yan
+
+ The Client class inherits from Central class
+
+"""
+
+from xml.dom.minidom import parseString
class Central:
""" Class Central describes bioMoby Server
@@ -44,7 +51,7 @@
#Remote call of the method on the Moby server
xmlt=self.call_method("retrieveObjectNames", None)
- from xml.dom.minidom import parseString
+
doc=parseString(xmlt)
for node in doc.getElementsByTagName("Object"):
@@ -55,7 +62,7 @@
for ssNode in subNode.childNodes:
if ssNode.nodeType==ssNode.CDATA_SECTION_NODE:
result[objectName]=ssNode.nodeValue
- del parseString
+
return result
def retrieveObjectDefinition(self, objectName):
@@ -68,7 +75,7 @@
definition={}
definition["Relationship"]={}
- from xml.dom.minidom import parseString
+
xmlinput="<retrieveObjectDefinition><objectType>"+objectName+"</objectType></retrieveObjectDefinition>"
doc=parseString(self.call_method("retrieveObjectDefinition", xmlinput))
@@ -82,8 +89,6 @@
elif child.nodeType==child.ELEMENT_NODE:
if child.firstChild:
definition[str(child.nodeName)]=child.firstChild.nodeValue
-
- del parseString
return definition
@@ -99,14 +104,13 @@
result=[]
xmlt=self.call_method("retrieveServiceProviders", None)
- from xml.dom.minidom import parseString
+
doc=parseString(xmlt)
for node in doc.getElementsByTagName("serviceProvider"):
serviceProviderName= node.getAttribute("name")
result.append(serviceProviderName)
- del parseString
return result
@@ -117,7 +121,6 @@
xmlt=self.call_method("retrieveNamespaces", None)
- from xml.dom.minidom import parseString
doc=parseString(xmlt)
for node in doc.getElementsByTagName("Namespace"):
@@ -127,8 +130,7 @@
for ssNode in subNode.childNodes:
if ssNode.nodeType==ssNode.CDATA_SECTION_NODE:
result[ns]=ssNode.nodeValue
-
- del parseString
+
return result
@@ -139,7 +141,6 @@
xmlt=self.call_method("retrieveServiceNames", None)
- from xml.dom.minidom import parseString
doc=parseString(xmlt)
for node in doc.getElementsByTagName("serviceName"):
@@ -147,8 +148,7 @@
authURI=node.getAttribute("authURI")
result[serviceName]=authURI
-
- del parseString
+
return result
@@ -159,7 +159,6 @@
xmlt=self.call_method("retrieveServiceTypes", None)
- from xml.dom.minidom import parseString
doc=parseString(xmlt)
for node in doc.getElementsByTagName("serviceType"):
@@ -171,7 +170,6 @@
if ssNode.nodeType==ssNode.CDATA_SECTION_NODE:
result[st]=ssNode.nodeValue
- del parseString
return result
@@ -182,13 +180,11 @@
xmlt=self.call_method("retrieveService", xmlinput)
- from xml.dom.minidom import parseString
doc=parseString(xmlt)
service=doc.firstChild
wsdl=service.firstChild.nodeValue
- del parseString
return wsdl
@@ -208,7 +204,6 @@
xmlt=self.call_method("Relationships", xmlinput)
- from xml.dom.minidom import parseString
doc=parseString(xmlt)
for node in doc.getElementsByTagName("Relationship"):
@@ -216,7 +211,6 @@
if serviceType.nodeType==serviceType.ELEMENT_NODE:
result.append(serviceType.firstChild.nodeValue)
- del parseString
return result
def retrieveDataTypesRelationships(self, dataTypeName):
@@ -235,7 +229,6 @@
xmlt=self.call_method("Relationships", xmlinput)
- from xml.dom.minidom import parseString
doc=parseString(xmlt)
for node in doc.getElementsByTagName("Relationship"):
@@ -247,7 +240,6 @@
result[relationType]=relationTypeResults
- del parseString
return result
@@ -268,4 +260,6 @@
raise ETypeMismatch
def __init__(self, url="http://mobycentral.cbr.nrc.ca/cgi-bin/MOBY05/mobycentral.pl", ns="http://mobycentral.cbr.nrc.ca/MOBY/Central"):
+ """Constructor for class Client
+ """
Central.__init__(self, url, ns)
===================================================================
RCS file: /home/repository/moby/moby-live/Python/bioMoby/mobyDataTypes.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- /home/repository/moby/moby-live/Python/bioMoby/mobyDataTypes.py 2004/12/08 11:26:01 1.1
+++ /home/repository/moby/moby-live/Python/bioMoby/mobyDataTypes.py 2005/01/18 13:46:22 1.2
@@ -1,13 +1,32 @@
-#Date: 15th of April 2004
-#Author: Wong Yan
-#Some predefined datatypes
+"""Generic bioMoby data types
+"""
-class Parameter:
+""" Date: 15th of April 2004
+ Author: Wong Yan
+ predefined data types:
+ -object
+ -secondary article (Parameter)
+ -Xref
+ -Integer
+ -Float
+ -String
+ -MobyContent
+
+ 12/13/2004: added some methods to manipulate MobyContent objects
+ 01/17/2005: serialization of public attributes for bioMoby objects
+"""
+
+__ATTRIBUTES__=['namespace', 'id', 'articleName']
+
+from xml.dom.minidom import parseString
+
+class Parameter(object):
"""This Object defines a parameter
"""
def __init__(self, articleName="", value=""):
self.articleName=articleName
self.value=value
+ self.__isSecondary__=True
def toMoby(self):
"""Returns the object as a XML
@@ -15,15 +34,18 @@
return "<moby:Parameter moby:articleName='"+self.articleName+"'><moby:value>"+str(self.value)+"</moby:value></moby:Parameter>"
def __str__(self):
+ """Return the Parameter in its XML form
+ """
return self.toMoby()
def __repr__(self):
- return "Parameter name="+self.articleName+ " value="+`self.value`
+ """Print the XML on the python command line.
+ """
+ return self.toMoby()
def fromMoby(self, xml):
"""Get the attributes from a XML string
"""
- from xml.dom.minidom import parseString
xmlelt=parseString(xml).firstChild
self.articleName=xmlelt.getAttribute('moby:articleName')
l=xmlelt.getElementsByTagName("value")
@@ -32,113 +54,178 @@
self.value=l[0].firstChild.nodeValue
- del parseString
-
-class MobyObject:
- """Class implementing a bioMoby object
+class MobyGeneric(object):
+ """A Generic object (to use with the Marshaller)
"""
-
- def __init__(self,content=None, namespace="", id="", articleName="", tag="Object"):
- self.namespace=namespace
- self.id=id
- self.content=content
- self._articleName=articleName
- self._tag=tag
- self._cross=None
- self._PIB=None
-
- def __str__(self):
- return self.toMoby()
-
- def getInfo(self,xmlNode):
- """Get the namespace and the id of the Object
- """
- from xml.dom.minidom import parseString
-
- self.namespace=xmlNode.getAttribute('moby:namespace')
- if self.namespace=="":
- self.namespace=xmlNode.getAttribute('namespace')
-
- self.id=xmlNode.getAttribute('moby:id')
- if self.id=="":
- self.id=xmlNode.getAttribute('id')
-
- self._articleName=xmlNode.getAttribute('moby:articleName')
- if self._articleName=="":
- self._articleName=xmlNode.getAttribute('articleName')
-
- del parseString
-
-
+ def __init__(self, namespace="", id="", articleName="", *args, **kw):
+ """Class constructor, basic attributes are namespace,
+ identifier and the article's name
+ """
+ self.namespace=namespace
+ self.id=id
+ self.articleName=articleName
+
+ for name, value in kw.items():
+ setattr(self, name, value)
+
+class MobyObject(MobyGeneric):
+ """Define a Moby XML Object
+ It has methods toMoby and fromMoby
+ """
+ def __init__(self, prefix="moby", tag="Object", content="", *args, **kw):
+ """Class constructor for a bioMoby Object
+ """
+ MobyGeneric.__init__(self, *args, **kw)
+ self.__prefix__=prefix
+ self.__tag__=tag
+ self.__cross__=[]
+ self.__PIB__=[]
+
+ self.content=content
+
+
def toMoby(self):
- """Returns the object as a string
- """
-
- #the Object has a content or it has several attributes
- cnt=[]
- from mobyMarshal import MobyMarshaller
- m=MobyMarshaller()
-
- for attribute in dir(self):
- if attribute[0] !='_' and attribute!='content' and attribute!='id' and attribute!='namespace' and not callable(getattr(self,attribute)):
- if "_articles" in dir(self):
- cnt.append(m.dumps(getattr(self,attribute),articleName=self._articles[attribute]))
- else:
- cnt.append(m.dumps(getattr(self,attribute), articleName=attribute))
-
- if '_cross' in dir(self) and self._cross != None:
- cnt.append('<CrossReference>')
- for ref in self._cross:
- cnt.append(m.dumps(ref))
- cnt.append('</CrossReference>')
-
- if 'content' in dir(self) and self.content!=None:
- cnt.append("<![CDATA["+str(self.content)+"]]>")
-
- del MobyMarshaller
-
- if len(cnt)==0:
- return "<moby:"+self._tag+" moby:namespace=\""+self.namespace+"\" moby:id=\""+self.id+"\" moby:articleName=\""+self._articleName+"\"/>"
-
- return "<moby:"+self._tag+" moby:namespace=\""+self.namespace+"\" moby:id=\""+self.id+"\" moby:articleName=\""+self._articleName+"\">"+"".join(cnt)+"</moby:"+self._tag+">"
-
- def fromMoby(self, xml):
- """Deserializes an object from an XML string
- """
- from xml.dom.minidom import parseString
- from bioMoby.mobyMarshal import MobyUnmarshaller
-
- xmlelt=parseString(xml).firstChild
- #retrieve Identifier and namespace
- self.getInfo(xmlelt)
-
- um=MobyUnmarshaller()
-
- #Looking for cross References
-
- cross=xmlelt.getElementsByTagName("CrossReference")
- if len(cross)>0:
- self._cross=[]
- for ref in cross[0].childNodes:
- if ref.nodeType==ref.ELEMENT_NODE:
- self._cross.append(um.loads(ref.toxml()))
-
- #Looking for a content
+ """Deserializes the content in XML api
+ """
+
+ beginTag=["<%s:%s"%(self.__prefix__,self.__tag__)]
+
+ #First see if the object has an identifier, a namepsace and a name
+ for attribute in __ATTRIBUTES__:
+ if hasattr(self, attribute) and getattr(self, attribute):
+ beginTag.append("%s:%s=\"%s\""%(self.__prefix__, attribute, getattr(self,attribute)))
+ #Retrieve only object's attributes that are public.
+ filterFunc=lambda x: x[0] != "_" and not callable(getattr(self, x)) and x !="content" and x not in __ATTRIBUTES__
+
+ #Retrieve the associated objects
+ #In MobyObject, associated objects are object's attributes
+ mobyObjects=filter(filterFunc, dir(self))
+
+ #If none, return the tag closed
+ if len(mobyObjects)==0 and (not hasattr(self, "__cross__") or len(self.__cross__)==0) and (not hasattr(self, "__PIB__") or len(self.__PIB__)==0) and (not hasattr(self, "content") or not self.content):
+ beginTag.append("/>")
+ return " ".join(beginTag)
- for elt in xmlelt.childNodes:
- if elt.nodeType==elt.TEXT_NODE or elt.nodeType==elt.CDATA_SECTION_NODE:
- if self.content==None:
- self.content=""
- self.content=self.content+elt.nodeValue
+ #Else, end begin tag and serialize the associated objects
+ beginTag.append(">")
- del parseString
+ result=[" ".join(beginTag)]
+
+ #Serialize Cross references
+ if hasattr(self, "__cross__") and self.__cross__:
+ result.append("<CrossReference>")
+
+ for aCross in self.__cross__:
+ result.append(aCross.toMoby())
+
+ result.append("</CrossReference>")
+
+ #Serialize PIB
+ if hasattr(self, "__PIB__") and self.__PIB__:
+ result.append("<ProvisionInformation>")
+
+ for aPIB in self.__PIB__:
+ result.append(aPIB.toMoby())
+
+ result.append("</ProvisionInformation>")
+
+ #Serialize the other attibutes
+ #If the attributes has a toMoby method, then use it
+ #Else, use a MobyMarshaller object to serialize
+ for mobyObject in mobyObjects:
+ if hasattr(getattr(self,mobyObject), "toMoby"):
+ getattr(self, mobyObject).__articleName__=mobyObject
+ result.append(getattr(self, mobyObject).toMoby())
+ else:
+ from bioMoby import MobyMarshaller
+ m=MobyMarshaller()
+ result.append(m.dumps(getattr(self, mobyObject), articleName=mobyObject))
+
+ #Put the raw content of the object
+ #If you want to put your special object, then then you should write
+ #a __str__ method
+ if hasattr(self, "content") and self.content:
+ result.append("%s"%(self.content))
+
+ result.append("</%s:%s>"%(self.__prefix__, self.__tag__))
+
+ return "".join(result)
+
+ def fromMoby(self, xmlstring):
+ """Deserialization method
+ """
+
+ doc=parseString(xmlstring)
+
+ elem=doc.firstChild
+
+ self.__tag__=elem.localName
+
+ self.__prefix__="moby"
+
+ self.content=[]
+
+ if elem.nodeName.split(":")>1:
+ self.__prefix__=elem.nodeName.split(":")[0]
+
+ #Set the object's attributes
+ for attribute in elem.attributes.values():
+ setattr(self, attribute.localName, str(attribute.nodeValue))
+
+ for child in elem.childNodes:
+ if child.nodeType==child.ELEMENT_NODE:
+ #deserializes the cross references
+ if child.localName=="CrossReference":
+ for aCross in child.childNodes:
+ if aCross.localName=="Xref":
+ aXref=MobyXref()
+ aXref.fromMoby(aCross.toxml())
+ self.__cross__.append(aXref)
+ if aCross.localName=="Object":
+ anObj=MobyObject()
+ anObj.fromMoby(aCross.toxml())
+ self.__cross__.append(anObj)
+ else:
+ #Do the same for the other objects
+ associatedObjectName=child.getAttribute("moby:articleName")
+
+ if not associatedObjectName:
+ associatedObjectName=child.getAttribute("articleName")
+
+ if not associatedObjectName:
+ associatedObjectName="associated"
+
+ #Create an object
+ o=MobyObject()
+ o.fromMoby(child.toxml())
+
+ #if there is already an object, then store it inside a list and
+ #append the other objects in the list
+ if hasattr(self, associatedObjectName):
+ if type(getattr(self, associatedObjectName)) is list:
+ getattr(self, associatedObjectName).append(o)
+ else:
+ setattr(self, associatedObjectName, [o])
+ else:
+ setattr(self, associatedObjectName, o)
+ else:
+ self.content.append(child.nodeValue)
+
+ self.content="".join(self.content)
+
+ def __str__(self):
+ return self.toMoby()
+
+ def __repr__(self):
+ return self.toMoby()
+
class MobyXref(MobyObject):
"""Describes an Xref
"""
- def __init__(self, namespace, id, authURI, serviceName, evidenceCode, xrefType):
+ def __init__(self, namespace="", id="", authURI="", serviceName="", evidenceCode="", xrefType=""):
MobyObject.__init__(self,namespace=namespace, id=id, tag="Xref", articleName="")
self.authURI=authURI
self.serviceName=serviceName
@@ -148,14 +235,13 @@
def toMoby(self):
"""Serialize the Xref object
"""
- return "<moby:Xref moby:namespace=\""+self.namespace+"\" moby:id=\""+self.id+"\" authURI=\""+self.authURI+"\" serviceName=\""+self.serviceName+"\" evidenceCode=\""+self.evidenceCode+"\" xrefType=\""+self.xrefType+"\"/>"
+ return "<%s:%s moby:namespace=\"%s\" moby:id=\"%s\" authURI=\"%s\" serviceName=\"%s\" evidenceCode=\"%s\" xrefType=\"%s\"/>"%(self.__prefix__, self.__tag__, self.namespace, self.id, self.authURI, self.serviceName, self.evidenceCode, self.xrefType)
def fromMoby(self, xml):
"""Deserialize the Xref Object
"""
MobyObject.fromMoby(self, xml)
- from xml.dom.minidom import parseString
doc=parseString(xml)
self.authURI=doc.firstChild.getAttribute("authURI")
@@ -163,129 +249,40 @@
self.evidenceCode=doc.firstChild.getAttribute("evidenceCode")
self.xrefType=doc.firstChild.getAttribute("xrefType")
- del parseString
-
-class MobyString(MobyObject):
- """A string as it is described in the ontology
- """
- def __init__(self, content="", namespace="", id="", articleName=""):
- MobyObject.__init__(self,content=content, namespace=namespace, id=id, tag="String", articleName=articleName)
-
-class MobyFloat(MobyObject):
- """A Float object
- """
- def __init__(self, content=0.0, namespace="", id="", articleName=""):
- MobyObject.__init__(self, content=content, namespace=namespace, id=id, articleName=articleName,tag="Float")
-
- def fromMoby(self, xml):
- """Convert an XML into a String object
- """
- self.content=""
- MobyObject.fromMoby(self, xml)
- self.content=float(self.content)
-
+
class MobyInteger(MobyObject):
- """An Integer as it is described in the ontology
+ """Use this object to serialize/deserialize integers
"""
- def __init__(self, content=0, namespace="", id="", articleName=""):
- MobyObject.__init__(self,namespace=namespace, id=id, articleName=articleName, tag="Integer")
- self.content=content
+ def __init__(self, value=0, *args, **kw):
+ MobyObject.__init__(self, content=value, tag="Integer", *args, **kw)
- def fromMoby(self, xml):
- """Convert an XML into an Integer
- """
- self.content=""
- MobyObject.fromMoby(self, xml)
- self.content=int(self.content)
-
-class MobyZmPDB(MobyObject):
- """WARNING: this class was only used as an example of how to transmit PDB files!
- It just compress the file using zlib and encode it in order to embed PDB in xml tags
+ def fromMoby(self, xmlstring):
+ MobyObject.fromMoby(self, xmlstring)
+ self.content = int(self.content)
+
+class MobyFloat(MobyObject):
+ """Serialize/deserialize floating point numbers
"""
- def __init__(self, filename="", content="", compress=None, namespace="", id="",articleName=""):
- MobyObject.__init__(self, content="", namespace=namespace, id=id,articleName=articleName, tag="ZmPDB")
- self.compress=compress
-
- if content != "":
- self.content=content
- elif filename != "":
- f=file(filename,'r')
- r=''
-
- for l in f.readlines():
- r=r+l
-
- f.close()
-
- self.content=r
-
- if compress==1:
- import zlib
- zr=zlib.compress(self.content)
-
- self.content=zr
- del zlib
-
- def toMoby(self):
- """This is the method that transforms a PDB into a moby object
- """
- if self.compress!=1:
- import zlib, base64
- res=base64.encodestring(zlib.compress(self.content))
- del zlib, base64
- return '<moby:'+self._tag+' moby:namespace="'+self.namespace+'" moby:id="'+self.id+'" moby:articleName="'+self._articleName+'">'+res+'</moby:'+self._tag+'>'
-
-
- def fromMoby(self, xml):
- """Returns a PDB from a XML String
- """
- import zlib, base64
- from xml.dom.minidom import parseString
- xmlelt=parseString(xml).firstChild
- self.getInfo(xmlelt)
- pdb=xmlelt.firstChild.nodeValue
- self.content=zlib.decompress(base64.decodestring(pdb))
- del zlib, base64, parseString
-
- def __str__(self):
- """Returns the PDB
- """
- res=self.content
- if self.compress==1:
- import zlib
- res=zlib.decompress(self.content)
- del zlib
-
- return res
+ def __init__(self, value=0, *args, **kw):
+ MobyObject.__init__(self, content=value, tag="Float", *args, **kw)
+
+ def fromMoby(self, xmlstring):
+ MobyObject.fromMoby(self, xmlstring)
+ self.content=float(self.content)
+
+class MobyString(MobyObject):
+ """String Moby object
+ """
+ def __init__(self, content="", *args, **kw):
+ MobyObject.__init__(self, content=content, *args, **kw)
+ self.__tag__="String"
- def compress(self):
- """Compress the PDB using zlib
- """
- if self.compress!=1:
- import zlib
- self.content=zlib.compress(self.content)
- del zlib
-
- def saveToFile(self, filename):
- """ Save the PDB into a file
- """
- fp=file(filename,'w')
- fp.write(self.content)
- fp.close()
-
- def loadFromFile(self, filename):
- """Load a PDB
- """
- fp=file(filename,'r')
- self.content=fp.read()
- fp.close()
-
class MobyContent:
"""The class describes a Moby Content (for queries or answers)
"""
- def __init__(self, queryData, authority="", servicenotes=""):
+ def __init__(self, queryData={}, authority="", servicenotes=""):
"""Optional parameters indicate the authority's URL and notes about the service
"""
self.authority=authority
@@ -294,6 +291,11 @@
self.queryData=queryData
def __str__(self):
+ """return the XML form of the Moby Content object
+ """
+ return self.toMoby()
+
+ def toMoby(self):
"""The XML reprentation of the content
"""
from mobyMarshal import MobyMarshaller
@@ -312,6 +314,8 @@
for queryKey in self.queryData:
result.append("<moby:mobyData moby:queryID='"+queryKey+"'>")
+ #For serialization, use the MobyMarshaller object
+
for queryObject in self.queryData[queryKey]:
#if the Collection ('CollectionName',[MobyObjects])
if queryObject.__class__ is tuple:
@@ -333,42 +337,134 @@
result.append('</moby:mobyContent></moby:MOBY>')
del MobyMarshaller
-
return "".join(result)
+ def fromMoby(self, xmlstring):
+ """fill the properties from an XML
+ """
+ from bioMoby import MobyUnmarshaller
+
+ um=MobyUnmarshaller()
+
+ self.queryData={}
+ mdl=parseString(xmlstring).getElementsByTagName('mobyData')
+
+ if not mdl:
+ mdl=parseString(xmlstring).getElementsByTagName('moby:mobyData')
+
+ #For each query
+ for elt in mdl:
+ #Get the ID
+ queryID=str(elt.getAttribute('queryID'))
+
+ if not queryID:
+ queryID=str(elt.getAttribute('moby:queryID'))
+
+ #Collect the data
+ data=[]
+
+ #for each datum translate it in MobyObject, and put it in the list
+ for datum in elt.childNodes:
+ #If it is a collection
+ if datum.nodeType==datum.ELEMENT_NODE and datum.localName=="Collection":
+ articleName=datum.getAttribute('moby:articleName')
+
+ articles=[]
+
+ for article in datum.childNodes:
+ if article.nodeType==article.ELEMENT_NODE and article.localName=="Simple":
+ for child in article.childNodes:
+ if child.nodeType==child.ELEMENT_NODE:
+ articles.append(um.loads(child.toxml()))
+
+ data.append((articleName, articles))
+ #if it is a Simple object
+ elif datum.nodeType==datum.ELEMENT_NODE and datum.localName=="Simple":
+ for elt in datum.childNodes:
+ if elt.nodeType==elt.ELEMENT_NODE:
+ o=um.loads(elt.toxml())
+ data.append(o)
+ elif datum.nodeType==datum.ELEMENT_NODE and datum.localName=="Parameter":
+ #It is a Parameter
+ p=Parameter()
+ p.fromMoby(datum.toxml())
+ data.append(p)
+
+ self.queryData[queryID]=data
+
def __getitem__(self, key):
+ """Get a query from his name
+ """
return self.queryData[key]
def __setitem__(self, key, item):
+ """Store a query in the dictionary
+ """
self.queryData[key]=item
def __len__(self):
+ """Return the number of elements inside the dictionary
+ """
return len(self.queryData)
def keys(self):
+ """Return all queries's name
+ """
return self.queryData.keys()
+
+ def collectionToQueries(self, aCollection):
+ """Turn a collection of object into a set of queries
+ """
+ queries={}
+ queryName=aCollection[0]
+
+ queryID=1
+
+ for aSimple in aCollection[1]:
+ queries["%s-%s"%(queryName, queryID)]=aSimple
+
+ return queries
+
+
+ def getObject(self, queryName, objectName):
+ """Get an object from a query with its name
+ """
+ filterfunc=lambda obj: not hasattr(obj,'__isSecondary__') and hasattr(obj, "articleName") and obj.articleName==objectName
+
+ for obj in filter(filterfunc, self.queryData[queryName]):
+ return obj
-class MobySequence(MobyObject):
- """An example of sequence as described in the API
- """
- def __init__(self, sequence="", namespace="", id="", articleName=""):
- MobyObject.__init__(self, namespace=namespace, id=id, articleName=articleName, tag="Sequence")
- self.length=len(sequence)
- self.sequence=sequence
-
- def fromMoby(self, xml):
- from xml.dom.minidom import parseString
-
- xmlelt=parseString(xml).firstChild
- self.getInfo(xmlelt)
- #first object should be Integer, second sequence
- for elt in xmlelt.childNodes:
- if elt.nodeName=='String' or elt.nodeName=='moby:String' and elt.firstChild!=None and elt.firstChild.nodeValue!=None:
- self.sequence=elt.firstChild.nodeValue
-
- if elt.nodeName=='Integer' or elt.nodeName=='moby:Integer':
- self.length=int(elt.firstChild.nodeValue)
-
-
- del parseString
\ No newline at end of file
+
+ def getObjects(self, queryName):
+ """Retrieve objects from a query
+ """
+ filterfunc=lambda obj: not hasattr(obj, "__isSecondary__")
+
+ return filter(filterfunc, self.queryData[queryName])
+
+ def getParameters(self, queryName):
+ """Retrieve parameters from a query
+ """
+ filterfunc=lambda param: hasattr(param, "__isSecondary__")
+
+ result={}
+ for param in filter(filterfunc, self.queryData[queryName]):
+ result[param.articleName]=param.value
+
+ return result
+
+ def getParameter(self, queryName, parameterName):
+ """Retrieve a parameter from a query and his name
+ """
+ filterfunc=lambda param: hasattr(param, "__isSecondary__") and hasattr(param, "articleName") and param.articleName==parameterName
+
+ l=filter(filterfunc, self.queryData[queryName])
+
+ if l:
+ return l[0]
+
+ def __repr__(self):
+ """put the xml of the Content
+ """
+ return self.__str__()
===================================================================
RCS file: /home/repository/moby/moby-live/Python/bioMoby/mobyExceptions.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- /home/repository/moby/moby-live/Python/bioMoby/mobyExceptions.py 2004/12/08 11:26:02 1.1
+++ /home/repository/moby/moby-live/Python/bioMoby/mobyExceptions.py 2005/01/18 13:46:22 1.2
@@ -1,25 +1,44 @@
-#Date: 15th of April 2004
-#Author: Wong Yan
-#
-#
+"""bioMoby exceptions
+"""
+
+"""Date: 15th of April 2004
+ Author: Wong Yan
+
+ bioMoby exceptions
+"""
class ETypeMismatch(Exception):
+ """Input type is not good
+ """
def __str__(self):
return "Type Mismatch"
-#the method doesn't exist in the web service
class ENotAWSMethod(Exception):
+ """the method doesn't exist in the web service
+ """
def __str__(self):
return "Method is not a member of the web service"
class EMethodRetrieveError(Exception):
+ """Cannot retrieve method list from a wrong WSDL
+ """
def __str__(self):
return "Cannot retrieve method list from a wrong WSDL"
class EInvalidArgument(Exception):
+ """A parameter is not good
+ """
def __str__(self):
return "Invalid argument"
class EInvalidType(Exception):
+ """Object must have a toMoby() method in order to be used as a moby XML object
+ """
def __str__(self):
return "Object must have a toMoby() method in order to be used as a moby XML object"
+
+class EInvalidMobyXML(Exception):
+ """A XML input is not a Moby XML Object.
+ """
+ def __str__(self):
+ return "The bioMoby XML object couldn't be parsed"
\ No newline at end of file
===================================================================
RCS file: /home/repository/moby/moby-live/Python/bioMoby/mobyMarshal.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- /home/repository/moby/moby-live/Python/bioMoby/mobyMarshal.py 2004/12/08 11:26:02 1.1
+++ /home/repository/moby/moby-live/Python/bioMoby/mobyMarshal.py 2005/01/18 13:46:22 1.2
@@ -1,11 +1,20 @@
-#Date 19th of May 2004
-#Author: Wong Yan
-#Topic: Marshalling moby Objects
-#Note: the Unmarshaller object works only well with bioMoby Objects
-#In case the object is not recognized, it uses the Generic marshaller to do the job
-#changed some part of the code: if x in dir(y) --> if hasattr(y, x)
+"""Serialisation/deserialisation of Python objects into bioMoby XML
+"""
+""" Date 19th of May 2004
+
+ Author: Wong Yan
+ Topic: Marshalling moby Objects
+ Note: The Unmarshaller object works only well with bioMoby Objects
+
+ 01/17/2005: MobyMarshaller and MobyUnmarshaller can operate on all objects
+ serialisation and deserialisation are done only on public (no _ prefix) non callable attributes
+ The serialisation and deserialisation is recursive.
+"""
+
+from xml.dom.minidom import parseString
+
class MobyMarshaller:
"""Transforms a Moby Object into XML
"""
@@ -15,34 +24,18 @@
"""
if type(value).__name__=='NoneType':
return ""
- try:
- tvalue=type(value).__name__
- if type(value).__name__=='instance':
- tvalue=str(value.__class__).split('.')
- tvalue=tvalue[len(tvalue)-1]
-
- if hasattr(value, 'toMoby'):
- return getattr(value,'toMoby')()
-
- method="m_"+tvalue
+ tvalue=type(value).__name__
- """Serialize the components
-
- """
+ method="m_"+tvalue
-
- if hasattr(self, method):
- return getattr(self,method)(value,articleName=articleName)
-
- return self._compoundObject(value, tvalue[0].lower()+tvalue[-len(tvalue)+1:])
- except:
- #When everything fails, we use a generic Marshaller
- from xml.marshal import generic
- marshaller=generic.Marshaller()
- r=marshaller.dumps(value)
- del generic
- return r
+ if hasattr(value, "toMoby"):
+ return value.toMoby()
+
+ if hasattr(self, method):
+ return getattr(self,method)(value,articleName=articleName)
+
+ return self._compoundObject(value, articleName=articleName)
def m_str(self, value, articleName=""):
@@ -53,32 +46,38 @@
return str(m)
def m_unicode(self, value, articleName=""):
+ """Turn a unicode string into a mobyString object
+ """
return self.m_str(str(value), articleName)
def m_string(self, value, articleName=""):
- """Return a string as itself"""
+ """Return a string object into a mobyString object
+ """
return self.m_str(value, articleName)
def m_int(self, value, namespace="", id="", articleName=""):
"""Turn an integer into a Moby XML object
"""
- return "<moby:Integer moby:namespace=\""+namespace+"\" moby:id=\""+id+"\" moby:articleName=\""+articleName+"\">"+str(value)+"</moby:Integer>"
-
+ from bioMoby.mobyDataTypes import MobyInteger
+ m=MobyInteger(value, namespace=namespace, id=id, articleName=articleName)
+
+ return m.toMoby()
+
def m_float(self, value, namespace="", id="", articleName=""):
"""Turn a float into a Moby XML object
"""
- return "<moby:Float moby:namespace=\""+namespace+"\" moby:id=\""+id+"\" moby:articleName=\""+articleName+"\">"+str(value)+"</moby:Float>"
-
- def m_list(self, value, namespace="",articleName=""):
+ from bioMoby.mobyDataTypes import MobyFloat
+ m=MobyFloat(value, namespace=namespace, id=id, articleName=articleName)
+
+ return m.toMoby()
+
+ def m_list(self, value, articleName=""):
"""Turn a list into a Moby XML object
"""
- result=['<moby:Collection namespace=\"'+namespace+'\">']
+ result=[]
for elt in value:
- result.append(self._marshal(elt))
-
- result.append('</moby:Collection>')
-
+ result.append(self._marshal(elt, articleName))
return "".join(result)
@@ -87,7 +86,7 @@
"""Turn a dictionary into a Moby Object
"""
- result=['<moby:Dict moby:namespace=\"'+namespace+'\">']
+ result=['<moby:Dict moby:namespace=\"'+namespace+'\" moby:articleName=\"'+articleName+'\">']
for key in value.keys():
result.append('<moby:Key moby:id=\"'+key+'\">')
@@ -102,46 +101,59 @@
def m_tuple(self, value, namespace="", articleName=""):
"""Define a tuple as a Moby Object
"""
- result=['<moby:Tuple moby:namespace=\"'+namespace+'\">']
+ result=['<moby:Tuple moby:namespace=\"'+namespace+'\" moby:articleName=\"'+articleName+'\">']
for val in value:
- result.append('<moby:Element>')
result.append(self._marshal(val))
- result.append('</moby:Element>')
result.append('</moby:Tuple>')
return "".join(result)
- def _compoundObject(self, value, tag, articleName=""):
+ def _compoundObject(self, value, articleName=""):
"""transforms an object and all properties into a XML
"""
- tnamespace=""
- tid=""
- tarticleName=""
-
- if hasattr(value, 'namespace'):
- tnamespace=value.namespace
- if hasattr(value, 'id'):
- tid=value.id
- if hasattr(value, '_articleName'):
- tarticleName=value._articleName
-
- t=tag
+
+ result=[]
+
+ properties=[]
+
+ filterfunc=lambda x: x[0] != "_" and not callable(getattr(value, x)) and x !="content" and x not in ["id", "namespace", "articleName", "content"]
+ attribfunc= lambda x: hasattr(value, x)
+
+ tagName="moby:%s"%type(value).__name__
+
+ if hasattr(value, "__tag__") and value.__tag__:
+ tagName="moby:%s"%value.__tag__
+
+ header=["<%s"%tagName]
+
+ for attribute in filter(attribfunc, ["id", "namespace", "articleName"]):
+ header.append("moby:%s=\"%s\""%(attribute,getattr(value,attribute)))
+
+ for prop in filter(filterfunc, dir(value)):
+ properties.append(self._marshal(getattr(value, prop), articleName=prop))
+
+ if not properties and not (hasattr(value, "content") and value.content):
+ header.append("/>")
+ else:
+ header.append(">")
+
+ result.append(" ".join(header))
- if len(tag)>4 and str.upper(tag[0:4])=='MOBY':
- t=tag[4:]
-
- result=['<moby:'+t+' moby:namespace="'+tnamespace+'" moby:id="'+tid+'" moby:articleName="'+tarticleName+'">']
-
- for prop in dir(value):
- if (not callable(prop)) and prop[0]!='_' and prop!='namespace' and prop!='id':
- result.append(self._marshal(getattr(value,prop)))
+ if properties:
+ result.append("".join(properties))
+
+ if hasattr(value, "content") and value.content:
+ result.append("<![CDATA[%s]]>"%value.content)
+
+ if properties:
+ result.append("</%s>"%tagName)
- result.append('</moby:'+t+'>')
- return "".join(result)
-
+ return r"".join(result)
+
+
def dumps(self, value, articleName=""):
"""Serialize the object into a Moby XML object
"""
@@ -157,12 +169,13 @@
"""
import re
+ aName=str(aName)
+
if aName=="":
return ""
if aName=="namespace" or aName=="id" or aName=='content':
- return aName
-
+ return aName
r=re.compile("\W")
@@ -182,136 +195,152 @@
if xml=="":
return None
- from xml.dom.minidom import parseString
+# _typesmodule=["bioMoby.mobyDataTypes", "bioMoby.ontology"]
+
+ import bioMoby.mobyDataTypes
+ import bioMoby.ontology
doc=parseString(xml)
- mcl=doc.getElementsByTagName('moby:mobyContent')
+ mcl=doc.getElementsByTagNameNS('http://www.biomoby.org/moby','mobyContent')
if len(mcl)!=0:
- return self.m_MobyContent(mcl[0].toxml())
+ return self.m_MobyContent(doc)
element=doc.firstChild
- #moby:Object or Object
- nn=element.nodeName.split(':')
-
- #if name is object or Object then name is Object 1st letter in capital letter
- object2build=self._cleanName(str(nn[len(nn)-1]))
- if object2build !='Parameter':
- object2build='Moby'+str.upper(object2build[0])+object2build[1:]
-
- methodName=str('m_'+nn[len(nn)-1])
-
-
- #See if the object has its own converter
- try:
- #Instanciate the objects
- import bioMoby
- if hasattr(bioMoby.mobyDataTypes, object2build):
- o=eval('bioMoby.mobyDataTypes.'+object2build+'()')
- elif hasattr(bioMoby.ontology, object2build):
- o=eval('bioMoby.ontology.'+object2build+'()')
-
- #Fill properties witl the xml
- getattr(o,'fromMoby')(element.toxml())
- return o
-
- except:
- pass
-
- del parseString
-
- #if it doesn't work try ones contained in the Unmarshaller class
- if hasattr(self, methodName):
- return getattr(self,methodName)(element.toxml())
- #if not, just return the string :-(
-
- return xml
+ nn=element.localName
+
+ #Try to see if this object got a deserializer
+ object2build=self._cleanName(nn)
+
+ objectName=str.upper(object2build[0])+object2build[1:]
+
+ if hasattr(bioMoby.mobyDataTypes, "Moby%s"%objectName):
+ o=getattr(bioMoby.mobyDataTypes, "Moby%s"%objectName)()
+ if hasattr(o, "fromMoby"):
+ o.fromMoby(xml)
+ return o
+ elif hasattr(bioMoby.ontology, "Moby%s"%objectName):
+ o=getattr(bioMoby.ontology, "Moby%s"%objectName)()
+ if hasattr(o, "fromMoby"):
+ o.fromMoby(xml)
+ return o
+
+ methodName=str('m_'+nn)
+
+ if not hasattr(self, methodName):
+ methodName="m_Object"
+
+# try:
+ return getattr(self,methodName)(element)
+# except:
+# #if not, Raise an invalid moby XML :-(
+# from bioMoby.mobyExceptions import EInvalidMobyXML
+
+# raise EInvalidMobyXML
def m_Integer(self, value):
- """Return an Integer from an XML, warning, you'll lose information about namespace and ID!
- """
- from xml.dom.minidom import parseString
- xmlElt=parseString(value).firstChild
- res=int(xmlElt.firstChild.nodeValue)
- del parseString
- return res
-
+ """Turn a Integer XML element into an integer
+ """
+ value.normalize()
+
+ if value.firstChild:
+ return int(value.firstChild.nodeValue.replace("\n","").replace("\t","").replace(" ",""))
+ else:
+ return 0
+
def m_Float(self, value):
- """Return a float from an XML, warning, you'll lose information about namespace and ID!
- """
- from xml.dom.minidom import parseString
- xmlElt=parseString(value).firstChild
- res=float(xmlElt.firstChild.nodeValue)
- del parseString
- return res
-
- def m_generic(self, value):
- """If it is unkwown in our mobyDataTypes, then return a generic Object
- """
- from xml.marshal.generic import Unmarshaller
- res=Unmarshaller().loads(value)
- del Unmarshaller
- return res
-
- def m_Simple(self, value):
- """If it is a "Simple" tag, then return the child object
- """
- from xml.dom.minidom import parseString
- doc=parseString(value).firstChild
-
- res=""
- for elt in doc.childNodes:
- if elt.nodeType==elt.ELEMENT_NODE:
- res=self.loads(elt.toxml())
-
- del parseString
- return res
+ """Turn a Float XML element into a float number
+ """
+ value.normalize()
+ if value.firstChild:
+ return float(value.firstChild.nodeValue.replace("\n","").replace("\t","").replace(" ",""))
+ return 0.0
+
+ def m_String(self, value):
+ """Turn a Moby XML String element into a String object
+ """
+
+ cnt=[]
+ value.normalize()
+
+ for aChild in value.childNodes:
+ if aChild.nodeType==aChild.TEXT_NODE or aChild.nodeType==aChild.CDATA_SECTION_NODE:
+ cnt.append(aChild.wholeText)
+
+ return r"".join(cnt)
+
- def m_Collection(self, value):
- """If it is a Collection then get the articleName and the data
- """
-
- from xml.dom.minidom import parseString
+ def m_Object(self, value):
+ """Turn any XML into a generic object
+ """
+ filterFunc= lambda x: x.nodeType==x.ELEMENT_NODE
+
+ typeName="GMoby%s"%str(value.localName)
+
+ from bioMoby.mobyDataTypes import MobyGeneric
+
+ NewType=type(typeName, (MobyGeneric,), {})
+
+ anObject=NewType()
+
+ anObject.__prefix__="moby"
+ anObject.__tag__=str(value.localName)
+
+ for tupleAttribute in value.attributes.itemsNS():
+ #First item, second field:
+ setattr(anObject, str(tupleAttribute[0][1]), str(tupleAttribute[1]))
+
+ i=0
+ for elem in filter(filterFunc, value.childNodes):
+ methodName="m_%s"%str(elem.localName)
- node=parseString(value).firstChild
- articleName=node.getAttribute('moby:articleName')
-
- articles=[]
-
- for article in node.childNodes:
- if article.nodeType==article.ELEMENT_NODE:
- articles.append(MobyUnmarshaller().loads(article.toxml()))
+ articleName=elem.getAttribute("moby:articleName")
+
+ if not articleName:
+ articleName=elem.getAttribute("articleName")
+
+ if not articleName:
+ articleName="attribute_%s"%i
+
+ if hasattr(self, methodName):
+ prop=getattr(self, methodName)(elem)
+ else:
+ prop=self.m_Object(elem)
+
+ if hasattr(anObject, articleName):
+ t=prop
+ if not type(getattr(anObject, articleName)) is list:
+ t=getattr(anObject, articleName)
+ setattr(anObject, articleName, [])
+ getattr(anObject, articleName).append(t)
+ else:
+ setattr(anObject, articleName, prop)
+ i+=1
+
+ content=[]
+
+ isContentNode= lambda x: x.nodeType==x.TEXT_NODE or x.nodeType==x.CDATA_SECTION_NODE
+
+ for elem in filter(isContentNode, value.childNodes):
+ content.append(str(elem.nodeValue))
+
+ if content:
+ anObject.content(r"".join(content))
+
+ return anObject
- del parseString
- return (articleName, articles)
-
def m_MobyContent(self, value):
- """return a mobyContent object from an XML
- """
- from xml.dom.minidom import parseString
- doc=parseString(value)
- queries={}
- mdl=doc.getElementsByTagName('moby:mobyData')
-
- #For each query
- for elt in mdl:
- #Get the ID
- queryID=str(elt.getAttribute('moby:queryID'))
- #Collect the data
- data=[]
- #for each datum translate it in MobyObject, and put it in the list
- for datum in elt.childNodes:
- if datum.nodeType==datum.ELEMENT_NODE:
- u=MobyUnmarshaller()
- data.append(u.loads(datum.toxml()))
-
- queries[queryID]=data
-
- from bioMoby.mobyDataTypes import MobyContent
-
- res=MobyContent(queries)
-
- del parseString, MobyContent
- return res
+ """Turn an MobyContentXML into a MobyContent object
+ """
+ from bioMoby.mobyDataTypes import MobyContent
+
+ mc=MobyContent({})
+
+ mc.fromMoby(value.toxml())
+
+ del MobyContent
+
+ return mc
+
===================================================================
RCS file: /home/repository/moby/moby-live/Python/bioMoby/mobyRegister.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- /home/repository/moby/moby-live/Python/bioMoby/mobyRegister.py 2004/12/08 11:26:02 1.1
+++ /home/repository/moby/moby-live/Python/bioMoby/mobyRegister.py 2005/01/18 13:46:22 1.2
@@ -1,7 +1,13 @@
-#Date: 16th of April 2004
-#Author: Wong Yan
-#Nom du fichier: MobyRegister
-#
+"""Classes for registration of object's classes, service's type, namespaces
+"""
+
+""" Date: 16th of April 2004
+ Author: Wong Yan
+
+
+"""
+
+from xml.dom.minidom import parseString
class RegistrationObject:
"""A registration object
@@ -16,7 +22,6 @@
self.RDF=""
#Parse the document, retrieve the success, id, message and RDF fields
- from xml.dom.minidom import parseString
doc=parseString(xmlInput)
if len(doc.getElementsByTagName("success")[0].childNodes)>0:
@@ -31,8 +36,6 @@
except:
pass
- del parseString
-
def __str__(self):
"""Return the moby xml of the instance
"""
@@ -110,13 +113,13 @@
class ObjectClass(GeneralInformations):
"""An object's class
- relationships are described as a set of tuple [ ('ISA|HAS|HASA', 'name', 'TYPE'), ...]
+ relationships are described as a set of tuple [ ('ISA|HAS|HASA', {'name': 'TYPE'}), ...]
"""
def __init__(self, contactEmail="", authURI="", description="", objectType="", relationships=None):
GeneralInformations.__init__(self, contact=contactEmail, authURI=authURI, description=description)
self.objectType=objectType
- self.relationShips=relationships
+ self.relationships=relationships
def __str__(self):
"""Return the xml of the instance
@@ -124,7 +127,7 @@
result=["<objectType>"+self.objectType+"</objectType>"]
result.append("<Description><![CDATA["+self.description+"]]></Description>")
- for relationship in self.relationShips:
+ for relationship in self.relationships:
result.append('<Relationship relationshipType="'+relationship[0]+'">')
for objectTypeKey in relationship[1].keys():
===================================================================
RCS file: /home/repository/moby/moby-live/Python/bioMoby/mobyService.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- /home/repository/moby/moby-live/Python/bioMoby/mobyService.py 2004/12/08 11:26:02 1.1
+++ /home/repository/moby/moby-live/Python/bioMoby/mobyService.py 2005/01/18 13:46:22 1.2
@@ -1,8 +1,16 @@
-#Date: 15th of April 2004
-#Author: Wong Yan
-#
+""" Classes that describes a services and its articles and parameters,
+ the Service class can be used for registration or execution.
+"""
+
+""" Date: 15th of April 2004
+ Author: Wong Yan
+
+ 01/17/2004: Service can be executed as a Thread, thus several queries can be made
+ in the same time.
+"""
from mobyRegister import GeneralInformations
+from xml.dom.minidom import parseString
class ServiceArticle:
"""In a service query, it represents an article
@@ -33,7 +41,6 @@
def fromXML(self, xml):
"""Return an article from a xml node
"""
- from xml.dom.minidom import parseString
node=parseString(xml)
self.name=node.getAttribute("articleName")
@@ -43,8 +50,6 @@
elif otns.nodeName=="Namespace":
self.namespaces.append(otns.firstChild.nodeValue)
- del parseString
-
class ServiceSecondary:
"""The class represents a parameter for the Service Query Object
"""
@@ -90,7 +95,6 @@
"""Return a parameter from a xml
"""
- from xml.dom.minidom import parseString
node=parseString(xml)
self.enums=[]
@@ -108,8 +112,6 @@
elif childNode.nodeName=="enum":
self.enums.append(childNode.firstChild.nodeValue)
- del parseString
-
class ServiceQuery:
"""Solely used in the findService
should help us to manage list of services
@@ -287,7 +289,6 @@
def getMethods(self, wsdl):
"""Retrieve the methods from the wsdl
"""
- from xml.dom.minidom import parseString
self.methods=[]
doc=parseString(wsdl)
@@ -303,8 +304,6 @@
for name in doc.getElementsByTagName("service"):
self.name=name.getAttribute("name")
- del parseString
-
def execute(self, query, method="", returnXml=True, debug=False):
"""Executes the web service
v0.5: return either the XML form or try to unmarshall the result and return a MobyContent Object
@@ -339,16 +338,14 @@
return result
#try to return a MobyContent Object instead
- from bioMoby import MobyUnmarshaller
- um=MobyUnmarshaller()
-
- result=um.loads(result)
+ from bioMoby.mobyDataTypes import MobyContent
+ mc=MobyContent()
+ mc.fromMoby(result)
- del MobyUnmarshaller
+ del MobyContent
-
- return result
-
+ return mc
+
def __str__(self):
"""Returns The moby xml form of the web service
"""
@@ -432,7 +429,34 @@
result=RegistrationObject(self.central.call_method("deregisterService", xmlinput))
del RegistrationObject
return result
-
+
+ def _executeThread(self, mobyContent):
+ """Execute the service, store the result in a field
+ """
+
+ self.results=self.execute(mobyContent, returnXml=(mobyContent.__class__ is str))
+
+
+ def start(self, mobycontent, timeout=-1):
+ """Start the service as it was a thread
+ """
+ from threading import Thread
+
+
+ if timeout != -1:
+ self._execThread=Thread(target=self._executeThread, args=(mobycontent,))
+ else:
+ self._execThread=Thread(target=self._executeThread, args=(mobycontent,), timeout=timeout)
+
+ self._execThread.start()
+
+ def join(self):
+ """Same as Thread.join
+ """
+ self._execThread.join()
+
+
+
class ServiceList:
"""Class representing a service's list
"""
@@ -443,8 +467,6 @@
simpleArticle=ServiceArticle(name='',type='',namespaces=[])
- from xml.dom.minidom import parseString
-
simpleArticle.name=node.getAttribute("articleName")
for otns in node.childNodes:
if otns.nodeName=="objectType":
@@ -452,15 +474,11 @@
elif otns.nodeName=="Namespace":
simpleArticle.namespaces.append(otns.firstChild.nodeValue)
- del parseString
-
return simpleArticle
def toCollection(self, node):
"""Return a collection of articles
"""
- from xml.dom.minidom import parseString
-
collection=[]
result={}
collectionName=node.getAttribute("articleName")
@@ -470,8 +488,6 @@
result[collectionName]=collection
- del parseString
-
return result
@@ -482,8 +498,6 @@
secondary.enums=[]
- from xml.dom.minidom import parseString
-
secondary.name=node.getAttribute("articleName")
for childNode in node.childNodes:
@@ -503,8 +517,6 @@
if childNode.firstChild:
secondary.enums.append(childNode.firstChild.nodeValue)
- del parseString
-
return secondary
def __init__(self, xmlt):
@@ -512,8 +524,6 @@
"""
self.list=[]
- from xml.dom.minidom import parseString
-
doc=parseString(xmlt)
#for each service
for node in doc.getElementsByTagName("Service"):
@@ -558,8 +568,6 @@
self.list.append(service)
- del parseString
-
def getServiceByName(self, nameOfService):
"""Get a service by name
"""
More information about the MOBY-guts
mailing list