Exemplo n.º 1
0
    def stop_jvm(cls):
        """Stop java virtual machine and GNATS server

        This also moves back to the original directory that was set
        prior to starting the JVM

        If this function is not called manually, it will be called
        automatically at exit to make sure that the JVM is properly
        shutdown.  Multiple calls are OK.

        """
        if not cls.jvm_started:
            # Not yet started, do nothing
            return
        if cls.jvm_stopped:
            # Already started, do nothing
            return

        cls.gnatsStandalone.stop()

        # Note: have observed that calls to shutdownJVM after a jpype
        # exception can lead to a hang.  It should be safe here due to
        # the jvm_started check, but keep it in mind if reorganizing
        # the code.
        jpype.shutdownJVM()

        # Go back to where we where.  Note that calling this prior to
        # gnatsStandalone.stop() seeems to result in crashes/hangs.
        # Also note that trying to do this directory change prior to
        # writing the output file does not seem to eliminate the need
        # to fixup the paths manually.
        os.chdir(cls.cwd)

        cls.jvm_stopped = True
Exemplo n.º 2
0
def main():

    sys.modules["jpype"] = importlib.import_module("jt.jpype")
    sys.modules["jpypex"] = importlib.import_module("jt.jpypex")
    sys.modules["jpype.awt"] = importlib.import_module("jt.jpype.awt")
    sys.modules["jpype.imports"] = importlib.import_module("jt.jpype.imports")
    sys.modules["jpype.JClassUtil"] = importlib.import_module(
        "jt.jpype.JClassUtil")
    sys.modules["jpype.nio"] = importlib.import_module("jt.jpype.nio")
    sys.modules["jpype.reflect"] = importlib.import_module("jt.jpype.reflect")
    sys.modules["jpype._jboxed"] = importlib.import_module("jt.jpype._jboxed")
    sys.modules["jpype._jwrapper"] = importlib.import_module(
        "jt.jpype._jwrapper")
    sys.modules["jpype._jvmfinder"] = importlib.import_module(
        "jt.jpype._jvmfinder")
    sys.modules["jpype._linux"] = importlib.import_module("jt.jpype._linux")
    sys.modules["jpype._darwin"] = importlib.import_module("jt.jpype._darwin")
    sys.modules["jpype._cygwin"] = importlib.import_module("jt.jpype._cygwin")
    sys.modules["jpype._windows"] = importlib.import_module(
        "jt.jpype._windows")

    import jpype
    jvm_path = jpype.getDefaultJVMPath(java_version=1.8)

    print("Running testsuite using JVM:", jvm_path, "\n", file=sys.stderr)

    try:
        tests = test_suite(sys.argv[1:] or None)
        result = unittest.TextTestRunner(verbosity=2).run(tests)
    finally:
        if jpype.isJVMStarted():
            jpype.shutdownJVM()

    sys.exit(0 if result.wasSuccessful() else 1)
Exemplo n.º 3
0
 def stop_jvm(self):
     """
     关闭JVM虚拟机
     :return:
     """
     if self._is_jvm_ready:
         jpype.shutdownJVM()
Exemplo n.º 4
0
    def file2tasks(self, f1):
        fr = open(f1, 'r')
        tasks = []
        for line in fr:
            line = line.rstrip("\n")
            arr2 = line.split("\t")
            # path, params, tbin, tbout, time, line
            tasks.append(
                (arr2[0], arr2[2], arr2[5].split(",") if arr2[5] else [], arr2[6].split(",") if arr2[6] else [], float(arr2[7]), line))
        fr.close()
        out2id=dict([(ot, t[0]) for t in tasks for ot in t[3]])
        id2time=dict([(t[0], t[4]) for t in tasks])
        id2time["_end_"] = 0.0
        edges=[(out2id[it], t[0], id2time[out2id[it]]) for t in tasks for it in t[2]]
        edges += [(t[0], "_end_", id2time[t[0]]) for t in tasks]

        vs = [id for id in id2time.keys()]
        id2i = dict([(id, i) for i, id in enumerate(vs)])
        edges2A4 = [(id2i[e[0]], id2i[e[1]], e[2]) for e in edges]
        graphfile = f1 + ".graph"
        graphfw = open(graphfile, 'w')
        graphfw.write("%s\n" % len(id2i))
        graphfw.write("%s\n" % len(edges2A4))
        [graphfw.write("%s %s %s\n" %(e[0], e[1], e[2])) for e in edges2A4]
        graphfw.close()

        jarpath = "/home/wangdawei/github/algs4/target/algs4-1.0.0.0.jar"
        jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)
        AcycleLPSort = jpype.JClass('edu.princeton.cs.algs4.AcycleLPSort')
        acycleLPSort = AcycleLPSort()
        res = acycleLPSort.sort(graphfile)
        i2v = dict([(e.i, e.d) for e in res])
        jpype.shutdownJVM()

        return [(id, status, ins, outs, runtime, i2v[id2i[id]], line) for id, status, ins, outs, runtime, line in tasks]
