示例#1
0
 def _start_jvm(cls, jvm_path, jvm_options, driver_path):
     if jvm_path is None:
         jvm_path = jpype.get_default_jvm_path()
     if driver_path is None:
         driver_path = os.path.join(
             os.path.dirname(os.path.abspath(__file__)), ATHENA_JAR)
     if not jpype.isJVMStarted():
         _logger.debug('JVM path: %s', jvm_path)
         args = ['-server', '-Djava.class.path={0}'.format(driver_path)]
         if jvm_options:
             args.extend(jvm_options)
         _logger.debug('JVM args: %s', args)
         jpype.startJVM(jvm_path, *args)
         cls.class_loader = jpype.java.lang.Thread.currentThread(
         ).getContextClassLoader()
     if not jpype.isThreadAttachedToJVM():
         jpype.attachThreadToJVM()
         if not cls.class_loader:
             cls.class_loader = jpype.java.lang.Thread.currentThread(
             ).getContextClassLoader()
         class_loader = jpype.java.net.URLClassLoader.newInstance(
             [jpype.java.net.URL('jar:file:{0}!/'.format(driver_path))],
             cls.class_loader)
         jpype.java.lang.Thread.currentThread().setContextClassLoader(
             class_loader)
示例#2
0
def start_jvm():

    if not jpype.isJVMStarted():
        jpype.startJVM(jpype.get_default_jvm_path(), '-Dfile.encoding=UTF8',
                       '-ea', '-Xmx1024m')

    if not jpype.isThreadAttachedToJVM():
        jpype.attachThreadToJVM()

    global classpath_added
    if not classpath_added:
        add_classpaths([
            f'{os.path.dirname(__file__)}/java/{lib}' for lib in [
                'poi-3.17.jar',
                'poi-excelant-3.17.jar',
                'poi-ooxml-3.17.jar',
                'poi-ooxml-schemas-3.17.jar',
                'poi-scratchpad-3.17.jar',
                'lib/commons-codec-1.10.jar',
                'lib/commons-collections4-4.1.jar',
                'lib/commons-logging-1.2.jar',
                'lib/log4j-1.2.17.jar',
                'ooxml-lib/xmlbeans-2.6.0.jar',
                'ooxml-lib/curvesapi-1.04.jar',
            ]
        ])
        classpath_added = True
示例#3
0
    def run(self):
        # cpopt = "-Djava.class.path=%s" % './java_classes'
        jpype.startJVM(
            jpype.get_default_jvm_path(), '-ea',
            '-Djava.class.path=/Users/dawan/PycharmProjects/mamoc_server/java_classes'
        )

        # print(jpype.get_default_jvm_path())

        # hey = jpype.java.lang.System.out.println("hello world")
        # print(hey)

        # testPkg = jpype.JPackage('uk').standrews.cs.mamoc

        quick = jpype.JClass("QuickSort")

        tic = time.time()

        text_file = "./data/" + "medium" + ".txt"
        with open(text_file, "r") as file:
            content = file.read().split(" ")

        quick.quickSort(content)  # uk.ac.standrews.cs.mamoc.NQueens

        duration = time.time() - tic
        print(duration)

        return duration
 def _start_jvm(cls, jvm_path, jvm_options, driver_path, log4j_conf):
     if jvm_path is None:
         jvm_path = jpype.get_default_jvm_path()
     if driver_path is None:
         driver_path = os.path.join(cls._BASE_PATH, ATHENA_JAR)
     if log4j_conf is None:
         log4j_conf = os.path.join(cls._BASE_PATH, LOG4J_PROPERTIES)
     if not jpype.isJVMStarted():
         _logger.debug('JVM path: %s', jvm_path)
         args = [
             '-server',
             '-Djava.class.path={0}'.format(driver_path),
             '-Dlog4j.configuration=file:{0}'.format(log4j_conf)
         ]
         if jvm_options:
             args.extend(jvm_options)
         _logger.debug('JVM args: %s', args)
         if jpype.__version__.startswith("0.6"):
             jpype.startJVM(jvm_path, *args)
         else:
             jpype.startJVM(jvm_path, *args, ignoreUnrecognized=True, convertStrings=True)
         cls.class_loader = jpype.java.lang.Thread.currentThread().getContextClassLoader()
     if not jpype.isThreadAttachedToJVM():
         jpype.attachThreadToJVM()
         if not cls.class_loader:
             cls.class_loader = jpype.java.lang.Thread.currentThread().getContextClassLoader()
         class_loader = jpype.java.net.URLClassLoader.newInstance(
             [jpype.java.net.URL('jar:file:{0}!/'.format(driver_path))],
             cls.class_loader)
         jpype.java.lang.Thread.currentThread().setContextClassLoader(class_loader)
