Esempio n. 1
0
    def find_spec(self, name, path, target=None):
        # If jvm is not started then we just check against the TLDs
        if not _jpype.isStarted():
            base = name.partition('.')[0]
            if not base in _JDOMAINS:
                return None
            raise ImportError("Attempt to create java modules without jvm")

        # Check if it is a TLD
        parts = name.rpartition('.')
        if not parts[1] and _jpype.isPackage(parts[2]):
            return _ModuleSpec(name, self)

        if not parts[1] and not _jpype.isPackage(parts[0]):
            return None

        base = sys.modules.get(parts[0], None)
        if not base or not isinstance(base, _jpype._JPackage):
            return None

        # Support for external modules in java tree
        name = unwrap(name)
        for customizer in _CUSTOMIZERS:
            if customizer.canCustomize(name):
                return customizer.getSpec(name)

        # Using isPackage eliminates need for registering tlds
        if not hasattr(base, parts[2]):
            # If the base is a Java package and it wasn't found in the
            # package using getAttr, then we need to emit an error
            # so we produce a meaningful diagnositic.
            _getJavaClass(name)

        # Import the java module
        return _ModuleSpec(name, self)
def registerJVMInitializer(func):
    """Register a function to be called after jvm is started"""
    if not _jpype.isStarted():
        JInitializers.append(func)
    else:
        # JVM is already started so we are safe to execute immediately.
        func()
Esempio n. 3
0
def isJVMStarted():
    """ True if the JVM is currently running."""
    # TODO This method is horribly named.  It should be named isJVMRunning as
    # isJVMStarted would seem to imply that the JVM was started at some
    # point without regard to whether it has been shutdown.
    #
    return _jpype.isStarted()
Esempio n. 4
0
    def __getattribute__(self, n):
        try:
            return object.__getattribute__(self, n)
        except AttributeError as ex:
            if n.startswith("__"):
                raise ex
            # not found ...

            # perhaps it is a class?
            subname = "{0}.{1}".format(self.__name, n)
            if not _jpype.isStarted():
                import warnings
                warnings.warn(
                    "JVM not started yet, can not inspect JPackage contents")
                return n
            if not _jpype.isThreadAttachedToJVM():
                _jpype.attachThreadToJVM()
            cc = _jpype.findClass(subname)
            if cc is None:
                # can only assume it is a sub-package then ...
                cc = JPackage(subname)
            else:
                cc = _jclass._getClassFor(cc)

            self.__setattr__(n, cc, True)
            return cc
Esempio n. 5
0
    def find_spec(self, name, path, target=None):
        # If jvm is not started then we just check against the TLDs
        if not _jpype.isStarted():
            base = name.partition('.')[0]
            if not base in _JDOMAINS:
                return None
            raise ImportError(
                "Attempt to create Java package '%s' without jvm" % name)

        # Check for aliases
        if name in _JDOMAINS:
            jname = _JDOMAINS[name]
            if not _jpype.isPackage(jname):
                raise ImportError(
                    "Java package '%s' not found, requested by alias '%s'" %
                    (jname, name))
            ms = _ModuleSpec(name, self)
            ms._jname = jname
            return ms

        # Check if it is a TLD
        parts = name.rpartition('.')

        # Use the parent module to simplify name mangling
        if not parts[1] and _jpype.isPackage(parts[2]):
            ms = _ModuleSpec(name, self)
            ms._jname = name
            return ms

        if not parts[1] and not _jpype.isPackage(parts[0]):
            return None

        base = sys.modules.get(parts[0], None)
        if not base or not isinstance(base, _jpype._JPackage):
            return None

        # Support for external modules in java tree
        name = unwrap(name)
        for customizer in _CUSTOMIZERS:
            if customizer.canCustomize(name):
                return customizer.getSpec(name)

        # Using isPackage eliminates need for registering tlds
        if not hasattr(base, parts[2]):
            # If the base is a Java package and it wasn't found in the
            # package using getAttr, then we need to emit an error
            # so we produce a meaningful diagnositic.
            try:
                # Use forname because it give better diagnostics
                _jpype._java_lang_Class.forName(name, True,
                                                _jpype.JPypeClassLoader)
                raise ImportError("Class `%s` was found but was not expected" %
                                  name)
            # Not found is acceptable
            except Exception as ex:
                raise ImportError("Failed to import '%s'" % name) from ex

        # Import the java module
        return _ModuleSpec(name, self)
