def setUp(self): root = path.dirname(path.abspath(path.dirname(__file__))) jpype.addClassPath(path.join(root, 'classes')) jvm_path = jpype.getDefaultJVMPath() classpath_arg = "-Djava.class.path=%s" classpath_arg %= jpype.getClassPath() jpype.startJVM(jvm_path, "-ea", # "-Xcheck:jni", "-Xmx256M", "-Xms16M", classpath_arg)
def testCygwin(self): if sys.platform == "win32" or sys.platform == "cygwin": raise common.unittest.SkipTest("not tested on cygwin") try: sys.platform = "cygwin" importlib.reload(jpype._classpath) self.assertEqual(jpype._classpath._SEP, ";") self.assertEqual(jpype._classpath._root, None) jpype._classpath._root = r'C:\cygwin64' self.assertEqual(jpype._classpath._get_root(), r'C:\cygwin64') self.assertEqual( jpype._classpath._splitpath('/cygdrive/c/cygwin64'), ['cygdrive', 'c', 'cygwin64']) self.assertEqual( jpype._classpath._posix2win('/cygdrive/c/windows'), 'c:\\windows') self.assertEqual(jpype._classpath._posix2win('/bin'), r"C:\cygwin64\bin") jpype._classpath._CLASSPATHS = [] jpype.addClassPath("/cygdrive/c/windows") jpype.addClassPath("/cygdrive/c/data") self.assertEqual(jpype._classpath._CLASSPATHS, [r"c:\windows", r"c:\data"]) env = os.environ.get("CLASSPATH") os.environ["CLASSPATH"] = r"c:\programs" self.assertEqual(jpype.getClassPath(True), r"c:\windows;c:\data;c:\programs") self.assertEqual(jpype.getClassPath(False), r"c:\windows;c:\data") # jpype.addClassPath("") #self.assertEqual(jpype.getClassPath(False), r"c:\windows;c:\data") jpype.addClassPath("/cygdrive/c/data/*") self.assertEqual(jpype.getClassPath(False), r"c:\windows;c:\data") if not env: del os.environ["CLASSPATH"] jpype._classpath._CLASSPATHS = [] with self.assertRaises(jpype.JVMNotFoundException): jpype.getDefaultJVMPath() finally: sys.platform = self.platform importlib.reload(jpype._classpath)
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)
def decode(cls, code): jvmPath = jpype.getDefaultJVMPath() print(jvmPath) print(jpype.getClassPath()) jpype.startJVM(jvmPath, '-Djava.class.path=D:/woniuboss-decode.jar') javaclass = jpype.JClass('com.woniuxy.des.DESede') des = javaclass() decode = des.decryptMode(code) jpype.shutdownJVM() return decode
def get_classpath() -> str: """Get the Java classpath. Notes ----- Get the Java classpath. If the JVM has not yet started, this will list the jars that have been added with ``py5_tools.add_classpath()`` and ``py5_tools.add_jars()``. After the JVM has started, the classpath cannot be changed and the aformentioned functions would throw a ``RuntimeError``. Use ``py5_tools.is_jvm_running()`` to first determine if the JVM is running.""" if jpype.isJVMStarted(): return jpype.getClassPath() else: return ':'.join(str(p) for p in _classpath)
def setUp(self): if not jpype.isJVMStarted(): root = path.dirname(path.abspath(path.dirname(__file__))) jpype.addClassPath(path.join(root, 'classes')) jvm_path = jpype.getDefaultJVMPath() logger = logging.getLogger(__name__) logger.info("Running testsuite using JVM %s" % jvm_path) classpath_arg = "-Djava.class.path=%s" classpath_arg %= jpype.getClassPath() jpype.startJVM(jvm_path, "-ea", # "-Xcheck:jni", "-Xmx256M", "-Xms16M", classpath_arg) self.jpype = jpype.JPackage('jpype') if sys.version < '3': self.assertCountEqual = self.assertItemsEqual
def addLuciferJar(self, verbose=False): if self.isLuciferJarLoaded: if verbose: print("Already Loaded Lucifer Jar!") return jarLocation = os.path.abspath( os.path.join( self.luciferJavaBuildPath, f"java-{luciferJVM.getJavaMajorVersion()}/{self.luciferJarName}" )) if not os.path.exists(jarLocation): print("Jar has not been build, please build jar first") return self.addJarToClassPath(jarLocation, verbose=verbose) print(jpype.getClassPath()) self.isLuciferJarLoaded = True
def setUp(self): if not jpype.isJVMStarted(): try: import faulthandler faulthandler.enable() faulthandler.disable() except: pass root = path.dirname(path.abspath(path.dirname(__file__))) jpype.addClassPath(path.join(root, 'classes')) jvm_path = jpype.getDefaultJVMPath() logger = logging.getLogger(__name__) logger.info("Running testsuite using JVM %s" % jvm_path) classpath_arg = "-Djava.class.path=%s" args = ["-ea", "-Xmx256M", "-Xms16M"] if self._checkjni: args.append("-Xcheck:jni") # TODO: enabling this check crashes the JVM with: FATAL ERROR in native method: Bad global or local ref passed to JNI # "-Xcheck:jni", if self._classpath: from pathlib import Path import warnings # This needs to be relative to run location jpype.addClassPath(Path(self._classpath).resolve()) warnings.warn("using jar instead of thunks") if self._convertStrings: import warnings warnings.warn("using deprecated convertStrings") if self._jacoco: import warnings args.append( "-javaagent:lib/org.jacoco.agent-0.8.5-runtime.jar=destfile=build/coverage/jacoco.exec,includes=org.jpype.*" ) warnings.warn("using JaCoCo") import pathlib jpype.addClassPath(pathlib.Path("lib/*").absolute()) jpype.addClassPath(pathlib.Path("test/jar/*").absolute()) classpath_arg %= jpype.getClassPath() args.append(classpath_arg) _jpype.enableStacktraces(True) #JPypeTestCase.str_conversion = eval(os.getenv('JPYPE_STR_CONVERSION', 'True')) jpype.startJVM(jvm_path, *args, convertStrings=self._convertStrings) self.jpype = jpype.JPackage('jpype') if sys.version < '3': self.assertCountEqual = self.assertItemsEqual
def setUp(self): if not jpype.isJVMStarted(): root = path.dirname(path.abspath(path.dirname(__file__))) jpype.addClassPath(path.join(root, 'classes')) jvm_path = jpype.getDefaultJVMPath() logger = logging.getLogger(__name__) logger.info("Running testsuite using JVM %s" % jvm_path) classpath_arg = "-Djava.class.path=%s" classpath_arg %= jpype.getClassPath() JPypeTestCase.str_conversion = eval(os.getenv('JPYPE_STR_CONVERSION', 'True')) jpype.startJVM(jvm_path, "-ea", # TODO: enabling this check crashes the JVM with: FATAL ERROR in native method: Bad global or local ref passed to JNI #"-Xcheck:jni", "-Xmx256M", "-Xms16M", classpath_arg, convertStrings=self.str_conversion) self.jpype = jpype.JPackage('jpype') if sys.version < '3': self.assertCountEqual = self.assertItemsEqual
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')
def __init__(self): jar_path = Path(__file__).parent / "hartree" found_jars = sorted(jar_path.glob('*.jar')) if len(found_jars) == 0: raise Exception( "Could not find any JARs in dir {}".format(jar_path)) for found_jar in found_jars: jpype.addClassPath(found_jar) print("Classpath: ", jpype.getClassPath()) jpype.startJVM(convertStrings=False) # TODO: Figure out how to scope these imports for the class # noinspection PyUnresolvedReferences from org.cmayes.hartree.loader.gaussian import SnapshotLoader self.loader = SnapshotLoader()
def basic_example(): class_path = jpype.getClassPath() print("Class path: {}.".format(class_path)) jvm_path = jpype.getDefaultJVMPath() print("JVM path: {}.".format(jvm_path)) if not jpype.isJVMStarted(): try: #jpype.addClassPath("/path/to/sample.jar") #jpype.startJVM(jvmpath=jvmpath, classpath=classpath, ignoreUnrecognized=False, convertStrings=False, interrupt=False) jpype.startJVM() except TypeError as ex: print("TypeError raised: {}.".format(ex)) except OSError as ex: print("OSError raised: {}.".format(ex)) #-------------------- # Do something. #-------------------- if jpype.isJVMStarted(): jpype.shutdownJVM()
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()
for i in range(0, 100): obj.compareTo(obj) self.assertTrue(sys.getrefcount(obj) - initialObj < 5) self.assertTrue( sys.getrefcount(obj.__javavalue__) - initialValue < 5) self.assertTrue(subJVM(f, 'testRefCountCall')) if __name__ == "__main__": # Launch jpype with a clean JVM root = path.dirname(path.abspath(path.dirname(__file__))) jpype.addClassPath(path.join(root, 'classes')) jvm_path = jpype.getDefaultJVMPath() classpath_arg = "-Djava.class.path=%s" classpath_arg %= jpype.getClassPath() jpype.startJVM( jvm_path, "-ea", # "-Xcheck:jni", "-Xmx256M", "-Xms16M", classpath_arg) # Execute the requested test case ltc = LeakTestCase() ltc.setUp() getattr(ltc, sys.argv[1])() # Return 0 on success exit(0)
def get_classpath(): return jpype.getClassPath()
def get(): return jpype.getClassPath()
#!/usr/bin/env python # -*- coding:utf-8 -*- #====#====#====#==== # Author: # CreateDate: # Version: #====#====#====#==== import jpype jvmPath = jpype.getDefaultJVMPath() print(jvmPath) print(jpype.getClassPath()) jpype.startJVM(jvmPath, '-Djava.class.path=D:/woniuboss-decode.jar') javaclass = jpype.JClass('com.woniuxy.des.DESede') print(javaclass) des = javaclass() decode = des.decryptMode('35C50A9B463B93A3C034C0850DA6B091') print(decode) jpype.shutdownJVM() # # import hashlib # # m = hashlib.md5() # m.update('woniu1234'.encode()) # print(m.digest()) # print(m.digest().hex()) # print(m.hexdigest()) # print(m.digest_size) # import pyDes