示例#5
0
def init_jvm():
    jvm_path = jpype.get_default_jvm_path()
    file_path = os.path.dirname(os.path.realpath(__file__))
    jars_path = os.path.join(file_path, 'jars')
    jars = [os.path.join(jars_path, f) for f in os.listdir(jars_path)]
    jpype.startJVM(jvm_path,
                   '-Djava.class.path={}'.format(os.pathsep.join(jars)),
                   '-Dfile.encoding=UTF8', '-ea')
示例#6
0
    def __init__(self, gui=False, thd=False, netlogo_home=None,
                 netlogo_version=None, jvm_home=None):
        '''

        Create a link with NetLogo. Underneath, the NetLogo JVM is started
        through Jpype.


        :param gui: boolean, if true run NetLogo with gui, otherwise run in 
                    headless mode. Defaults to false.
        :param thd: boolean, if true start NetLogo in 3d mode. Defaults to 
                    false
        :param nl_dir: string - full path to NetLogo .exe directory, use if
                    NetLogo is not in the default location
        :param nl_version: string - NetLogo version under nl_dir (5.2 or 6.0)

        '''
        if not netlogo_home:
            netlogo_home = get_netlogo_home()
        if not netlogo_version:
            netlogo_version = establish_netlogoversion(netlogo_home)
        if not jvm_home:
            jvm_home = jpype.get_default_jvm_path()

        if not jpype.isJVMStarted():
            jars = find_jars(netlogo_home)
            jars.append(os.path.join(PYNETLOGO_HOME,
                                     'java', 'netlogoLink_combined.jar'))
            joined_jars = jar_sep[sys.platform].join(jars)
            jarpath = '-Djava.class.path={}'.format(joined_jars)
            try:
                debug("starting jvm: {} {}".format(jvm_home, jarpath))
                jpype.startJVM(jvm_home, jarpath)
                debug("JVM started")
            except RuntimeError as e:
                warning('failed to start JVM using jvm_home')
                raise e
            #jpype.java.lang.System.setProperty('user.dir', netlogo_home)
            if sys.platform == 'darwin':
                debug('set state to headless on mac os')
                jpype.java.lang.System.setProperty("java.awt.headless", "true")

        try:
            link = jpype.JClass(module_name[netlogo_version])
        except Exception as e:
            ema_logging.warning(
                "can't find class for netlogo version"+netlogo_version)
            raise e
        debug('NetLogoLink class found')

        if sys.platform == 'darwin' and gui:
            info('on mac only Headless mode is supported')
            gui = False

        self.link = link(jpype.java.lang.Boolean(gui),
                         jpype.java.lang.Boolean(thd))
        debug('NetLogoLink class instantiated')
    def __init__(self, host="localhost", port=1099, debug=False,
                 output_channel=None):
        self.host = host
        self.port = port
        self.url = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi" % (host, port)
        self.debug = debug
        self.mbean = None
        self.output_channel = output_channel
        jpype.startJVM(jpype.get_default_jvm_path())
        if debug:
            self.__print_to_ouput_channel("JVM loaded")
            self.__print_to_ouput_channel(jpype.get_default_jvm_path())

        jmx_url = javax.management.remote.JMXServiceURL(self.url)
        jmx_soc = javax.management.remote.JMXConnectorFactory.connect(
            jmx_url, java.util.HashMap())
        self.connection = jmx_soc.getMBeanServerConnection()
        if self.debug:
            self.__print_to_ouput_channel("Connection successful")