Esempio n. 6
0
def _JTerminate():
    try:
        import jpype.config
        # We are exiting anyway so no need to free resources
        if _jpype.isStarted():
            _jpype.JPypeContext.freeResources = False
        if jpype.config.onexit:
            _jpype.shutdown(jpype.config.destroy_jvm, False)
    except RuntimeError:
        pass
Esempio n. 7
0
def shutdownJVM():
    """ Shuts down the JVM.

    This method shuts down the JVM and disables access to existing
    Java objects. Due to limitations in the JPype, it is not possible to
    restart the JVM after being terminated.
    """
    import threading
    import jpype.config
    if threading.current_thread() is not threading.main_thread():
        raise RuntimeError("Shutdown must be called from main thread")
    if _jpype.isStarted():
        _jpype.JPypeContext.freeResources = jpype.config.free_resources
    _jpype.shutdown(jpype.config.destroy_jvm, False)
Esempio n. 8
0
def getJVMVersion():
    """ Get the JVM version if the JVM is started.

    This function can be used to determine the version of the JVM. It is
    useful to help determine why a Jar has failed to load.

    Returns:
      A typle with the (major, minor, revison) of the JVM if running.
    """
    if not _jpype.isStarted():
        return (0, 0, 0)
    version = str(_jclass.JClass(
        'java.lang.Runtime').class_.getPackage().getImplementationVersion())
    if version.find('_') != -1:
        parts = version.split('_')
        version = parts[0]
    return tuple([int(i) for i in version.split('.')])
Esempio n. 9
0
def getJVMVersion():
    """ Get the JVM version if the JVM is started.

    This function can be used to determine the version of the JVM. It is
    useful to help determine why a Jar has failed to load.

    Returns:
      A typle with the (major, minor, revison) of the JVM if running.
    """
    if not _jpype.isStarted():
        return (0, 0, 0)

    import re
    runtime = _jpype.JClass('java.lang.Runtime')
    version = runtime.class_.getPackage().getImplementationVersion()

    # Java 9+ has a version method
    if not version:
        version = runtime.version()
    version = (re.match("([0-9.]+)", str(version)).group(1))
    return tuple([int(i) for i in version.split('.')])
Esempio n. 10
0
    def __getattribute__(self, n):
        try:
            return object.__getattribute__(self, n)
        except AttributeError as ex:
            ex1 = ex
            pass

        if n.startswith("__"):
            raise ex1
        # not found ...

        # perhaps it is a class?
        subname = "{0}.{1}".format(self.__name, n)
        if not _jpype.isStarted():
            if n.startswith('_'):
                raise ex1
            import warnings
            warnings.warn(
                "JVM not started yet, can not inspect JPackage contents %s")
            return n

        # See if it is a Java class
        try:
            cc = _jclass.JClass(subname)
            self.__setattr__(n, cc, True)
            return cc
        except:
            pass

        # Check to see if this conforms to the required package name
        # convention, it not then we should not create a new package
        if self.__pattern and self.__pattern.match(n) == None:
            raise AttributeError(
                "Java package %s does not contain a class %s" %
                (self.__name, n))

        # Add package to the path
        cc = JPackage(subname, pattern=self.__pattern)
        self.__setattr__(n, cc, True)
        return cc
Esempio n. 11
0
def addClassPath(path1):
    """ Add a path to the Java class path

    Classpath items can be a java, a directory, or a
    glob pattern.  Relative paths are relative to the 
    caller location.

    Arguments:
      path(str):

    """
    # We are deferring these imports until here as we only need them
    # if this function is used.
    from pathlib import Path
    import inspect
    global _CLASSPATHS

    # Convert to an absolute path.  Note that
    # relative paths will be resolve based on the location
    # of the caller rather than the JPype directory.
    path1 = Path(path1)
    if not path1.is_absolute():
        path2 = Path(inspect.stack(1)[1].filename).parent.resolve()
        path1 = path2.joinpath(path1)

    # If the JVM is already started then we will have to load the paths
    # immediately into the DynamicClassLoader
    if _jpype.isStarted():
        Paths = _jpype.JClass('java.nio.file.Paths')
        JContext = _jpype.JClass('org.jpype.JPypeContext')
        classLoader = JContext.getInstance().getClassLoader()
        if path1.name == "*":
            paths = list(path1.parent.glob("*.jar"))
            if len(paths) == 0:
                return
            for path in paths:
                classLoader.addFile(Paths.get(str(path)))
        else:
            classLoader.addFile(Paths.get(str(path1)))
    _CLASSPATHS.append(path1)