def Normalize(query):
    ZEMBEREK_PATH: str = join('Zemberek', 'bin', 'zemberek-full.jar')

    startJVM(getDefaultJVMPath(),
             '-ea',
             f'-Djava.class.path={ZEMBEREK_PATH}',
             convertStrings=False)

    TurkishMorphology: JClass = JClass('zemberek.morphology.TurkishMorphology')
    TurkishSentenceNormalizer: JClass = JClass(
        'zemberek.normalization.TurkishSentenceNormalizer')
    Paths: JClass = JClass('java.nio.file.Paths')

    normalizer = TurkishSentenceNormalizer(
        TurkishMorphology.createWithDefaults(),
        Paths.get(join('Zemberek', 'ZemberekData', 'normalization')),
        Paths.get(join('Zemberek', 'ZemberekData', 'lm', 'lm.2gram.slm')))

    norm = normalizer.normalize(JString(query))

    print((f'\nNoisy : {query}'
           f'\nNormalized : {normalizer.normalize(JString(query))}\n'))

    return norm

    shutdownJVM()
Exemplo n.º 6
0
def main():
    if len(sys.argv)!=2:
        print len(sys.argv)
        print "Usage " +str(sys.argv[0])+" <edf file> "
        sys.exit(0)
    else:
        fl = str(sys.argv[1])
        dataObj  = EEGData(fl)

        jpype.startJVM(jpype.getDefaultJVMPath())

        pyobs   = Observer()
        pyobs.setData(dataObj)
        jobs    = jpype.JClass("Observer")
        obsprox = jpype.JProxy(jobs, inst=pyobs)

        jdata    = jpype.JClass("EEGData")
        dataprox = jpype.JProxy(jdata,inst=dataObj)

        projObj  = projectManager()
        jproj    = jpype.JClass("ProjectManager")
        projprox = jpype.JProxy(jproj,inst=projObj)

        gui = jpype.JClass("GUI")
        print 'gui init'
        gui(obsprox,dataprox,projprox)

        time.sleep(1000)
        jpype.shutdownJVM()
Exemplo n.º 7
0
 def encryption_zip(self, xtbh):
     cg = ReadConfig()
     zippath = cg.getvalue('localPath', 'path') + '\\' + str(xtbh) + '.zip'
     logger.info(zippath)
     if os.path.exists(zippath):
         logger.info('压缩包存在,开始加密')
         jarpath1 = os.path.join(
             os.path.abspath('.'),
             '../tools//jar//ebcp-exchange-1.1.6-minio-SNAPSHOT.jar')
         jpype.startJVM(jpype.getDefaultJVMPath(), "-ea",
                        "-Djava.class.path=%s" % (jarpath1))  # 启动jvm
         JClass = jpype.JClass(
             'com.thunisoft.ebcp.exchange.support.utils.DESUtil')
         test = JClass()
         zipanme = os.path.split(zippath)[1]  # 获取压缩包名称
         logger.info("压缩包名称%s" % zipanme)
         zip_path = os.path.split(zippath)[0]  # 获取压缩包路径
         logger.info("压缩包路径%s" % zip_path)
         zip_path_after = os.path.join(
             zip_path, "./after_jiami")  # 默认在当前路径下创建一级目录,用来存放解密之后的压缩包
         test.encryptZip(zippath, zip_path_after, zipanme,
                         "75AFFF024BDA72E9CAAB5E019BB94729")
         jpype.shutdownJVM()  # 最后关闭jvm
         logger.info("加密成功")
         logger.info("加密后文件存放路径:%s" % zip_path_after)
     else:
         logger.info('压缩包不存在,无法加密')
 def _pre_transform(self):
     jvm_path = jpype.getDefaultJVMPath()
     jars_path = _get_jars_path(self.java_lib_path)
     jvm_arg = "-Djava.class.path={jars_path}".format(jars_path=":".join(jars_path))
     if jpype.isJVMStarted():
         jpype.shutdownJVM()
     jpype.startJVM(jvm_path, jvm_arg, convertStrings=True)
Exemplo n.º 9
0
 def do_shutdown(self, restart):
     if restart:
         if not jpype.isJVMStarted():
             startJVM()
         self.VTLSession = JPackage('it').bancaditalia.oss.vtl.config.ConfigurationManager.getDefault().createSession()
     else:
         jpype.shutdownJVM()
Exemplo n.º 10
0
def sendMessage(openId, message):
    testPostUrl = 'http://test-public-txt.pingan.com.cn:10080/HMP/rest/sendMessage'
    proPostUrl = 'http://public-txt.pingan.com.cn/HMP/rest/sendMessage'
    appid = '10001862'
    secretkeyTest = '123456'
    secretkeyPrd = '49475fd41c9120f652c3284993bb8596ab34aceb'
    postUrl = testPostUrl

    timestamp = getTimestamp()
    nonce = getRandom(6)
    # 时间戳和随机数的连接串(timestamp+nonce)与共享密钥做一次HMAC-SHA1加密得到签名串
    signature = timestamp + nonce
    signature = getHmacSHA1(secretkeyTest, signature)
    while '+' in signature:
        timestamp = getTimestamp()
        nonce = getRandom(6)
        signature = timestamp + nonce
        signature = getHmacSHA1(secretkeyTest, signature)

    jvmPath = jpype.getDefaultJVMPath()
    ext_classpath = "dist/httpclient-4.5.1.jar:dist/commons-logging.jar:dist/httpcore-4.4.3.jar:dist/log4j-1.2.17.jar:"
    jvmArg = "-Djava.class.path=" + ext_classpath
    if not jpype.isJVMStarted():
        jpype.startJVM(jvmPath, jvmArg)
    javaClass = jpype.JClass('sendmessage2user.Sendmessage')
    print javaClass
    javaClass.send(postUrl, appid, timestamp, nonce, signature, openId,
                   message)
    print 'success'
    jpype.shutdownJVM()
