def __prepareParam(self, param_pyclass, data): """ 私有方法 根据java类型为数据执行转型方法 """ if data == None: return None try: # 如果为精确数值型则执行new if param_pyclass.class_.getSimpleName() == 'BigDecimal': return param_pyclass(jpype.JString(str(data))) # 如果为字符串则转为jpype的通用字符型 elif param_pyclass.class_.getSimpleName() == 'String': return jpype.JString(str(data)) # 如果为整数型则执行new并开箱 elif param_pyclass.class_.getSimpleName() == 'Integer': return param_pyclass(jpype.JString(str(data))).intValue() # 否则执行其类方法转换 else: return param_pyclass.valueOf(jpype.JString(str(data))) except JavaException as e: _logger.error("Oracle Driver: SQL Error in prepare Params") log_java_exception(e) self.close() raise e
def testLt(self): a = jpype.JString("abc") b = jpype.JString("def") self.assertTrue(a < b) self.assertFalse(b < a) self.assertFalse(b < "def") self.assertTrue(a < "def")
def testLe(self): a = jpype.JString("abc") b = jpype.JString("def") self.assertTrue(a <= a) self.assertTrue(a <= b) self.assertFalse(b <= a) self.assertTrue(b <= "def") self.assertTrue(a <= "def")
def testGe(self): a = jpype.JString("abc") b = jpype.JString("def") self.assertTrue(a >= a) self.assertFalse(a >= b) self.assertTrue(b >= a) self.assertTrue(b >= "def") self.assertFalse(a >= "def")
def decryptData(self, encData, key, iv): # 解密 AES192Impl = jpype.JClass("com.zcsmart.aes.impl.AES192Impl") iaes = AES192Impl() AESModule = jpype.JClass("com.zcsmart.aes.en.AESModule") decData = iaes.decDataBase64(jpype.JString(encData), AESModule.AES_192_CBC_PKCS7, jpype.JString(key), jpype.JString(iv)) return json.loads(str(decData))
def testInvokeLeak(self): jstr = jpype.JString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa") def func(): jstr.getBytes() self.assertNotLeaky(func)
def testInvokeLeak(self): jstr = jpype.JString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa") def func(): jstr.getBytes() runLeakChecker(func, 5000)
def buildup(): """Everything we need to do BEFORE the tests are run""" # Start a Java VM jpype.startJVM( jpype.getDefaultJVMPath(), '-ea', '-Djava.class.path=' + config.ROOT_DIR + '/lib/spmf.jar' ) # Export the package and object which are needed in x4_cpt_plus.py pytest.pkg = jpype.JPackage('ca').pfv.spmf.algorithms.sequenceprediction.ipredict optionalParameters = 'CCF:true CBS:true CCFmin:1 CCFmax:5 CCFsup:2 splitMethod:0 ' \ 'splitLength:5 minPredictionRatio:1.0 noiseRatio:1' prediction_model_class = pytest.pkg.predictor.CPT.CPTPlus.CPTPlusPredictor pytest.prediction_model = prediction_model_class( jpype.JString('CPT+'), jpype.JString(optionalParameters) )
def encryptHead(self, head): # 签名消息头 AES192Impl = jpype.JClass("com.zcsmart.aes.impl.AES192Impl") iaes = AES192Impl() signData = iaes.signData(jpype.JString(head)) print("头信息: " + head) print("签名数据: " + str(signData)) return str(signData)
def encryptBody(self, body, key, iv): # 通过key,iv加密body # body传入的是json格式的,但这里比较特殊需要格式化 body = json.dumps(body, separators=(',', ':'), ensure_ascii=False) AES192Impl = jpype.JClass("com.zcsmart.aes.impl.AES192Impl") iaes = AES192Impl() AESModule = jpype.JClass("com.zcsmart.aes.en.AESModule") encBody = iaes.encDataBase64(jpype.JString(body), AESModule.AES_192_CBC_PKCS7, jpype.JString(key), jpype.JString(iv)) SHA256Util = jpype.JClass("com.zcsmart.aes.SHA256Util") bytesBody = bytes(SHA256Util.getServerHash_C(encBody)) base64Body = base64.b64encode(bytesBody) print("=========body: " + body) print("=========encBody: " + str(encBody)) print("=========hashBody: " + base64Body.decode('utf8')) return str(encBody), base64Body.decode('utf8')
def testAutoConvert(self): Instant = jpype.JClass("java.time.Instant") now = "2019-11-12T03:20:54.710948400Z" then = Instant.parse(now) self.assertEqual(str(then), now) then = Instant.parse(jpype.JString(now)) self.assertEqual(str(then), now) then = Instant.parse(jpype.JObject(now, "java.lang.CharSequence")) self.assertEqual(str(then), now)
def runInvoke(counts): startup() lc = LeakChecker() jstr = jpype.JString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa") def func(): jstr.getBytes() return lc.memTest(func, 5000)
def testMethodHelp(self): import io import contextlib f = io.StringIO() with contextlib.redirect_stdout(f): help(jpype.JString("a").substring) s = f.getvalue() self.assertTrue("Java method dispatch" in s) self.assertTrue("substring(int)" in s) self.assertTrue("substring(int, int)" in s)
def testGetItem(self): a = jpype.JString("abc") self.assertEqual(a[0], 'a') self.assertEqual(a[1], 'b') self.assertEqual(a[2], 'c') self.assertEqual(a[-1], 'c') self.assertEqual(a[-2], 'b') self.assertEqual(a[-3], 'a') with self.assertRaises(IndexError): x = a[3] with self.assertRaises(IndexError): x = a[-4]
def load_training_set(pkg, path, numbers=[]): """Loads the training set file of training sequences. Either simply load a training set file (in the tree) as is, or load a training set file appended with an additional sequence. Args: pkg(jpype object): common root of the java package from which we load the classes we need. path(str): filepath to the training file to load. numbers(list): optional, number sequence(s) to append to training file. Returns: jpype object: training set object. """ # Loading the java classes we need and instantiating the objects we will use # Training Set: this is the file we feed to the tree training_set_class = pkg.database.SequenceDatabase training_set = training_set_class() if numbers: with tempfile.NamedTemporaryFile(mode='w+') as tmpf: with open(path, 'r') as file: tmpf.write(file.read()) new_line = ' -1 '.join(map( str, numbers)) + ' -1 -2\n' # SPMF format tmpf.write(new_line) tmpf.seek(0) training_set.loadFileSPMFFormat(jpype.JString(tmpf.name), jpype.JInt(99999), jpype.JInt(0), jpype.JInt(99999)) else: training_set.loadFileSPMFFormat(jpype.JString(path), jpype.JInt(99999), jpype.JInt(0), jpype.JInt(99999)) return training_set
def runRefCount(): startup() obj = jpype.JString("help me") initialObj = sys.getrefcount(obj) initialValue = sys.getrefcount(obj.__javavalue__) for i in range(0, 100): obj.charAt(0) subrun.assertTrue(sys.getrefcount(obj) - initialObj < 5) subrun.assertTrue(sys.getrefcount(obj.__javavalue__) - initialValue < 5) initialObj = sys.getrefcount(obj) initialValue = sys.getrefcount(obj.__javavalue__) for i in range(0, 100): obj.compareTo(obj) subrun.assertTrue(sys.getrefcount(obj) - initialObj < 5) subrun.assertTrue(sys.getrefcount(obj.__javavalue__) - initialValue < 5)
def wrapper(**kargs): kargsTuple = (kargs['body'], kargs['key'], kargs['iv'], kargs['head'], kargs['payload'], kargs['headers']) body, key, iv, head, payload, headers = kargsTuple # 加密 encBody, hashBody = self.encryptBody(body, key, iv) head['hashbody'] = hashBody # 签名 signData = self.encryptHead(json.dumps(head)) payload['encData'] = encBody if 'token' in kargs.keys(): headers.update({'X-CLIENT-TOKEN': kargs['token']}) headers.update({ 'X-CLIENT-AUTH': json.dumps(head), 'X-CLIENT-SIGN': signData }) encData = func(**kargs) # 解密 return self.decryptData(jpype.JString(encData), key, iv)
def testAttach(self): # Make sure we are attached to start the test jpype.attachThreadToJVM() self.assertTrue(jpype.isThreadAttachedToJVM()) # Detach from the thread jpype.detachThreadFromJVM() self.assertFalse(jpype.isThreadAttachedToJVM()) # Reattach to the thread jpype.attachThreadToJVM() self.assertTrue(jpype.isThreadAttachedToJVM()) # Detach again jpype.detachThreadFromJVM() self.assertFalse(jpype.isThreadAttachedToJVM()) # Call a Java method which will cause it to attach automatically s = jpype.JString("foo") self.assertTrue(jpype.isThreadAttachedToJVM())
def testModuleExamine(self): # this is an internal testing routine for Java slots _jpype.examine(jpype.JString) _jpype.examine(jpype.JString("foo"))
def testJStringRepr(self): js = jpype.JString("fred") self.assertTrue(repr(js), "fred")
def testJStringContains(self): js = jpype.JString("fred") self.assertTrue("r" in js) self.assertFalse("g" in js)
def testJStringGE(self): js = jpype.JString("b") self.assertFalse(js >= 'c') self.assertTrue(js >= 'b') self.assertTrue(js >= 'a')
def testJStringLT(self): js = jpype.JString("b") self.assertTrue(js < 'c') self.assertFalse(js < 'b') self.assertFalse(js < 'a')
def testJStringLen(self): js = jpype.JString("fred") self.assertEqual(len(js), 4)
def testJStringGetItem(self): js = jpype.JString("fred") self.assertEqual(js[1], "r")
def testJStringNE(self): js = jpype.JString("foo") self.assertFalse(js != "foo") self.assertFalse(js != jpype.JString("foo"))
def testJStringAppend(self): js = jpype.JString("foo") self.assertEqual(js + "bar", "foobar") if not self._convertStrings: self.assertIsInstance(js + "bar", jpype.java.lang.String)
def cut(line): words = jd.seg(jpype.JString(line)) coreStop.apply(words) return [i.word for i in words if i.word not in stopwords]
def testMonitorOnString(self): value = jpype.JString("foo") with self.assertRaises(TypeError): _jpype._JMonitor(value)
def testHashString(self): self.assertIsNotNone(hash(jpype.java.lang.String("upside down"))) self.assertIsNotNone(hash(jpype.JString("upside down"))) self.assertEqual(hash(jpype.JString("upside down")), hash("upside down"))