Esempio n. 12
0
    def __getattribute__(self, n):
        try:
            return object.__getattribute__(self, n)
        except:
            # not found ...

            # perhaps it is a class?
            subname = "{0}.{1}".format(self.__name, n)
            if not _jpype.isStarted():
               import warnings
               warnings.warn("JVM not started yet, can not inspect JPackage contents")
               return n
            if not _jpype.isThreadAttachedToJVM():
                _jpype.attachThreadToJVM()
            cc = _jpype.findClass(subname)
            if cc is None:
                # can only assume it is a sub-package then ...
                cc = JPackage(subname)
            else:
                cc = _jclass._getClassFor(cc)

            self.__setattr__(n, cc, True)
            return cc
Esempio n. 13
0
    def create_module(self, spec):
        if not _jpype.isStarted():
            raise ImportError("Attempt to create java modules without jvm")

        # Handle creating the java name based on the path
        parts = spec.name.split('.')
        if len(parts) == 1:
            return _JModule(spec, _JDOMAINS[spec.name])

        # Use the parent module to simplify name mangling
        base = _sys.modules[".".join(parts[:-1])]

        # Support of inner classes
        if not isinstance(base, _JImport):
            return getattr(base, parts[-1])
        jbasename = object.__getattribute__(base, '__javaname__')
        try:
            object.__getattribute(base, '__javaclass__')
            javaname = "$".join([jbasename, _keywordUnwrap(parts[-1])])
        except AttributeError:
            javaname = ".".join([jbasename, _keywordUnwrap(parts[-1])])

        return _JModule(spec, javaname)
Esempio n. 14
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...)
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the JVM.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to ignore
        invalid JVM arguments. Default is False.
      convertStrings (bool): Option to force Java strings to
        cast to Python strings. This option is to support legacy code
        for which conversion of Python strings was the default. This
        will globally change the behavior of all calls using
        strings, and a value of True is NOT recommended for newly
        developed code.
      interrupt (bool): Option to install ^C signal handlers.
        If True then ^C will stop the process, else ^C will
        transfer control to Python rather than halting.  If
        not specified will be False if Python is started as
        an interactive shell.

    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, str):
            args.append('-Djava.class.path=%s' % _handleClassPath([classpath]))
        elif hasattr(classpath, '__iter__'):
            args.append('-Djava.class.path=%s' % _handleClassPath(classpath))
        else:
            raise TypeError("Unknown class path element")

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)
    convertStrings = kwargs.pop('convertStrings', False)
    interrupt = kwargs.pop('interrupt', not interactive())

    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'" %
                        (','.join([str(i) for i in kwargs])))

    try:
        _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized,
                       convertStrings, interrupt)
        initializeResources()
    except RuntimeError as ex:
        source = str(ex)
        if "UnsupportedClassVersion" in source:
            import re
            match = re.search(r"([0-9]+)\.[0-9]+", source)
            if match:
                version = int(match.group(1)) - 44
                raise RuntimeError(
                    "%s is older than required Java version %d" %
                    (jvmpath, version)) from ex
        raise
Esempio n. 15
0
def isJVMStarted() :
    return _jpype.isStarted()
Esempio n. 16
0
def registerJVMInitializer(func):
    if not _jpype.isStarted():
        JInitializers.append(func)
    else:
        # JVM is already started so we are safe to execute immediately.
        func()