Exemplo n.º 11
0
def TestRemote():
    dfltPath = jpype.getDefaultJVMPath()
    jpype.startJVM(dfltPath)
    # Connection refused.
    # URL = "service:jmx:rmi://localhost/jndi/rmi://localhost:1090/jmxconnector"

    # jpype._jexception.IOExceptionPyRaisable: java.io.IOException:
    # Failed to retrieve RMIServer stub: javax.naming.CommunicationException
    # [Root exception is java.rmi.NoSuchObjectException: no such object in table]
    URL = "service:jmx:rmi://localhost/jndi/rmi://localhost:52964/jmxconnector"

    #  Failed to retrieve RMIServer stub: javax.naming.CommunicationException
    # [Root exception is java.rmi.NoSuchObjectException: no such object in table]
    URL = "service:jmx:rmi:///jndi/rmi://localhost:52964/jmxrmi"

    # jpype._jexception.ClassCastExceptionPyRaisable:
    # java.lang.ClassCastException: com.sun.jndi.rmi.registry.RegistryContext cannot be cast to javax.management.remote.rmi.RMIServer
    URL = "service:jmx:rmi:///jndi/rmi://localhost:52964/"

    # Connection refused to host: localhost; nested exception is: java.net.ConnectException
    URL = "service:jmx:rmi:///jndi/rmi://localhost:1090/jmxrmi"

    # URL = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi" % (HOST, PORT)

    jmxurl = javax.management.remote.JMXServiceURL(URL)

    # "jmxurl=service:jmx:rmi:///jndi/rmi://localhost:52964/jmxrmi"
    print("jmxurl=%s" % str(jmxurl))

    # It throws here:
    jmxsoc = javax.management.remote.JMXConnectorFactory.connect(jmxurl)
    theconnection = jmxsoc.getMBeanServerConnection()

    # and you have to shutdown the VM at the end
    jpype.shutdownJVM()
Exemplo n.º 12
0
def TestLocal(listOnly):
    #jvPck = jpype.JPackage('sun').tools.attach.WindowsVirtualMachine
    jvPckVM = JPypeLocalStartJVM()

    listVMs = JPypeListVMs(jvPckVM)

    #listVMs = jvPckVM.list()
    # sys.stdout.write("VirtualMachine.dir=%s\n"%str(dir(listVMs)))
    sys.stdout.write("VirtualMachine.list:\n")
    for thePid in listVMs:
        theProcObj = listVMs[thePid]
        if listOnly:
            # Do not attach to each process.
            sys.stdout.write("    PID=%s\n" % str(thePid))
        else:
            for theKey in theProcObj:
                theVal = theProcObj[theKey]
                sys.stdout.write("\t#### %s = %s\n" % (theKey, theVal))
            JavaJmxPidMBeansAttach(thePid, jvPckVM)
            sys.stdout.write("\n")

    # For convenience, the jpype modules predefines the following JPackages : java, javax
    # They can be used as is, without needing to resort to the JPackage class.
    # This packages allows structured access to java packages and classes. It is very similar to a python import statement.
    # Only the root of the package tree need be declared with the JPackage constructor. sub-packages will be created on demand

    java.lang.System.out.println("\nHello World!!")

    # and you have to shutdown the VM at the end
    jpype.shutdownJVM()
Exemplo n.º 13
0
def set_flash(driver, base_url, project_path):
    '''
            该方法提供设置flash为允许的功能
    '''
    # 定义所需图片在项目中的位置
    picture_path = project_path + r"images\sikuli_img\chrome_set"
    # 打开flash的设置页
    driver.get("chrome://settings/content/flash")
    sleep(2)
    # 定义jvm的路径及jar的路径
    jvm_path = r"C:\Program Files\Java\jdk1.8.0_151\jre\bin\server\jvm.dll"
    jar_path = "-Djava.class.path=" + project_path + r"libs\sikulixapi.jar"
    print(jar_path)
    # 启动JVM
    jpype.startJVM(jvm_path, jar_path)
    # 得到Screen类和Pattern类
    Screen = jpype.JClass("org.sikuli.script.Screen")
    Pattern = jpype.JClass("org.sikuli.script.Pattern")
    # 实例化Screen类
    screen = Screen()
    # 先定义添加图片的路径,然后进行适当的偏移
    add_path = picture_path + r"\add.png"
    offset_Path = Pattern(add_path).targetOffset(300, 0)
    screen.click(offset_Path)
    sleep(2)
    # 输入网址
    url_path = picture_path + r"\url.png"
    screen.type(url_path, base_url)
    # 点击添加
    add_ok_path = picture_path + r"\add_ok.png"
    screen.click(add_ok_path)
    # 关闭JVM
    jpype.shutdownJVM()
    sleep(1)
