/gdata/tlslite/utils/jython_compat.py

http://radioappz.googlecode.com/ · Python · 195 lines · 137 code · 39 blank · 19 comment · 17 complexity · a28d80f70fbb0f290a2f6f9c73a264dd MD5 · raw file

  1. """Miscellaneous functions to mask Python/Jython differences."""
  2. import os
  3. import sha
  4. if os.name != "java":
  5. BaseException = Exception
  6. from sets import Set
  7. import array
  8. import math
  9. def createByteArraySequence(seq):
  10. return array.array('B', seq)
  11. def createByteArrayZeros(howMany):
  12. return array.array('B', [0] * howMany)
  13. def concatArrays(a1, a2):
  14. return a1+a2
  15. def bytesToString(bytes):
  16. return bytes.tostring()
  17. def stringToBytes(s):
  18. bytes = createByteArrayZeros(0)
  19. bytes.fromstring(s)
  20. return bytes
  21. def numBits(n):
  22. if n==0:
  23. return 0
  24. return int(math.floor(math.log(n, 2))+1)
  25. class CertChainBase: pass
  26. class SelfTestBase: pass
  27. class ReportFuncBase: pass
  28. #Helper functions for working with sets (from Python 2.3)
  29. def iterSet(set):
  30. return iter(set)
  31. def getListFromSet(set):
  32. return list(set)
  33. #Factory function for getting a SHA1 object
  34. def getSHA1(s):
  35. return sha.sha(s)
  36. import sys
  37. import traceback
  38. def formatExceptionTrace(e):
  39. newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
  40. return newStr
  41. else:
  42. #Jython 2.1 is missing lots of python 2.3 stuff,
  43. #which we have to emulate here:
  44. import java
  45. import jarray
  46. BaseException = java.lang.Exception
  47. def createByteArraySequence(seq):
  48. if isinstance(seq, type("")): #If it's a string, convert
  49. seq = [ord(c) for c in seq]
  50. return jarray.array(seq, 'h') #use short instead of bytes, cause bytes are signed
  51. def createByteArrayZeros(howMany):
  52. return jarray.zeros(howMany, 'h') #use short instead of bytes, cause bytes are signed
  53. def concatArrays(a1, a2):
  54. l = list(a1)+list(a2)
  55. return createByteArraySequence(l)
  56. #WAY TOO SLOW - MUST BE REPLACED------------
  57. def bytesToString(bytes):
  58. return "".join([chr(b) for b in bytes])
  59. def stringToBytes(s):
  60. bytes = createByteArrayZeros(len(s))
  61. for count, c in enumerate(s):
  62. bytes[count] = ord(c)
  63. return bytes
  64. #WAY TOO SLOW - MUST BE REPLACED------------
  65. def numBits(n):
  66. if n==0:
  67. return 0
  68. n= 1L * n; #convert to long, if it isn't already
  69. return n.__tojava__(java.math.BigInteger).bitLength()
  70. #This properly creates static methods for Jython
  71. class staticmethod:
  72. def __init__(self, anycallable): self.__call__ = anycallable
  73. #Properties are not supported for Jython
  74. class property:
  75. def __init__(self, anycallable): pass
  76. #True and False have to be specially defined
  77. False = 0
  78. True = 1
  79. class StopIteration(Exception): pass
  80. def enumerate(collection):
  81. return zip(range(len(collection)), collection)
  82. class Set:
  83. def __init__(self, seq=None):
  84. self.values = {}
  85. if seq:
  86. for e in seq:
  87. self.values[e] = None
  88. def add(self, e):
  89. self.values[e] = None
  90. def discard(self, e):
  91. if e in self.values.keys():
  92. del(self.values[e])
  93. def union(self, s):
  94. ret = Set()
  95. for e in self.values.keys():
  96. ret.values[e] = None
  97. for e in s.values.keys():
  98. ret.values[e] = None
  99. return ret
  100. def issubset(self, other):
  101. for e in self.values.keys():
  102. if e not in other.values.keys():
  103. return False
  104. return True
  105. def __nonzero__( self):
  106. return len(self.values.keys())
  107. def __contains__(self, e):
  108. return e in self.values.keys()
  109. def iterSet(set):
  110. return set.values.keys()
  111. def getListFromSet(set):
  112. return set.values.keys()
  113. """
  114. class JCE_SHA1:
  115. def __init__(self, s=None):
  116. self.md = java.security.MessageDigest.getInstance("SHA1")
  117. if s:
  118. self.update(s)
  119. def update(self, s):
  120. self.md.update(s)
  121. def copy(self):
  122. sha1 = JCE_SHA1()
  123. sha1.md = self.md.clone()
  124. return sha1
  125. def digest(self):
  126. digest = self.md.digest()
  127. bytes = jarray.zeros(20, 'h')
  128. for count in xrange(20):
  129. x = digest[count]
  130. if x < 0: x += 256
  131. bytes[count] = x
  132. return bytes
  133. """
  134. #Factory function for getting a SHA1 object
  135. #The JCE_SHA1 class is way too slow...
  136. #the sha.sha object we use instead is broken in the jython 2.1
  137. #release, and needs to be patched
  138. def getSHA1(s):
  139. #return JCE_SHA1(s)
  140. return sha.sha(s)
  141. #Adjust the string to an array of bytes
  142. def stringToJavaByteArray(s):
  143. bytes = jarray.zeros(len(s), 'b')
  144. for count, c in enumerate(s):
  145. x = ord(c)
  146. if x >= 128: x -= 256
  147. bytes[count] = x
  148. return bytes
  149. import sys
  150. import traceback
  151. def formatExceptionTrace(e):
  152. newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
  153. return newStr