Esempio n. 17
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...)
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the jvm.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to JVM to ignore
        invalid JVM arguments. Default is False.
      convertStrings (bool): Option to JPype to force Java strings to
        cast to Python strings. This option is to support legacy code
        for which conversion of Python strings was the default. This
        will globally change the behavior of all calls using
        strings, and a value of True is NOT recommended for newly 
        developed code.

        The default value for this option during 0.7 series is 
        True.  The option will be False starting in 0.8. A
        warning will be issued if this option is not specified
        during the transition period.


    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')
    _JVM_started = True

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, (str, _jtypes._unicode)):
            args.append('-Djava.class.path=%s' % _handleClassPath([classpath]))
        elif hasattr(classpath, '__iter__'):
            args.append('-Djava.class.path=%s' % _handleClassPath(classpath))
        else:
            raise TypeError("Unknown class path element")

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)

    if not "convertStrings" in kwargs:
        import warnings
        warnings.warn("""
-------------------------------------------------------------------------------
Deprecated: convertStrings was not specified when starting the JVM. The default
behavior in JPype will be False starting in JPype 0.8. The recommended setting
for new code is convertStrings=False.  The legacy value of True was assumed for
this session. If you are a user of an application that reported this warning,
please file a ticket with the developer.
-------------------------------------------------------------------------------
""")

    convertStrings = kwargs.pop('convertStrings', True)


    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'"
                        % (','.join([str(i) for i in kwargs])))

    _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized, convertStrings)
    _initialize()