Exemplo n.º 14
0
def start_spider():
    #获取任务链
    taskChainDao = TaskChainDao()
    taskChains = taskChainDao.getTaskChainList()
    tasklog = TaskLogDao()

    try:
        setting = get_project_settings()
        process = CrawlerProcess(setting)
        for taskChain in taskChains:
            chainCode = taskChain.get("TASK_CHAIN_CODE")
            #CHROME、HTML
            browseFlag = taskChain.get("TASK_CHAIN_RENDERER")
            #sql保存到数据库 file只记录文件
            saveType = taskChain.get("OUTPUT_TYPE")
            logging.warning(
                "开始执行任务链:[%s]%s,调动爬虫程序scrapy crawl %s ,并记录日志" %
                (chainCode, taskChain.get('TASK_CHAIN_NAME'), 'commonspider'))
            #记录日志
            tasklog.recodeLog(chainCode, 'progress', '')
            process.crawl('spiderjob',
                          chainCode=chainCode,
                          browse=browseFlag,
                          savetype=saveType)
            tasklog.recodeLog(chainCode, 'success', '')
        process.start(stop_after_crawl=True)

    except Exception as e:
        logging.error('爬虫程序--出现错误--', e)
    finally:
        jpype.shutdownJVM()
        process.stop()
        del process
        kill_CHROME_IDS('chrome')
Exemplo n.º 15
0
def shutdown():
    """
    关闭jvm
    :return: 无
    """
    # 关闭jvm
    jpype.shutdownJVM()
Exemplo n.º 16
0
def classGen( ) :	
	global Modifier
	root = os.path.abspath( os.path.dirname( __file__ ) )
	cp = os.path.abspath(root+"/../../build-support/jasmin.jar;"+root+"/../../_bin;"+root+"/../../_classgen")
	jpype.startJVM( jpype.getDefaultJVMPath( ), "-ea", "-Djava.class.path=%s"%cp)
	
	Modifier = jpype.JClass( "java.lang.reflect.Modifier" )
	
	try :
		# base = jpype.JClass("javax.swing.JFrame")
		base = jpype.JClass( "java.lang.Object" )
		intf = [ jpype.JClass( "java.lang.Comparable" ), 
				 #jpype.JClass("javax.swing.CellEditor"),
		]
		
		try :
			result = generateClass( "com.darkwolf.jpype.classgen.TestClass", base, intf, "../../_classgen" );

			dumpClassInformation( result );
		except :
			import traceback
			traceback.print_exc( )
			
	finally :
		jpype.shutdownJVM( )	
Exemplo n.º 17
0
def rmi_example():
    if not jpype.isJVMStarted():
        try:
            jpype.startJVM(jpype.getDefaultJVMPath(), "-ea",
                           "-Djava.class.path=/path/to/classes")
        except TypeError as ex:
            print("TypeError raised: {}.".format(ex))
        except OSError as ex:
            print("OSError raised: {}.".format(ex))

    #--------------------
    import java.rmi

    try:
        p = java.rmi.Naming.lookup("rmi://localhost:2004/server")
    except java.rmi.ConnectException as ex:
        print("java.rmi.ConnectException raised: {}.".format(ex))
        return
    print(p, p.__class__)

    p.callRemote()

    #--------------------
    if jpype.isJVMStarted():
        jpype.shutdownJVM()
Exemplo n.º 18
0
def prepare_data_sets(tag_problem_type, data_folder_path, filename,
                      morph_code_folder, dataset_file):
    dataset = []
    analyzer = TurkishMorphemeAnalyzer(morph_code_folder)

    if dataset_file == 'conll':
        sentences, labels = read_conll_file(filename)
    elif dataset_file == 'enemax':
        sentences, labels = read_enemax_file(filename)
    else:
        raise ValueError('An unexpected dataset file type!')

    for i in range(len(sentences)):
        word_list = sentences[i].split(' ')
        label_list = labels[i].split(' ')
        morpheme_list = analyzer.get_sentence_morphemes(word_list)
        dataset.append([word_list, label_list, morpheme_list])

    jp.shutdownJVM()

    index1 = int(len(dataset) * 0.8)
    index2 = int(len(dataset) * 0.9)

    shuffle(dataset)
    create_dataset_files(data_folder_path + tag_problem_type + '_train.txt',
                         dataset[:index1])
    create_dataset_files(data_folder_path + tag_problem_type + '_valid.txt',
                         dataset[index1:index2])
    create_dataset_files(data_folder_path + tag_problem_type + '_test.txt',
                         dataset[index2:])