示例#8
0
def SelectRegion():

    jvmPath = jpype.get_default_jvm_path()

    jpype.startJVM(jvmPath, '-ea', '-Djava.class.path=F:\\sikuli\\1\\sikulixapi.jar') #加载jar包路径

    Screen = jpype.JClass('org.sikuli.script.Screen')

    myscreen = Screen()

    region = myscreen.selectRegion() # 自定义获取屏幕范围

    return region
示例#9
0
 def __init__(self):
     if self.__first_init:
         jar_path = os.path.dirname(
             __file__
         ) + os.sep + '..' + os.sep + '..' + os.sep + "testdata" + os.sep + 'jarfile_dir' + os.sep + 'rsa.jar'
         jvm_arg = "-Djava.class.path=%s" % jar_path
         if not jpype.isJVMStarted():
             jpype.startJVM(jpype.get_default_jvm_path(), "-ea", jvm_arg)
         if not jpype.isThreadAttachedToJVM():
             jpype.attachThreadToJVM()
         import time
         time.sleep(0.5)
         JDClass = jpype.JClass("dj.RSATool")
         self.jd = JDClass()
示例#10
0
 def _start_jvm(cls, jvm_path, jvm_options, driver_path):
     if jvm_path is None:
         jvm_path = jpype.get_default_jvm_path()
     if driver_path is None:
         driver_path = os.path.join(os.path.dirname(__file__), ATHENA_JAR)
     if not jpype.isJVMStarted():
         _logger.debug('JVM path: %s', jvm_path)
         args = ['-server', '-Djava.class.path={0}'.format(driver_path)]
         if jvm_options:
             args.extend(jvm_options)
         _logger.debug('JVM args: %s', args)
         jpype.startJVM(jvm_path, *args)
     if not jpype.isThreadAttachedToJVM():
         jpype.attachThreadToJVM()
示例#11
0
def Main():
    jvmPath = jpype.get_default_jvm_path()
    jarpath = "F:\\sikuli\\sikulixapi.jar"
    classpath = "-Djava.class.path=" + jarpath
    jpype.startJVM(jvmPath, classpath)
    print("初始化JAVA虚拟机".center(50, "*"))
    fighting = Fighting()
    playnum = 1
    while playnum <= 4:
        fighting.gotoRoom()
        fighting.entry()
        fighting.autoattack()
        fighting.resolve()
        fighting.choosePlay()
        playnum += 1
    jpype.shutdownJVM()
    print("关闭JAVA虚拟机".center(50, "*"))
示例#12
0
    def build_and_start_jvm(self,
                            maven_dir: str,
                            code_dir: str,
                            root_package: str,
                            jvm_path=None):
        # Needs to be done here to work with setuptools setup_requires
        # (otherwise imported before that line is even read)
        import jpype
        if jvm_path is None:
            jvm_path = jpype.get_default_jvm_path()
        _logger.debug('generating classpath in {}'.format(maven_dir))

        pom_path = os.path.join(maven_dir, 'pom.xml')

        self._generate_full_pom(pom_path)
        maven_completion = subprocess.run(
            ['mvn', '-DskipTests=true', 'assembly:assembly'], cwd=maven_dir)

        maven_completion.check_returncode()

        for jar in os.listdir(os.path.join(maven_dir, 'target')):
            if jar.endswith('jar-with-dependencies.jar'):
                full_path = os.path.join(maven_dir, 'target', jar)
                _logger.debug('adding {} to classpath'.format(full_path))
                jpype.addClassPath(full_path)

        jpype.startJVM(jvm_path,
                       "-Djava.class.path=%s" % jpype.getClassPath(),
                       convertStrings=False)

        # TODO: generate pxi files for all classes on classpath. Needs to be done after build
        # - generate python type-hinted classes
        # - store them next to jar
        # - put them on sys.path
        PyiUtils = jpype.JClass(
            'org.matsim.contrib.pythonmatsim.typehints.PyiUtils')

        try:
            PyiUtils.generatePythonWrappers(code_dir, root_package)
        except jpype.JException as e:
            print(e.message())
            print(e.stacktrace())
            raise e

        _logger.debug('done generating classpath')
