PageRenderTime 451ms CodeModel.GetById 437ms RepoModel.GetById 0ms app.codeStats 0ms

/indra/lib/python/indra/ipc/xml_rpc.py

https://bitbucket.org/lindenlab/viewer-beta/
Python | 273 lines | 264 code | 0 blank | 9 comment | 0 complexity | a1f9cb481b3c9dd01a6b2fc2f03969ad MD5 | raw file
Possible License(s): LGPL-2.1
  1. """\
  2. @file xml_rpc.py
  3. @brief An implementation of a parser/generator for the XML-RPC xml format.
  4. $LicenseInfo:firstyear=2006&license=mit$
  5. Copyright (c) 2006-2009, Linden Research, Inc.
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. $/LicenseInfo$
  22. """
  23. from greenlet import greenlet
  24. from mulib import mu
  25. from xml.sax import handler
  26. from xml.sax import parseString
  27. # States
  28. class Expected(object):
  29. def __init__(self, tag):
  30. self.tag = tag
  31. def __getattr__(self, name):
  32. return type(self)(name)
  33. def __repr__(self):
  34. return '%s(%r)' % (
  35. type(self).__name__, self.tag)
  36. class START(Expected):
  37. pass
  38. class END(Expected):
  39. pass
  40. class STR(object):
  41. tag = ''
  42. START = START('')
  43. END = END('')
  44. class Malformed(Exception):
  45. pass
  46. class XMLParser(handler.ContentHandler):
  47. def __init__(self, state_machine, next_states):
  48. handler.ContentHandler.__init__(self)
  49. self.state_machine = state_machine
  50. if not isinstance(next_states, tuple):
  51. next_states = (next_states, )
  52. self.next_states = next_states
  53. self._character_buffer = ''
  54. def assertState(self, state, name, *rest):
  55. if not isinstance(self.next_states, tuple):
  56. self.next_states = (self.next_states, )
  57. for next in self.next_states:
  58. if type(state) == type(next):
  59. if next.tag and next.tag != name:
  60. raise Malformed(
  61. "Expected %s, got %s %s %s" % (
  62. next, state, name, rest))
  63. break
  64. else:
  65. raise Malformed(
  66. "Expected %s, got %s %s %s" % (
  67. self.next_states, state, name, rest))
  68. def startElement(self, name, attrs):
  69. self.assertState(START, name.lower(), attrs)
  70. self.next_states = self.state_machine.switch(START, (name.lower(), dict(attrs)))
  71. def endElement(self, name):
  72. if self._character_buffer.strip():
  73. characters = self._character_buffer.strip()
  74. self._character_buffer = ''
  75. self.assertState(STR, characters)
  76. self.next_states = self.state_machine.switch(characters)
  77. self.assertState(END, name.lower())
  78. self.next_states = self.state_machine.switch(END, name.lower())
  79. def error(self, exc):
  80. self.bozo = 1
  81. self.exc = exc
  82. def fatalError(self, exc):
  83. self.error(exc)
  84. raise exc
  85. def characters(self, characters):
  86. self._character_buffer += characters
  87. def parse(what):
  88. child = greenlet(xml_rpc)
  89. me = greenlet.getcurrent()
  90. startup_states = child.switch(me)
  91. parser = XMLParser(child, startup_states)
  92. try:
  93. parseString(what, parser)
  94. except Malformed:
  95. print what
  96. raise
  97. return child.switch()
  98. def xml_rpc(yielder):
  99. yielder.switch(START.methodcall)
  100. yielder.switch(START.methodname)
  101. methodName = yielder.switch(STR)
  102. yielder.switch(END.methodname)
  103. yielder.switch(START.params)
  104. root = None
  105. params = []
  106. while True:
  107. state, _ = yielder.switch(START.param, END.params)
  108. if state == END:
  109. break
  110. yielder.switch(START.value)
  111. params.append(
  112. handle(yielder))
  113. yielder.switch(END.value)
  114. yielder.switch(END.param)
  115. yielder.switch(END.methodcall)
  116. ## Resume parse
  117. yielder.switch()
  118. ## Return result to parse
  119. return methodName.strip(), params
  120. def handle(yielder):
  121. _, (tag, attrs) = yielder.switch(START)
  122. if tag in ['int', 'i4']:
  123. result = int(yielder.switch(STR))
  124. elif tag == 'boolean':
  125. result = bool(int(yielder.switch(STR)))
  126. elif tag == 'string':
  127. result = yielder.switch(STR)
  128. elif tag == 'double':
  129. result = float(yielder.switch(STR))
  130. elif tag == 'datetime.iso8601':
  131. result = yielder.switch(STR)
  132. elif tag == 'base64':
  133. result = base64.b64decode(yielder.switch(STR))
  134. elif tag == 'struct':
  135. result = {}
  136. while True:
  137. state, _ = yielder.switch(START.member, END.struct)
  138. if state == END:
  139. break
  140. yielder.switch(START.name)
  141. key = yielder.switch(STR)
  142. yielder.switch(END.name)
  143. yielder.switch(START.value)
  144. result[key] = handle(yielder)
  145. yielder.switch(END.value)
  146. yielder.switch(END.member)
  147. ## We already handled </struct> above, don't want to handle it below
  148. return result
  149. elif tag == 'array':
  150. result = []
  151. yielder.switch(START.data)
  152. while True:
  153. state, _ = yielder.switch(START.value, END.data)
  154. if state == END:
  155. break
  156. result.append(handle(yielder))
  157. yielder.switch(END.value)
  158. yielder.switch(getattr(END, tag))
  159. return result
  160. VALUE = mu.tag_factory('value')
  161. BOOLEAN = mu.tag_factory('boolean')
  162. INT = mu.tag_factory('int')
  163. STRUCT = mu.tag_factory('struct')
  164. MEMBER = mu.tag_factory('member')
  165. NAME = mu.tag_factory('name')
  166. ARRAY = mu.tag_factory('array')
  167. DATA = mu.tag_factory('data')
  168. STRING = mu.tag_factory('string')
  169. DOUBLE = mu.tag_factory('double')
  170. METHODRESPONSE = mu.tag_factory('methodResponse')
  171. PARAMS = mu.tag_factory('params')
  172. PARAM = mu.tag_factory('param')
  173. mu.inline_elements['string'] = True
  174. mu.inline_elements['boolean'] = True
  175. mu.inline_elements['name'] = True
  176. def _generate(something):
  177. if isinstance(something, dict):
  178. result = STRUCT()
  179. for key, value in something.items():
  180. result[
  181. MEMBER[
  182. NAME[key], _generate(value)]]
  183. return VALUE[result]
  184. elif isinstance(something, list):
  185. result = DATA()
  186. for item in something:
  187. result[_generate(item)]
  188. return VALUE[ARRAY[[result]]]
  189. elif isinstance(something, basestring):
  190. return VALUE[STRING[something]]
  191. elif isinstance(something, bool):
  192. if something:
  193. return VALUE[BOOLEAN['1']]
  194. return VALUE[BOOLEAN['0']]
  195. elif isinstance(something, int):
  196. return VALUE[INT[something]]
  197. elif isinstance(something, float):
  198. return VALUE[DOUBLE[something]]
  199. def generate(*args):
  200. params = PARAMS()
  201. for arg in args:
  202. params[PARAM[_generate(arg)]]
  203. return METHODRESPONSE[params]
  204. if __name__ == '__main__':
  205. print parse("""<?xml version="1.0"?> <methodCall> <methodName>examples.getStateName</methodName> <params> <param> <value><i4>41</i4></value> </param> </params> </methodCall>
  206. """)