Exemplo n.º 19
0
def seq_hss_csi_test(test_model_list, model_names, is_java=True, is_plot=True):
    if is_java:
        jd = start_jd()
    test_model_hss = {}
    test_model_csi = {}
    for i, model in enumerate(test_model_list):
        if is_java:
            hss, csi = seq_eva_hss_csi_java(model, jd)
        else:
            hss, csi = seq_eva_hss_csi(test_root,
                                       os.path.join(evaluate_root, model))
        test_model_hss[model] = hss
        test_model_csi[model] = csi
        mean_hss = np.mean(hss, 0)
        mean_csi = np.mean(csi, 0)
        print('The hss and csi of "', model_names[i], '" is: ')
        print(hss.shape, mean_hss)
        print(csi.shape, mean_csi)
        print()

    if is_plot:
        plot_seq_hss_or_csi(test_model_hss, test_model_list, model_names,
                            'HSS')
        plot_seq_hss_or_csi(test_model_csi, test_model_list, model_names,
                            'CSI')

    if is_java:
        jpype.shutdownJVM()

    return test_model_hss, test_model_csi
Exemplo n.º 20
0
def classGen():
    global Modifier
    root = os.path.abspath(os.path.dirname(__file__))
    cp = os.path.abspath(root + "/../../build-support/jasmin.jar;" + root +
                         "/../../_bin;" + root + "/../../_classgen")
    jpype.startJVM(jpype.getDefaultJVMPath(), "-ea",
                   "-Djava.class.path=%s" % cp)

    Modifier = jpype.JClass("java.lang.reflect.Modifier")

    try:
        # base = jpype.JClass("javax.swing.JFrame")
        base = jpype.JClass("java.lang.Object")
        intf = [
            jpype.JClass("java.lang.Comparable"),
            #jpype.JClass("javax.swing.CellEditor"),
        ]

        try:
            result = generateClass("com.darkwolf.jpype.classgen.TestClass",
                                   base, intf, "../../_classgen")

            dumpClassInformation(result)
        except:
            import traceback
            traceback.print_exc()

    finally:
        jpype.shutdownJVM()
Exemplo n.º 21
0
def make_java_task(num_calcs):
    if not jpype.isJVMStarted():
        jpype.startJVM(jpype.getDefaultJVMPath(), 
                       "-d log4j.debug")

    res = jpype.JInt(num_calcs)
    jpype.shutdownJVM()
    return res
Exemplo n.º 22
0
def runTest():
    runner = unittest.TextTestRunner()
    result = runner.run(suite())

    if jpype.isJVMStarted():
        jpype.shutdownJVM()
    if not result.wasSuccessful():
        sys.exit(1)
Exemplo n.º 23
0
def teardown():
    """Everything we need to do AFTER the tests are run"""
    try:
        os.remove(config.TEST_DB_PATH + config.TEST_DB_NAME)  # Delete the test database file
        os.remove(TEST_FILES_DIR + 'random_data.csv')         # Delete csv fake file
        jpype.shutdownJVM()                                   # Shut down the JVM
    except BaseException:
        pass
Exemplo n.º 24
0
    def __exit__(self, ex, value, tb):
        jpype.shutdownJVM()
        logger.info("JVM shut down")
        self.started = False

        if ex is not None:
            logger.exception("Exception while calling OpenRocket",
                             exc_info=(ex, value, tb))
Exemplo n.º 25
0
def __get_post__():

    jpype.startJVM("C:/Program Files/Java/jre7/bin/server/jvm.dll", "-ea")
    javaPackage = jpype.JPackage("use_facebook4j")
    javaClass = javaPackage.Main
    javaObject = javaClass()
    javaObject.main()
    jpype.shutdownJVM()
Exemplo n.º 26
0
def runTest() :
    runner = unittest.TextTestRunner()
    result = runner.run(suite())

    if jpype.isJVMStarted():
        jpype.shutdownJVM()
    if not result.wasSuccessful():
        sys.exit(1)
Exemplo n.º 27
0
def stop():
    """
    Stops the JVM.
    
    :return: True if the JVM has been stopped, else False
    """
    # Stop the JVM
    jpype.shutdownJVM()
Exemplo n.º 28
0
def __on_close():
    """
    退出时执行的方法
    :return:
    """
    try:
        jpype.shutdownJVM()
    except Exception as e:
        logger.warn(e)
Exemplo n.º 29
0
    def __exit__(self, ty, value, tb):

        jpype.shutdownJVM()

        if not ty is None:
            print("Exception while calling openrocket")
            print("Exception info : ", ty, value, tb)
            print("Traceback : ")
            traceback.print_exception(ty, value, tb)
Exemplo n.º 30
0
 def run_analysis(self):
     jp.startJVM(jp.getDefaultJVMPath(),
                 "-Djava.class.path=%s/lib/" % os.path.abspath("."),
                 "-Djava.class.path=%s/ffdec.jar" % os.path.abspath("."))
     self.parser = jp.JClass('com.jpexs.decompiler.flash.gui.Main')
     self.log_obj.logger.info("Analyzing files...")
     self.analyze_paths()
     self.log_obj.logger.info("Analysis complete.")
     jp.shutdownJVM()
Exemplo n.º 31
0
 def get_secret(cls, msg):
     import jpype
     jvmPath = jpype.getDefaultJVMPath()
     jpype.startJVM(jvmPath, '-Djava.class.path=D:/woniuboss-decode.jar')
     javaclass = jpype.JClass('com.woniuxy.des.DESede')
     des = javaclass()
     decode = des.decryptMode(msg)
     jpype.shutdownJVM()
     return decode
