Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.py 6.2KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. # -*- test-case-name: twisted.test.test_pb -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Utility classes for spread.
  6. """
  7. from zope.interface import implementer
  8. from twisted.internet import defer, interfaces
  9. from twisted.protocols import basic
  10. from twisted.python.failure import Failure
  11. from twisted.spread import pb
  12. class LocalMethod:
  13. def __init__(self, local, name):
  14. self.local = local
  15. self.name = name
  16. def __call__(self, *args, **kw):
  17. return self.local.callRemote(self.name, *args, **kw)
  18. class LocalAsRemote:
  19. """
  20. A class useful for emulating the effects of remote behavior locally.
  21. """
  22. reportAllTracebacks = 1
  23. def callRemote(self, name, *args, **kw):
  24. """
  25. Call a specially-designated local method.
  26. self.callRemote('x') will first try to invoke a method named
  27. sync_x and return its result (which should probably be a
  28. Deferred). Second, it will look for a method called async_x,
  29. which will be called and then have its result (or Failure)
  30. automatically wrapped in a Deferred.
  31. """
  32. if hasattr(self, "sync_" + name):
  33. return getattr(self, "sync_" + name)(*args, **kw)
  34. try:
  35. method = getattr(self, "async_" + name)
  36. return defer.succeed(method(*args, **kw))
  37. except BaseException:
  38. f = Failure()
  39. if self.reportAllTracebacks:
  40. f.printTraceback()
  41. return defer.fail(f)
  42. def remoteMethod(self, name):
  43. return LocalMethod(self, name)
  44. class LocalAsyncForwarder:
  45. """
  46. A class useful for forwarding a locally-defined interface.
  47. """
  48. def __init__(self, forwarded, interfaceClass, failWhenNotImplemented=0):
  49. assert interfaceClass.providedBy(forwarded)
  50. self.forwarded = forwarded
  51. self.interfaceClass = interfaceClass
  52. self.failWhenNotImplemented = failWhenNotImplemented
  53. def _callMethod(self, method, *args, **kw):
  54. return getattr(self.forwarded, method)(*args, **kw)
  55. def callRemote(self, method, *args, **kw):
  56. if self.interfaceClass.queryDescriptionFor(method):
  57. result = defer.maybeDeferred(self._callMethod, method, *args, **kw)
  58. return result
  59. elif self.failWhenNotImplemented:
  60. return defer.fail(
  61. Failure(NotImplementedError, "No Such Method in Interface: %s" % method)
  62. )
  63. else:
  64. return defer.succeed(None)
  65. class Pager:
  66. """
  67. I am an object which pages out information.
  68. """
  69. def __init__(self, collector, callback=None, *args, **kw):
  70. """
  71. Create a pager with a Reference to a remote collector and
  72. an optional callable to invoke upon completion.
  73. """
  74. if callable(callback):
  75. self.callback = callback
  76. self.callbackArgs = args
  77. self.callbackKeyword = kw
  78. else:
  79. self.callback = None
  80. self._stillPaging = 1
  81. self.collector = collector
  82. collector.broker.registerPageProducer(self)
  83. def stillPaging(self):
  84. """
  85. (internal) Method called by Broker.
  86. """
  87. if not self._stillPaging:
  88. self.collector.callRemote("endedPaging", pbanswer=False)
  89. if self.callback is not None:
  90. self.callback(*self.callbackArgs, **self.callbackKeyword)
  91. return self._stillPaging
  92. def sendNextPage(self):
  93. """
  94. (internal) Method called by Broker.
  95. """
  96. self.collector.callRemote("gotPage", self.nextPage(), pbanswer=False)
  97. def nextPage(self):
  98. """
  99. Override this to return an object to be sent to my collector.
  100. """
  101. raise NotImplementedError()
  102. def stopPaging(self):
  103. """
  104. Call this when you're done paging.
  105. """
  106. self._stillPaging = 0
  107. class StringPager(Pager):
  108. """
  109. A simple pager that splits a string into chunks.
  110. """
  111. def __init__(self, collector, st, chunkSize=8192, callback=None, *args, **kw):
  112. self.string = st
  113. self.pointer = 0
  114. self.chunkSize = chunkSize
  115. Pager.__init__(self, collector, callback, *args, **kw)
  116. def nextPage(self):
  117. val = self.string[self.pointer : self.pointer + self.chunkSize]
  118. self.pointer += self.chunkSize
  119. if self.pointer >= len(self.string):
  120. self.stopPaging()
  121. return val
  122. @implementer(interfaces.IConsumer)
  123. class FilePager(Pager):
  124. """
  125. Reads a file in chunks and sends the chunks as they come.
  126. """
  127. def __init__(self, collector, fd, callback=None, *args, **kw):
  128. self.chunks = []
  129. Pager.__init__(self, collector, callback, *args, **kw)
  130. self.startProducing(fd)
  131. def startProducing(self, fd):
  132. self.deferred = basic.FileSender().beginFileTransfer(fd, self)
  133. self.deferred.addBoth(lambda x: self.stopPaging())
  134. def registerProducer(self, producer, streaming):
  135. self.producer = producer
  136. if not streaming:
  137. self.producer.resumeProducing()
  138. def unregisterProducer(self):
  139. self.producer = None
  140. def write(self, chunk):
  141. self.chunks.append(chunk)
  142. def sendNextPage(self):
  143. """
  144. Get the first chunk read and send it to collector.
  145. """
  146. if not self.chunks:
  147. return
  148. val = self.chunks.pop(0)
  149. self.producer.resumeProducing()
  150. self.collector.callRemote("gotPage", val, pbanswer=False)
  151. # Utility paging stuff.
  152. class CallbackPageCollector(pb.Referenceable):
  153. """
  154. I receive pages from the peer. You may instantiate a Pager with a
  155. remote reference to me. I will call the callback with a list of pages
  156. once they are all received.
  157. """
  158. def __init__(self, callback):
  159. self.pages = []
  160. self.callback = callback
  161. def remote_gotPage(self, page):
  162. self.pages.append(page)
  163. def remote_endedPaging(self):
  164. self.callback(self.pages)
  165. def getAllPages(referenceable, methodName, *args, **kw):
  166. """
  167. A utility method that will call a remote method which expects a
  168. PageCollector as the first argument.
  169. """
  170. d = defer.Deferred()
  171. referenceable.callRemote(methodName, CallbackPageCollector(d.callback), *args, **kw)
  172. return d