Esempio n. 18
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...)
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the JVM.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to ignore
        invalid JVM arguments. Default is False.
      convertStrings (bool): Option to force Java strings to
        cast to Python strings. This option is to support legacy code
        for which conversion of Python strings was the default. This
        will globally change the behavior of all calls using
        strings, and a value of True is NOT recommended for newly
        developed code.

        The default value for this option during 0.7 series is
        True.  The option will be False starting in 0.8. A
        warning will be issued if this option is not specified
        during the transition period.


    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, str):
            args.append('-Djava.class.path=%s' % _handleClassPath([classpath]))
        elif hasattr(classpath, '__iter__'):
            args.append('-Djava.class.path=%s' % _handleClassPath(classpath))
        else:
            raise TypeError("Unknown class path element")

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)
    convertStrings = kwargs.pop('convertStrings', False)

    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'" %
                        (','.join([str(i) for i in kwargs])))

    try:
        _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized,
                       convertStrings)
        _JVM_started = True
    except RuntimeError as ex:
        source = str(ex)
        if "UnsupportedClassVersion" in source:
            import re
            match = re.search(r"([0-9]+)\.[0-9]+", source)
            if match:
                version = int(match.group(1)) - 44
                raise RuntimeError(
                    "%s is older than required Java version %d" %
                    (jvmpath, version)) from ex
        raise

    _jpype._java_lang_Class = None
    _jpype._java_lang_Object = _jpype.JClass("java.lang.Object")
    _jpype._java_lang_Throwable = _jpype.JClass("java.lang.Throwable")
    _jpype._java_lang_Exception = _jpype.JClass("java.lang.Exception")
    _jpype._java_lang_Class = _jpype.JClass("java.lang.Class")
    _jpype._java_lang_String = _jpype.JClass("java.lang.String")

    _jpype._java_lang_RuntimeException = _jpype.JClass(
        "java.lang.RuntimeException")

    # Preload needed classes
    _jpype._java_lang_Boolean = _jpype.JClass("java.lang.Boolean")
    _jpype._java_lang_Byte = _jpype.JClass("java.lang.Byte")
    _jpype._java_lang_Character = _jpype.JClass("java.lang.Character")
    _jpype._java_lang_Short = _jpype.JClass("java.lang.Short")
    _jpype._java_lang_Integer = _jpype.JClass("java.lang.Integer")
    _jpype._java_lang_Long = _jpype.JClass("java.lang.Long")
    _jpype._java_lang_Float = _jpype.JClass("java.lang.Float")
    _jpype._java_lang_Double = _jpype.JClass("java.lang.Double")

    # Bind types
    _jpype.JString.class_ = _jpype._java_lang_String
    _jpype.JObject.class_ = _jpype._java_lang_Object
    _jtypes.JBoolean.class_ = _jpype._java_lang_Boolean.TYPE
    _jtypes.JByte.class_ = _jpype._java_lang_Byte.TYPE
    _jtypes.JChar.class_ = _jpype._java_lang_Character.TYPE
    _jtypes.JShort.class_ = _jpype._java_lang_Short.TYPE
    _jtypes.JInt.class_ = _jpype._java_lang_Integer.TYPE
    _jtypes.JLong.class_ = _jpype._java_lang_Long.TYPE
    _jtypes.JFloat.class_ = _jpype._java_lang_Float.TYPE
    _jtypes.JDouble.class_ = _jpype._java_lang_Double.TYPE
    _jtypes.JBoolean._hints = _jcustomizer.getClassHints("boolean")
    _jtypes.JByte._hints = _jcustomizer.getClassHints("byte")
    _jtypes.JChar._hints = _jcustomizer.getClassHints("char")
    _jtypes.JShort._hints = _jcustomizer.getClassHints("short")
    _jtypes.JInt._hints = _jcustomizer.getClassHints("int")
    _jtypes.JLong._hints = _jcustomizer.getClassHints("long")
    _jtypes.JFloat._hints = _jcustomizer.getClassHints("float")
    _jtypes.JDouble._hints = _jcustomizer.getClassHints("double")

    # Table for automatic conversion to objects "JObject(value, type)"
    _jpype._object_classes = {}
    # These need to be deprecated so that we can support casting Python objects
    _jpype._object_classes[bool] = _jpype._java_lang_Boolean
    _jpype._object_classes[int] = _jpype._java_lang_Long
    _jpype._object_classes[float] = _jpype._java_lang_Double
    _jpype._object_classes[str] = _jpype._java_lang_String
    _jpype._object_classes[type] = _jpype._java_lang_Class
    _jpype._object_classes[object] = _jpype._java_lang_Object
    _jpype._object_classes[_jpype._JClass] = _jpype._java_lang_Class
    _jpype._object_classes[_jtypes.JBoolean] = _jpype._java_lang_Boolean
    _jpype._object_classes[_jtypes.JByte] = _jpype._java_lang_Byte
    _jpype._object_classes[_jtypes.JChar] = _jpype._java_lang_Character
    _jpype._object_classes[_jtypes.JShort] = _jpype._java_lang_Short
    _jpype._object_classes[_jtypes.JInt] = _jpype._java_lang_Integer
    _jpype._object_classes[_jtypes.JLong] = _jpype._java_lang_Long
    _jpype._object_classes[_jtypes.JFloat] = _jpype._java_lang_Float
    _jpype._object_classes[_jtypes.JDouble] = _jpype._java_lang_Double
    _jpype._object_classes[type(None)] = _jpype._java_lang_Object
    _jpype._object_classes[_jpype.JString] = _jpype._java_lang_String

    # Set up table of automatic conversions of Python primitives
    # this table supports "JArray(type)"
    _jpype._type_classes = {}
    _jpype._type_classes[bool] = _jtypes.JBoolean
    _jpype._type_classes[int] = _jtypes.JLong
    _jpype._type_classes[float] = _jtypes.JDouble
    _jpype._type_classes[str] = _jpype._java_lang_String
    _jpype._type_classes[type] = _jpype._java_lang_Class
    _jpype._type_classes[object] = _jpype._java_lang_Object
    _jpype._type_classes[_jpype.JString] = _jpype._java_lang_String
    _jpype._type_classes[_jpype.JObject] = _jpype._java_lang_Object
    _jinit.runJVMInitializers()

    _jpype.JClass('org.jpype.JPypeKeywords').setKeywords(
        list(_pykeywords._KEYWORDS))
Esempio n. 19
0
def isJVMStarted():
    return _jpype.isStarted()
Esempio n. 20
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.  

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...) 
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the jvm.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to JVM to ignore
        invalid JVM arguments. Default is False.

    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied 
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')
    _JVM_started = True

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, (str, _jtypes._unicode)):
            args.append('-Djava.class.path=%s' % classpath)
        else:
            args.append('-Djava.class.path=%s' %
                        (_classpath._SEP.join(classpath)))

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)

    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'" %
                        (','.join([str(i) for i in kwargs])))

    _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized)
    _initialize()