示例#13
0
def start_jvm(jvm_path=jpype.get_default_jvm_path(),
              *additional_classpath):
    if not pkg_resources.resource_exists('javaresources', 'python-matsim-instance-1.0-SNAPSHOT-jar-with-dependencies.jar'):
        raise RuntimeError('could not find jar file')

    if jpype.isJVMStarted():
        # TODO: check that classpath etc. are the ones we want
        _logger.info("JVM is already live, do nothing.")
        return

    python_matsim_jar = pkg_resources.resource_filename('javaresources', 'python-matsim-instance-1.0-SNAPSHOT-jar-with-dependencies.jar')

    jpype.addClassPath(python_matsim_jar)

    for jar in additional_classpath:
        jpype.addClassPath(jar)

    _logger.info('start jvm with classpath {}'.format(jpype.getClassPath()))

    jpype.startJVM(jvm_path, "-Djava.class.path=%s" % jpype.getClassPath(), convertStrings=False)
示例#14
0
    def __init__(self, jvm_path=None, classpath=None):
        """Class constructor

        Called when the object is initialized

        Args:                   
           jvm_path (str): JVM location, default from configuration
           classpath (str): Java classpath, default from configuration

        """

        self._mh = MasterHead.get_head()
        self._mh.find_module('hydratk.lib.bridge.java', None)

        if (jvm_path != None):
            self._jvm_path = jvm_path
        else:
            cfg = self._mh.cfg['Libraries']['hydratk.lib.bridge.java']['jvm_path']
            self._jvm_path = cfg if (cfg != 'default') else get_default_jvm_path()

        self._classpath = self._set_classpath(classpath)
示例#15
0
class IndexHandler(tornado.web.RequestHandler):

    default_jvm_path = jpype.get_default_jvm_path()

    if not jpype.isJVMStarted():
        jpype.startJVM(default_jvm_path,
                       "-Djava.class.path=SugestWord-1.0-SNAPSHOT.jar")
    SuggestWord = jpype.JClass("xxx.alphax.suggest.SuggestWord")
    suggestWord = SuggestWord()
    print 'suggest word load is ok...'

    def get(self):
        self.render('index.html')

    def post(self):
        searchKey = self.get_argument("searchKey")
        keyWords = self.suggestWord.getNextSuggestWord(searchKey)
        if keyWords:
            keyWords = ';'.join(list(keyWords))
        else:
            keyWords = ''
        self.write(keyWords)
示例#16
0
 def testJVMPathDepecated(self):
     jpype.get_default_jvm_path()