Exemplo n.º 32
0
def dis_connection():
    try:
        #print(f'* jpype.isJVMStarted()= > {jpype.isJVMStarted()}')
        if jpype.isJVMStarted():
            print('=== shutdown JVM===')
            jpype.shutdownJVM()
    except Exception as ex:
        print(ex)
        traceback.print_exc()
        raise RuntimeError(ex)
Exemplo n.º 33
0
    def testShutdown(self):
        # Install a coverage hook
        instance = JClass("org.jpype.JPypeContext").getInstance()
        JClass("jpype.common.OnShutdown").addCoverageHook(instance)

        # Shutdown
        jpype.shutdownJVM()

        # Check that shutdown does not raise
        jpype._core._JTerminate()
Exemplo n.º 34
0
 def __init__(self):
     jarpath = os.path.join(os.path.abspath('.'), './')
     jvmpath = jpype.getDefaultJVMPath()
     #jvmpath='/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/server/libjvm.dylib'
     if jpype.isJVMStarted() > 0:
         jpype.shutdownJVM()
     else:
         jpype.startJVM(jvmpath, "-ea",
                        "-Djava.class.path=%s" % (jarpath + "testP.jar"))
     self.Jcls = jpype.JPackage("com.zznode.utils").DESDecryptCoder()
Exemplo n.º 35
0
def AnotherTest():
    # Installed with "pip install JPype1"
    import jpype
    jpype.startJVM(jpype.getDefaultJVMPath())

    # you can then access to the basic java functions
    jpype.java.lang.System.out.println("hello world")

    # and you have to shutdown the VM at the end
    jpype.shutdownJVM()
Exemplo n.º 36
0
    def stop(self):
        """
        Stops the JVM.

        :return: True if the JVM has been stopped, else False
        """
        if self._jvm_running:
            # Update the presence flag
            self._jvm_running = False

            # Stop the JVM
            jpype.shutdownJVM()
Exemplo n.º 37
0
    def close():
        if self.Analyzer == None:
            return

        self.Analyzer.close()

        global analyzerActive
        analyzerActive -= 1

        if analyzerActive == 0:
            java.shutdownJVM()

            self.onJVMshutdown()
Exemplo n.º 38
0
 def cleanup(self):
     '''
     This model is called after finishing all the experiments, but 
     just prior to returning the results. This method gives a hook for
     doing any cleanup, such as closing applications. 
     
     In case of running in parallel, this method is called during 
     the cleanup of the pool, just prior to removing the temporary 
     directories. 
     
     '''
     self.netlogo.kill_workspace()
     jpype.shutdownJVM()
Exemplo n.º 39
0
 def __shutdownJVM(self):
   """
   Shuts down the Java Virtual Machine
   """
   
   if self._globJVMOn:
     jpype.shutdownJVM()
     
     self._globJVMOn = False
     self._globJVMSymm = None
     Messages.log(__name__, "JVM shut down!", verbose=1)
     
     self._deleteJVMOutputFiles()
Exemplo n.º 40
0
def InitJPypeJVM():
	# if(jpyejvm):
	# 	print "jvm is already running"
	# 	jpyejvm = jpype.attachToJVM()
	# else:
    print "init jvm for jpype"
    try:
        jpyejvm = jpype.startJVM(jvmPath)
    except Exception, e:
        print e
        jpype.shutdownJVM();
        jpyejvm = jpype.startJVM(jvmPath)
    
	print "JVM is started"
Exemplo n.º 41
0
def runTest() :	
	root = os.path.abspath(os.path.dirname(__file__))

	print "Running testsuite using JVM", jpype.getDefaultJVMPath()
	jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Xmx256M", "-Xms64M",
				   "-Djava.class.path=./classes%s%s%sclasses" % (os.pathsep, root, os.sep))

	runner = unittest.TextTestRunner()
	runner.run(suite())
	
	s = slice(2, 4)
	print s, dir(s)
	
	jpype.shutdownJVM()	
Exemplo n.º 42
0
 def __shutdownJVM(self):
   """
   Shuts down the Java Virtual Machine.
   
   """
   
   if self._globJVMOn:
     jpype.shutdownJVM()
     
     self._globJVMOn = False
     self._globJVMJar = None
     
     messages.log(__name__, "JVM shut down!", verbose=1)
     
     self._clearJVMOutputFiles()
Exemplo n.º 43
0
def main():
    jpype.startJVM("/usr/lib/jvm/java-6-sun/jre/lib/i386/server/libjvm.so","-Djava.endorsed.dirs=" + JMXREMOTEPATH)
    jmxurl = jpype.javax.management.remote.JMXServiceURL(URL)
    jhash = jpype.java.util.HashMap()
    jmxsoc = jpype.javax.management.remote.JMXConnectorFactory.connect(jmxurl,jhash)
    connection = jmxsoc.getMBeanServerConnection()

    if len(sys.argv) == 1:
        for name in connection.queryNames(None,None):
            print str(name)
    #        showName(connection,name)
    elif len(sys.argv) == 2:
        name=jpype.javax.management.ObjectName(sys.argv[1])
        showName(connection,name)

    jpype.shutdownJVM()
