def testDefaultTypeNameBoolean(self): self.assertEqual(type(JObject(True)), jpype.JClass("java.lang.Boolean")) self.assertEqual(type(JObject(False)), jpype.JClass("java.lang.Boolean"))
def test_01(self): # 第二步:打开被测网站 driver = self.driver driver.get(self.base_url) # 第三步:执行测试动作 # 定义测试数据 email = "*****@*****.**" password = "******" name = "王朝12001" # 登录主账号 login_thinksns(driver, email, password, name) # 先定位到左侧应用列表,再点击 相册 driver.find_element_by_class_name( "user_app_list").find_element_by_link_text("相册").click() # 得到当前照片数量 我的全部照片(2) number = self.get_pictures_number(driver, "我的全部照片(", ")") # 点击 上传 driver.find_element_by_link_text("上传").click() sleep(1) # 定义jvm和sikuli jar包所在的路径 jvm_path = r"C:\Program Files\Java\jdk1.8.0_151\jre\bin\server\jvm.dll" jar_path = "-Djava.class.path=" + self.path + r"\libs\sikulixapi.jar" # 启动JVM jpype.startJVM(jvm_path, jar_path) # 找到能够进行屏幕操作的Screen类(相当于将Java版本的Screen类转换成Python的) Screen = jpype.JClass("org.sikuli.script.Screen") # 实例化该Screen类 screen = Screen() # 定义添加照片按钮图片所在的路径 add_path = self.path + r"\images\sikuli_imgs\add.png" # 根据实例化对象,点击该图片 screen.click(add_path) # 定义文件名输入框图片所在的路径 input_path = self.path + r"\images\sikuli_imgs\input.png" # 根据实例化对象,点击该图片 screen.click(input_path) # 定义两张需要上传的照片的路径 "c:\灯塔.jpg" "c:\八仙花.jpg" img1 = self.path + "\\images\\blog_imgs\\" + str(randint(0, 7)) + ".jpg" img2 = self.path + "\\images\\blog_imgs\\" + str(randint(0, 7)) + ".jpg" img_path = '"' + img1 + '" "' + img2 + '"' # 根据实例化对象,在输入框内输入上述路径 screen.type(input_path, img_path) # 定义打开按钮的图片所在的路径 open_path = self.path + r"\images\sikuli_imgs\open.png" # 根据实例化对象,点击该图片 screen.click(open_path) sleep(1) # 关闭JVM jpype.shutdownJVM() # 点击开始上传 driver.find_element_by_id("btnUpload").click() sleep(2) # 判断是否出现成功的提示,判断在其中即可: 照片上传成功! actual_tip = driver.find_element_by_name("save_upload_photos").text self.assertIn("照片上传成功!", actual_tip) # 点击完成上传 driver.find_element_by_class_name("btn_b").click() # 得到当前照片数量 共4张 actual_number = self.get_pictures_number(driver, "共", "张") # 判断照片数量的变化是否正确 self.assertEqual(number + 2, actual_number)
def testJClassBadClass(self): with self.assertRaises(Exception): jpype.JClass("not.a.class")
import os import jpype jpype.startJVM(jpype.getDefaultJVMPath(),"-ea","-Djava.class.path=c:/Java") A = jpype.JClass("C") c = A() c.a() jpype.shutdownJVM()
def testJClassFromClass(self): self.assertIsInstance( jpype.JClass( jpype.java.lang.Class.forName("java.lang.StringBuilder")), jpype.JClass)
def setUp(self): common.JPypeTestCase.setUp(self) self.Test = jpype.JClass("jpype.common.Fixture")()
def testExcCtor(self): WE = jpype.JClass("jpype.exc.WierdException") with self.assertRaises(WE): WE.testThrow()
def __init__(self, dataDir): print "init func" self.dataDir = dataDir self.Presentation=jpype.JClass("com.aspose.slides.Presentation") self.SaveFormat=jpype.JClass("com.aspose.slides.SaveFormat") self.ShapeType=jpype.JClass("com.aspose.slides.ShapeType")
def setUp(self): common.JPypeTestCase.setUp(self) self.classLoader = jpype.JClass( 'org.jpype.classloader.JPypeClassLoader').getInstance()
def add_device(request): if request.method == 'POST': req = json.loads(request.body) keyuser = req['keyusername'] keypwd = req['keypassword'] a = login_require(keyuser, keypwd) if a == 0: reason = "未登录" elif a == 1: reason = "普通用户无此权限" elif a == 2: try: req = json.loads(request.body) devicename = req['devicename'] type = req['type'] except: reason = "没有数据耶" j = jsonedit(reason) return HttpResponse(j) username = req['username'] if username: # 单纯添加设备,不与用户绑定 try: userid = User.objects.get(username=username).id except: reason = "无此用户" j = jsonedit(reason) return HttpResponse(j) flag = 1 else: flag = 0 device = DeviceInfo.objects.filter(devicename=devicename) if device.exists(): print(device) reason = "重名啦" j = jsonedit(reason) return HttpResponse(j) if not jpype.isJVMStarted(): jpype.startJVM(jvmPath, jvmArg) jpype.attachThreadToJVM() Main = jpype.JClass("yuer.yueriot") jd = Main() secret = jd.yuerregist(devicename) try: id = DeviceInfo.objects.create(devicename=devicename, devicesecret=secret, type=type).id except: reason = "add_device出错" j = jsonedit(reason) return HttpResponse(j) if flag == 1: UandD.objects.create(username=username, deviceid_id=id, devicename=devicename, userid_id=userid, device_type=type) user_info_all() device_status_all() reason = None j = jsonedit(reason) return HttpResponse(j)
#random embedding # with open(char2ind_path,"rb") as f: # obj = pickle.load(f) # char_num = len(obj.keys()) # print("char_num",char_num) # print("obj keys",list(obj.items())) # random_char_embedding(300, char_num, embedding_path) #char_data_merge(corpus_path, merged_corpus_path, char2ind_path) #split jvmPath = jpype.getDefaultJVMPath() jpype.startJVM( jvmPath, '-Djava.class.path=C:\ProgramData\Anaconda3\Lib\site-packages\pyhanlp\static\hanlp-1.6.8.jar;C:\ProgramData\Anaconda3\Lib\site-packages\pyhanlp\static' ) HanLP = jpype.JClass('com.hankcs.hanlp.HanLP') #copus_to_input() # Config = jpype.JClass('com.hankcs.hanlp.HanLP$Config') # Config.ShowTermNature=False #data_merge(corpus_path, merged_corpus_path, "./label2ind.pkl") #corpus2tfrecord(r'word2ind_dct.pkl',r'./corpus_merge2.txt','./tfrecord_texst.record') # char_data_merge(corpus_path, merged_corpus_path, char2ind_path) #corpus2tfrecord(word2ind_path,merged_corpus_path,'./word_tfrecord_test.record') #corpus2tfrecord(char2ind_path,merged_corpus_path,'./char_tfrecord.record') #生成word训练集和验证集 #word2ind_path = "./data/word2ind_dct.pkl" #merged_corpus_path = r'./corpus_word_merge.txt' #corpus2tfrecord(word2ind_path, merged_corpus_path, './word_tfrecord.record', fold=8, num_class=33) #corpus2tfrecord(word2ind_path, merged_corpus_path, './word_test3000_tfrecord.record', fold=8, num_class=33)
def setUp(self): common.JPypeTestCase.setUp(self) self.classLoader = jpype.JClass( 'org.jpype.JPypeContext').getInstance().getBootLoader() self.refqueue = jpype.JClass( 'org.jpype.JPypeContext').getInstance().getReferenceQueue()
def testWrapJavaObjectCast(self): o = JClass('java.lang.String')("foo") c = JClass('java.lang.Object') self.assertEqual(type(JObject(o, c)), jpype.JClass("java.lang.Object"))
def testWrapJavaObject(self): o = JClass('java.lang.String')("foo") self.assertEqual(type(JObject(o)), jpype.JClass("java.lang.String"))
def __init__(self, server,username,pwd): jvmpath=r"C:\Program Files\Java\jre1.8.0_60\bin\server\jvm.dll" jarpath=r'd:\temp\jt400.jar' jvmArg = "-Djava.class.path=%s" % jarpath jpype.startJVM(jvmpath,jvmArg) #jt400 AS400=jpype.JClass('com.ibm.as400.access.AS400') CommandCall=jpype.JClass('com.ibm.as400.access.CommandCall') ProgramCall=jpype.JClass('com.ibm.as400.access.ProgramCall') SpooledFileList=jpype.JClass('com.ibm.as400.access.SpooledFileList') AS400Text=jpype.JClass('com.ibm.as400.access.AS400Text') AS400JDBCDriver=jpype.JClass('com.ibm.as400.access.AS400JDBCDriver') #java Connection=jpype.JClass('java.sql.Connection') DatabaseMetaData=jpype.JClass('java.sql.DatabaseMetaData') Statement=jpype.JClass('java.sql.Statement') self.ResultSet=jpype.JClass('java.sql.ResultSet') self.server,self.username,self.pwd = server,username,pwd self.RJobLog=jpype.JClass('com.ibm.as400.resource.RJobLog') self.AS400FTP=jpype.JClass('com.ibm.as400.access.AS400FTP') self.IFSFile=jpype.JClass('com.ibm.as400.access.IFSFile') self.ProgramParameter=jpype.JClass('com.ibm.as400.access.ProgramParameter') self.DriverManager=jpype.JClass('java.sql.DriverManager') self.DriverManager.registerDriver(AS400JDBCDriver()) self.system=AS400(server,username,pwd) self.cc=CommandCall(self.system) self.outqueue = SpooledFileList(self.system) self.pc = ProgramCall(self.system)
def testAccess(self): # Access the reference queue using the private class loader JPypeReferenceQueue = jpype.JClass('org.jpype.ref.JPypeReferenceQueue', loader=self.classLoader) # Make sure we can get the instance self.assertTrue(JPypeReferenceQueue.getInstance() != None)
def testForName(self): cls=jpype.JClass('java.lang.Class') test=cls.forName('jpype.overloads.Test1') # Should return a java.lang.Class, rather than the python wrapper for java.lang.Class self.assertTrue( type(test)==type(cls.class_)) self.assertEquals( test.getName(), 'jpype.overloads.Test1')
# -*- coding: utf-8 -*- import jpype as jp ## Zemberek: Histogram Example # Documentation: https://github.com/ahmetaa/zemberek-nlp/blob/master/examples/src/main/java/zemberek/examples/core/HistogramExample.java # Relative path to Zemberek .jar ZEMBEREK_PATH = '../../bin/zemberek-full.jar' # Start the JVM jp.startJVM(jp.getDefaultJVMPath(), '-ea', '-Djava.class.path=%s' % (ZEMBEREK_PATH)) # Importing the required Java class Histogram = jp.JClass('zemberek.core.collections.Histogram') # Creating the first histogram histogram = Histogram() fruits = ['apple', 'pear', 'grape', 'apple', 'apple', 'appricot', 'grape'] histogram.add(fruits) # Creating the second histogram other_histogram = Histogram() other_fruits = ['apple', 'apple', 'banana'] other_histogram.add(other_fruits) # Some Histogram methods: print('Histogram 1: %s' % histogram.map) print('Histogram 2: %s\n' % other_histogram.map)
import jpype import json import uuid import random import math from sympy import * jpype.startJVM(classpath=[ '/Users/hulang/IdeaProjects/UXVSimulator/target/UXVSim-1.0-SNAPSHOT-jar-with-dependencies.jar' ]) Emulator = jpype.JClass("uxvsim.Emulator") def solve_acc(): t = 1 x_abs = 20 v_abs = 10 param_list = [[[[t, 0, 0, 0, 0], [t, 0, 0, 0, 0]], [[t, x_abs, 0, v_abs, 5], [t, 0, 0, 0, 0]], [[t, -x_abs, 0, -v_abs, -5], [t, 0, 0, 0, 0]], [[t, 0, 0, 0, 0], [t, x_abs, 0, v_abs, 5]], [[t, 0, 0, 0, 0], [t, -x_abs, 0, -v_abs, -5]]], [[[t, 0, v_abs, 0, -5], [t, 0, 0, 0, 0]], [[t, x_abs, v_abs, v_abs, 0], [t, 0, 0, 0, 0]], [[t, -x_abs, v_abs, -v_abs, -5], [t, 0, 0, 0, 0]], [[t, 0, v_abs, 0, -5], [t, x_abs, 0, v_abs, 5]], [[t, 0, v_abs, 0, -5], [t, -x_abs, 0, -v_abs, -5]]], [[[t, 0, -v_abs, 0, 5], [t, 0, 0, 0, 0]], [[t, x_abs, -v_abs, v_abs, 5], [t, 0, 0, 0, 0]], [[t, -x_abs, -v_abs, -v_abs, 0], [t, 0, 0, 0, 0]], [[t, 0, -v_abs, 0, 5], [t, x_abs, 0, v_abs, 5]],
if not jpype.isJVMStarted(): _jvm_args = string.split(pym.environ['JVM_ARGS'],' ') _jvm_class_path = pym.environ['COMPILER_JARS'] _jvm_ext_dirs = pym.environ['BEAVER_PATH'] jpype.startJVM(pym.environ['JPYPE_JVM'], '-Djava.class.path=%s' % os.pathsep.join([_jvm_class_path]), *_jvm_args) org = jpype.JPackage('org') print "JVM started." # Compilers ModelicaCompilerInterface = None OptimicaCompilerInterface = None if pym._modelica_class: ModelicaCompilerInterface = jpype.JClass(pym._modelica_class) if pym._optimica_class: OptimicaCompilerInterface = jpype.JClass(pym._optimica_class) # Options registry OptionRegistryInterface = org.jmodelica.common.options.OptionRegistry # Exceptions UnknownOptionException = jpype.JClass( 'org.jmodelica.common.options.AbstractOptionRegistry$UnknownOptionException') InvalidOptionValueException = jpype.JClass( 'org.jmodelica.common.options.AbstractOptionRegistry$InvalidOptionValueException') IllegalLogStringException = org.jmodelica.util.logging.IllegalLogStringException
import jpype import os if __name__ == '__main__': jvmPath = jpype.getDefaultJVMPath() jpype.startJVM( jvmPath, "-ea", "-Djava.class.path=%s" % ('../out/artifacts/EncryptorDecryptor_jar/EncryptorDecryptor.jar')) MyAES = jpype.JClass("top.enatsu.MyAES") while True: command = input('Input command (e or d): ') if command == 'e': encodeRules = input() content = input() print('Encode result:', MyAES.AESEncode(encodeRules, content)) print( 'Decode result:', MyAES.AESDecode(encodeRules, MyAES.AESEncode(encodeRules, content))) elif command == 'd': encodeRules = input() content = input() print('Decode result:', MyAES.AESDecode(encodeRules, content)) print( 'Encode result:', MyAES.AESEncode(encodeRules, MyAES.AESDecode(encodeRules, content))) elif command == 'q': break else: print('Unknown command')
for key in sorted(d.keys()): output.append((key, hashable(d[key]))) return tuple(output) elif isinstance(d, list): output = [] for item in d: output.append(hashable(item)) return tuple(output) else: return d try: DatabaseInterface = jpype.JClass("org.hyperbolicstorage.DatabaseInterface") databaseInterface = DatabaseInterface(dbLocation) GeographicalTiles = jpype.JClass("org.hyperbolicstorage.GeographicalTiles") Point2D = jpype.JClass("org.hyperbolicstorage.GeographicalTiles$Point2D") IndexPair = jpype.JClass( "org.hyperbolicstorage.GeographicalTiles$IndexPair") for lineNumber, drawableString in enumerate(sys.stdin.xreadlines()): drawableString = drawableString.strip() drawable = json.loads(drawableString) if drawable["type"] == "polygon": x = 0.0 y = 0.0 N = 0.0
def setUp(self): common.JPypeTestCase.setUp(self) self.cls = jpype.JClass('java.lang.String') self.obj = self.cls('foo')
def execute_sql(sql): conn = None jars_path = '/you_filed_algos/jars/' dirver = "org.apache.hive.jdbc.HiveDriver" url = "jdbc:hive2://bigdata-dev-014:7180/;ssl=true;sslTrustStore=/you_filed_algos/cm-auto-global_truststore.jks;principal=impala/[email protected]" jars_file_ls = [] jars_file_str = '' for jar in os.listdir(jars_path): jars_file_ls.append(jars_path + jar) jars_file_str = ':'.join(jars_file_ls) jvm_options = "-Djava.class.path=" + jars_file_str # jvm = jpype.getDefaultJVMPath() jvm = '/you_filed_algos/jdk8/jre/lib/amd64/server/libjvm.so' # if not jpype.isJVMStarted(): # try: # #print('--------startjvm---------') # jpype.startJVM(jvm, jvm_options) # # print("JVM path:"+ jpype.getDefaultJVMPath()) # # print('----- running jvm -------------') # # except Exception as e: # print('====== throw error ======') # traceback.print_exc() # jpype.shutdownJVM() try: print('--------startjvm---------') jpype.startJVM(jvm, jvm_options) except Exception as e: print('====== throw error ======') pass System = jpype.java.lang.System # System = jpype.JClass('java.lang.System') System.setProperty("java.security.krb5.conf", "/you_filed_algos/krb5.conf") Configuration = jpype.JPackage('org.apache.hadoop.conf').Configuration conf = Configuration() conf.set("hadoop.security.authentication", "kerberos") try: UserGroupInformation = jpype.JClass( 'org.apache.hadoop.security.UserGroupInformation') UserGroupInformation.setConfiguration(conf) UserGroupInformation.loginUserFromKeytab( "sjfw_pbpang", "/you_filed_algos/sjfw_pbpang.keytab") conn = jaydebeapi.connect(dirver, url) # print("* create connection object") cur = conn.cursor() cur.execute(sql) list = cur.fetchall() # list = cur.fetchone() # 关闭游标 cur.close() # 关闭连接 conn.close() return list except Exception as ex: print(ex) traceback.print_exc()
def setUp(self): common.JPypeTestCase.setUp(self) global glob, success, obj obj = jpype.JClass("java.lang.Object")()
def prod_execute_sql(conn_type='prod', sqltype='insert', sql=''): """ :param conn_type: 连接类型 prod 生产集群环境 test 测试集群环境 :param sqltype: :param sql: :return: """ jars_path = '/you_filed_algos/jars/' dirver = "org.apache.hive.jdbc.HiveDriver" is_prod_env = True PROD = 'prod' # 生产环境 TEST = 'test' # 测试环境 #print('**** prod_execute_sql ****') #print('* conn_type=', conn_type) if conn_type == PROD: # 生产集群使用KUDU url = "jdbc:hive2://hadoop-pro-017:7180/default;ssl=true;sslTrustStore=/you_filed_algos/prod-cm-auto-global_truststore.jks;principal=impala/[email protected]" elif conn_type == TEST: # 开发集群使用KUDU # jdbc:hive2://bigdata-dev-014:7180/;ssl=true;sslTrustStore=/home/user/java/keytab/cm-auto-global_truststore.jks;principal=impala/[email protected] url = "jdbc:hive2://bigdata-dev-014:7180/;ssl=true;sslTrustStore=/you_filed_algos/cm-auto-global_truststore_kaifa.jks;principal=impala/[email protected]" jars_file_ls = [] jars_file_str = '' for jar in os.listdir(jars_path): jars_file_ls.append(jars_path + jar) jars_file_str = ':'.join(jars_file_ls) # jvm_options = ["-Djava.class.path=" + jars_file_str, '-Xmx2G','-Xms512M'] jvm_options = "-Djava.class.path=" + jars_file_str # jvm = jpype.getDefaultJVMPath() jvm = '/you_filed_algos/jdk8/jre/lib/amd64/server/libjvm.so' # if not jpype.isJVMStarted(): # try: # # print('--------startjvm---------') # jpype.startJVM(jvm, jvm_options) # # print("JVM path:"+ jpype.getDefaultJVMPath()) # # print('----- running jvm -------------') # # except Exception as e: # print('====== throw error ======') # traceback.print_exc() # jpype.shutdownJVM() try: if not jpype.isJVMStarted(): print('--------startjvm---------') jpype.startJVM(jvm, jvm_options) # jpype.startJVM(jvm, "-ea", jvm_options, '-Xmx5g', '-Xms5g', '-Xmn2g', '-XX:+UseParNewGC', # '-XX:ParallelGCThreads=8', '-XX:SurvivorRatio=6', '-XX:+UseConcMarkSweepGC') if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): print('-----attaching jvm-----') jpype.attachThreadToJVM() jpype.java.lang.Thread.currentThread().setContextClassLoader( jpype.java.lang.ClassLoader.getSystemClassLoader()) # print('--------startjvm---------') # jpype.startJVM(jvm, jvm_options) # print("JVM path:"+ jpype.getDefaultJVMPath()) # print('----- running jvm -------------') except Exception as e: print('====== throw error ======') traceback.print_exc() raise RuntimeError(e) try: # print('----- running jvm ,' , jpype.isJVMStarted()) System = jpype.java.lang.System if conn_type == PROD: # 生产集群使用KUDU System.setProperty("java.security.krb5.conf", "/you_filed_algos/prod-krb5.conf") elif conn_type == TEST: # 测试集群使用KUDU System.setProperty("java.security.krb5.conf", "/you_filed_algos/krb5_kaifa.conf") Configuration = jpype.JPackage('org.apache.hadoop.conf').Configuration conf = Configuration() conf.set("hadoop.security.authentication", "kerberos") UserGroupInformation = jpype.JClass( 'org.apache.hadoop.security.UserGroupInformation') UserGroupInformation.setConfiguration(conf) if conn_type == PROD: # 生产集群使用KUDU UserGroupInformation.loginUserFromKeytab( "sjfw_wangsh12348", "/you_filed_algos/sjfw_wangsh12348.keytab") elif conn_type == TEST: # 测试集群使用KUDU UserGroupInformation.loginUserFromKeytab( "sjfw_wangsh12348", "/you_filed_algos/sjfw_wangsh12348_kaifa.keytab") conn = jaydebeapi.connect(dirver, url) cur = conn.cursor() if sqltype == 'insert': cur.execute(sql) else: cur.execute(sql) result = cur.fetchall() # 关闭游标 cur.close() # 关闭连接 conn.close() if sqltype != 'insert': return result except Exception as ex: print(ex) traceback.print_exc() raise RuntimeError(ex)
def setUp(self): common.JPypeTestCase.setUp(self) self.test1 = jpype.JClass('jpype.overloads.Test1')() self.Reflect = jpype.JClass('jpype.reflect.ReflectionTest') self.Annotation = jpype.JClass('jpype.reflect.Annotation')
def testGetPrimitiveType(self): Integer = jpype.JClass("java.lang.Integer") intType = Integer.TYPE
def testJClassBadType(self): with self.assertRaises(TypeError): jpype.JClass({})
def testDefaultTypeNameString(self): self.assertEqual(type(JObject("123")), jpype.JClass("java.lang.String"))