示例#17
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2019-04-15 15:49
@Author  : zhangyu
@Contact : [email protected]
@File    : tabula_pdf_parser.py
@Software: PyCharm
@Site    : https://github.com/zhangyuo
"""
import tabula
from jpype import get_default_jvm_path

jvm_path = get_default_jvm_path()

df = tabula.read_pdf(
    "/Users/zhangyu/Downloads/2015年陕西省财政预算执行情况和2016年财政预算(草案).pdf",
    encoding='utf-8',
    pages='all')
print(df)
for indexs in df.index:
    print(df.loc[indexs].values[1].strip())

# tabula.convert_into(u"/Users/zhangyu/Downloads/2017年陕西省财政预算执行情况和2018年财政预算(草案).pdf", '/Users/zhangyu/Downlodas/1.csv', all)
示例#18
0
import sys
#sys.path.append('/Users/pradap/Documents/Research/Python-Package/enrique')
#sys.path.append('/scratch/pradap/python-work/enrqiue')
import os
import magellan as mg
import jpype
p = mg.get_install_path()
path_for_A = os.sep.join([p, 'datasets', 'table_A.csv'])
path_for_B = os.sep.join([p, 'datasets', 'table_B.csv'])
# mg.init_jvm('/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/lib/server/libjvm.dylib')
jvm_path = jpype.get_default_jvm_path()
if os.path.isfile(jvm_path):
    mg.init_jvm(jvm_path)
    #mg.init_jvm('/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/lib/server/libjvm.dylib')
else:
    x = []
    for t in jvm_path.split(os.sep):
        if t == 'client':
            t = 'server'
        elif t == 'server':
            r = 'client'
        x.append(t)
    jp = os.sep.join(x)
    if os.path.isfile(jp):
        mg.init_jvm(jp)
    else:
        jp = raw_input('Give path to jvm library (i.e libjvm.so in linux) : ')
        if os.path.isfile(jp):
            mg.init_jvm(jp)
        else:
            print 'Invalid path; cannot run tests; exiting'
from Helper import ParagraphToSentences, AllfilesInFolder, MongoDB, SemanticClass
import jpype as jp
from tqdm import tqdm

kparser_path = "E:\Documents\ASU\CSE_576_NLP\Project\KParser\kparser.jar"

try:
    x = jp.startJVM(jp.get_default_jvm_path(), "-ea",
                    "-Djava.class.path=%s" % kparser_path)
except:
    pass
classLoader = jp.java.lang.ClassLoader.getSystemClassLoader()
mgClass = jp.JClass("module.graph.MakeGraph")


def splitNodevalue(value):
    currentNodeValueTokens = value.split("-")
    return currentNodeValueTokens[0]


def classExits(srTemp, semanticRoles):
    for semanticRole in semanticRoles:
        if srTemp.root == semanticRole.root and srTemp.properties == semanticRole.properties:
            return True
    return False


def sematic_extraction(nd, semanticRoles):
    edgeList = nd.getEdgeList()
    children = nd.getChildren()
    properties = {}
示例#20
0
    print('开始初始化......')
    print('开始检测appium server是否可用......')
    try:
        doRquest=DoRequest(Read_APP_UI_Config().app_ui_config.appium_hub)

        httpResponseResult=doRquest.get('/status')
        result=json.loads(httpResponseResult.body)
        if result['status']==0:
            print('appium server状态为可用......')
        else:
            sys.exit('appium server状态为不可用')
    except:
        sys.exit('appium server状态为不可用')

    print('启动jvm......')
    jpype.startJVM(jpype.get_default_jvm_path(),"-ea","-Djava.class.path="+JavaTool.getAllJar())
    print('启动jvm成功')

    java_maven_init()

    print('初始化android基础数据......')
    android_init()
    print('初始化android基础数据完成......')

    print('初始化ios基础数据......')
    ios_init()
    print('初始化ios基础数据完成......')

    print('初始化windows基础数据......')
    windows_init()
    print('初始化windows基础数据完成......')
示例#21
0
def init_jvm():
    jvm_path = jpype.get_default_jvm_path()
    jpype.startJVM(jvm_path, '-Djava.class.path={}'.format(os.path.join(file_path, JAR_FILE)), '-Dfile.encoding=UTF8', '-ea')
示例#22
0
 def __init__(self):
     if self.__inited is None:
         jpype.startJVM(jpype.get_default_jvm_path(), "-ea",
                        "-Djava.class.path=" + JavaTool.getAllJar())
         self.__inited = True
import jpype
import jpype.imports as jimport

# This would be better separated somewhere else
# in any case, path to JAR should be defined somewhere more "central"
jimport.registerDomain('ch')
jpype.addClassPath(
    "../../java/target/demo-python-java-api-1.0-SNAPSHOT-jar-with-dependencies.jar"
)
jpype.startJVM(jpype.get_default_jvm_path(),
               "-Djava.class.path=%s" % jpype.getClassPath())

from ch.dubernet.demopythonapi.simulation.api import ProtobufAdapter, ProtobufBufferedAdapter

from api.protobuf.JumpEvent_pb2 import JumpEvent
from api.protobuf.SingEvent_pb2 import SingEvent
from api.protobuf.SpeakEvent_pb2 import SpeakEvent
from api.protobuf.EventBuffer_pb2 import EventBuffer, EventContainer

# Simple method: simply functions to wrap instances


def create_event_handler(handler):
    class ProtobufHandler:
        def notifyStart(self):
            if hasattr(handler, "notifyStart"):
                handler.notifyStart()

        def notifyEnd(self):
            if hasattr(handler, "notifyEnd"):
                handler.notifyEnd()