Exemplo n.º 44
0
def runTest() :
	root = os.path.abspath(os.path.dirname(__file__))

	print(("Running testsuite using JVM: {0}".format(jpype.getDefaultJVMPath())))
	jpype.startJVM(jpype.getDefaultJVMPath(),
				   "-ea", "-Xmx256M", "-Xms64M",
				   "-Djava.class.path={0}" \
				   .format(os.path.join(root, "classes")))

	runner = unittest.TextTestRunner()
	runner.run(suite())

	s = slice(2, 4)
	print("{0} {1}".format(s, dir(s)))

	jpype.shutdownJVM()
Exemplo n.º 45
0
    def stop(self):
        """Method stops JVM

        Args:
           none

        Returns:
           bool: result

        Raises:
           event: java_before_stop
           event: java_after_stop        

        """

        try:

            if (not self._status):
                self._mh.demsg('htk_on_warning', self._mh._trn.msg(
                    'htk_java_not_started'), self._mh.fromhere())
                return False

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_java_stopping_jvm'), self._mh.fromhere())
            ev = event.Event('java_before_stop')
            self._mh.fire_event(ev)

            shutdownJVM()
            self._status = False
            result = True

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_java_stopped'), self._mh.fromhere())
            ev = event.Event('java_after_stop')
            self._mh.fire_event(ev)

            return result

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None
Exemplo n.º 46
0
def get_faacets_moment_matrix(A_configuration, B_configuration, coefficients):
    from jpype import startJVM, shutdownJVM, JPackage, getDefaultJVMPath, JArray, JDouble
    # find the JAR file and start the JVM
    jarFiles = glob.glob('faacets-*.jar')
    assert len(jarFiles) == 1
    jarFile = os.path.join(os.getcwd(), jarFiles[0])
    startJVM(getDefaultJVMPath(), "-Djava.class.path="+jarFile)
    com = JPackage('com')

    # main code
    sc = com.faacets.Core.Scenario(configuration_to_faacets(A_configuration, B_configuration))
    representation = com.faacets.Core.Representation('NCRepresentation')
    ope = com.faacets.SDP.OperatorElements(['', 'A', 'AB'])
    pts = com.faacets.SDP.PartialTransposes([])
    vec = com.faacets.Core.QVector(JArray(JDouble)(coefficients))
    expr = com.faacets.Core.Expr(sc, representation, vec)
    sdp = com.faacets.SDP.CorrSDP(sc, ope, pts, expr.symmetryGroup())
    M = np.array(sdp.indexArray())
    ncIndices = np.array(sdp.ncIndices())
    shutdownJVM()
    return M, ncIndices
Exemplo n.º 47
0
 def close(self):
     jpype.shutdownJVM()
 def __exit__(self, exc_type, exc_val, exc_tb):
     jpype.shutdownJVM()
Exemplo n.º 49
0
 def stop(self):
     jp.shutdownJVM()
     self._exit.set()
Exemplo n.º 50
0
def shutdown_java():
    jpype.shutdownJVM()
Exemplo n.º 51
0
 def __del__(self):
     jpype.shutdownJVM()
Exemplo n.º 52
0
def teardown_package():
    """
    Stops the JVM use in tests
    """
    # Stop the JVM
    jpype.shutdownJVM()
Exemplo n.º 53
0
def shutdown():
	# NOTE: jpype says this function doesn't even work for most JVMs
	# I guess we'll just include it anyway, for completeness' sake
	jpype.shutdownJVM()
Exemplo n.º 54
0
def destroy_env():
    if jpype.isJVMStarted():
        jpype.shutdownJVM()
Exemplo n.º 55
0
import os
from jpype import *
import jpype

jarpath = os.path.join(os.path.abspath('.'), 'E:/du2.jar')
dependency = os.path.join(os.path.abspath('.'), 'E:/')
jpype.startJVM('C:/Program Files (x86)/Charles/jre/bin/client/jvm.dll', "-ea", "-Djava.class.path=%s" %jarpath)
JClass = jpype.JClass('com.shine.support.utils.aq')
instance = JClass()
result = instance.search(5,20)
print(result)
jpype.shutdownJVM()
Exemplo n.º 56
0
def constructDMatrix(data, distanceSetup={}):
    """ 
    
    Constructs a n-by-n matrix of distances for n data-series in data 
    according to the specified distance
    
    distance argument specifies the distance measure to be used. Options, 
    which are defined in distances.py, are as follows;
    
    * gonenc: a distance based on qualitative dynamic pattern features 
    * willem: a disance mainly based on the presence of crisis-periods and 
              the overall trend of the data series
    * sse: regular sum of squared errors
    * mse: regular mean squared error
    
    others will be added over time
    
    """

    global runLogs    
    noSeries = len(data)
    
    # Sets up the distance function according to user specification
    if 'distance' in distanceSetup.keys():
        distance = distanceSetup['distance']
    else:
        distance = 'gonenc'
    distFunc = getattr(distances, "distance_%s" %distance)
    
    #dMatrix = []   
    dMatrix = np.zeros((noSeries,noSeries),dtype=float)
    if distance == 'gonenc':
    # gonenc-distance requires interfacing with the java class JavaDistance
    # Java version will be phased out, and it will be migrated into python as 
    # other distance functions
        try:
            javap.startJVM(javap.getDefaultJVMPath())
            print 'started jvm'
        except:
            print "cannot start jvm: try to find jvm.dll"
#           jpype.startJVM(r'C:\Program Files (x86)\Java\jdk1.6.0_22\jre\bin\client\jvm.dll')
        g_dist = javap.JClass('JavaDistance')
        dist = g_dist()
        
        # Checks the parameters of the distance function that may be defined by the user in the distanceSetup dict
        if 'filter?' in distanceSetup.keys():
            dist.setWithFilter(distanceSetup['filter?'])
        if 'slope filter' in distanceSetup.keys():
            dist.setSlopeFilterThold(distanceSetup['slope filter'])
        if 'curvature filter' in distanceSetup.keys():
            dist.setCurvatureFilterThold(distanceSetup['curvature filter'])
        if 'no of sisters' in distanceSetup.keys():
            dist.setSisterCount(distanceSetup['no of sisters'])
                
        # Calculate the distances and fill in the distance matrix. 
        # i is the index for each run, and is in sync with the indexing used in 
        # the cases, and results output structures.
        runLogs = []
        for i in range(noSeries):
            #dMatrix.append([])
            
            # For each run, a log is created
            # Log includes a description dictionary that has key information 
            # for post-clustering analysis, and the data series itself. These 
            # logs are stored in a global array named runLogs
            behaviorDesc = {}
            behaviorDesc['Index'] = str(i)
            featVector = dist.getFeatureVector(data[i]) #this may not work due to data type mismatch
            
            behaviorDesc['Feature vector'] = str(featVector)
            behavior = data[i]
            localLog = (behaviorDesc, behavior)
            runLogs.append(localLog)
          
            for j in range(noSeries):
                dMatrix[i,j]=dist.distance(data[i],data[j])
                #dMatrix[i].append(dist.distance(data[i], data[j]))
        javap.shutdownJVM()   
    elif distance == "willem":
        try:
            javap.startJVM(javap.getDefaultJVMPath())
        except:
            print "cannot start jvm: try to find jvm.dll"
#           jpype.startJVM(r'C:\Program Files (x86)\Java\jdk1.6.0_22\jre\bin\client\jvm.dll')
        w_dist = javap.JClass('WillemDistance')
        dist = w_dist()
        runLogs = []
        for i in range(noSeries):
            #dMatrix.append([])
            
            # For each run, a log is created
            # Log includes a description dictionary that has key information for post-clustering analysis, and the data series itself
            # These logs are stored in a global array named runLogs
            behaviorDesc = {}
            behaviorDesc['Index'] = str(i)
            featVector = dist.getFeatureVector(data[i]) #this may not work due to data type mismatch
            behaviorDesc['Feature vector'] = str(featVector)
            behavior = data[i]
            localLog = (behaviorDesc, behavior)
            runLogs.append(localLog)
          
            for j in range(noSeries):
                dMatrix[i,j]=dist.distance(data[i],data[j])
                #dMatrix[i].append(dist.distance(data[i], data[j]))
        javap.shutdownJVM()      
    
    else:    
        for i in range(noSeries):
            #dMatrix.append([])
            
            # For each run, a log is created
            # Log includes a description dictionary that has key information for post-clustering analysis, and the data series itself
            # These logs are stored in a global array named runLogs
            behaviorDesc = {}
            behaviorDesc['Index'] = i
            behavior = data[i]
            localLog = (behaviorDesc, behavior)
            runLogs.append(localLog)
            
            for j in range(noSeries):
                dMatrix[i,j]=dist.distance(data[i],data[j])
                #dMatrix[i].append(distFunc(data[i], data[j])) 
    return dMatrix
Exemplo n.º 57
0
 def shutdown_jvm(self):
     jpype.shutdownJVM()
Exemplo n.º 58
0
def jpypeTester():
    javap.startJVM(javap.getDefaultJVMPath())
    javap.java.lang.System.out.println("Deneme")
    javap.shutdownJVM()               
Exemplo n.º 59
0
def stop_JVM():
	jpype.shutdownJVM()
Exemplo n.º 60
0
        _ = atts.item(i)
        # a = atts.item(i)
        # print(' {0}="{1}"'.format(a.getNodeName(), a.getNodeValue()), end='')

    # print('>')

    nl = el.getChildNodes()
    for i in range(nl.getLength()):
        output(nl.item(i), prefix + "  ")

        # print("{0}</{1}>".format(prefix, el.getTagName()))


# Compute the XML file path
xml_file = os.path.join(os.path.dirname(__file__), "sample", "big.xml")

t1 = time.time()
count = 30
for i in range(count):
    build = javax.xml.parsers.DocumentBuilderFactory.newInstance() \
        .newDocumentBuilder()
    doc = build.parse(xml_file)

    el = doc.getDocumentElement()
    output(el)

t2 = time.time()
print(count, "iterations in", t2 - t1, "seconds")

shutdownJVM()