예제 #1
0
 def enter_thread(self):
     J.attach()
     if not cpprefs.get_awt_headless():
         J.activate_awt()
     self.notify_socket = the_zmq_context.socket(zmq.SUB)
     self.notify_socket.setsockopt(zmq.SUBSCRIBE, "")
     self.notify_socket.connect(NOTIFY_ADDR)
예제 #2
0
def cp_start_vm():
    '''Start CellProfiler's JVM via Javabridge
    
    JVM parameters are harvested from preferences and
    the environment variables:
    
    CP_JDWP_PORT - port # for debugging Java within the JVM
    cpprefs.get_awt_headless() - controls java.awt.headless to prevent
        awt from being invoked
    '''

    args = [
        "-Dloci.bioformats.loaded=true",
        "-Dlogback.configurationFile=logback.xml",
        "-Djava.util.prefs.PreferencesFactory=" +
        "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"
    ]

    imagej_path = get_path_to_jars()
    if hasattr(sys, 'frozen'):
        jar_files = [
            jar_filename for jar_filename in os.listdir(imagej_path)
            if jar_filename.lower().endswith(".jar")
        ]

        def sort_fn(a, b):
            aa, bb = [(0 if x.startswith("cellprofiler-java") else 1, x)
                      for x in a, b]
            return cmp(aa, bb)

        jar_files = sorted(jar_files, cmp=sort_fn)
    else:
        jar_files = get_cellprofiler_jars()
    jar_files = [os.path.join(imagej_path, f) for f in jar_files]
    class_path = javabridge.JARS + jar_files

    if os.environ.has_key("CLASSPATH"):
        class_path += os.environ["CLASSPATH"].split(os.pathsep)
        logging.debug("Adding Java class path from environment variable, "
                      "CLASSPATH"
                      "")
        logging.debug("    CLASSPATH=" + os.environ["CLASSPATH"])

    plugin_directory = cpprefs.get_ij_plugin_directory()
    if (plugin_directory is not None and os.path.isdir(plugin_directory)):
        logger.debug("Using %s as imagej plugin directory" % plugin_directory)
        #
        # Add the plugin directory to pick up .class files in a directory
        # hierarchy.
        #
        class_path.append(plugin_directory)
        logger.debug("Adding %s to class path" % plugin_directory)
        #
        # Add any .jar files in the directory
        #
        for jarfile in os.listdir(plugin_directory):
            jarpath = os.path.join(plugin_directory, jarfile)
            if jarfile.lower().endswith(".jar"):
                logger.debug("Adding %s to class path" % jarpath)
                class_path.append(jarpath)
            else:
                logger.debug("Skipping %s" % jarpath)
    else:
        logger.info("Plugin directory doesn't point to valid folder: " +
                    plugin_directory)

    if sys.platform.startswith("win") and not hasattr(sys, 'frozen'):
        # Have to find tools.jar
        from javabridge.locate import find_jdk
        jdk_path = find_jdk()
        if jdk_path is not None:
            tools_jar = os.path.join(jdk_path, "lib", "tools.jar")
            class_path.append(tools_jar)
        else:
            logger.warning("Failed to find tools.jar")

    args += get_patcher_args(class_path)
    awt_headless = cpprefs.get_awt_headless()
    if awt_headless:
        logger.debug("JVM will be started with AWT in headless mode")
        args.append("-Djava.awt.headless=true")

    heap_size = str(cpprefs.get_jvm_heap_mb()) + "m"
    if os.environ.has_key("CP_JDWP_PORT"):
        args.append(("-agentlib:jdwp=transport=dt_socket,address=127.0.0.1:%s"
                     ",server=y,suspend=n") % os.environ["CP_JDWP_PORT"])

    javabridge.start_vm(args=args,
                        class_path=class_path,
                        max_heap_size=heap_size)
    #
    # Enable Bio-Formats directory cacheing
    #
    try:
        c_location = javabridge.JClassWrapper("loci.common.Location")
        c_location.cacheDirectoryListings(True)
        logger.debug("Enabled Bio-formats directory cacheing")
    except:
        logger.warning(
            "Bioformats version does not support directory cacheing")
예제 #3
0
def cp_start_vm():
    '''Start CellProfiler's JVM via Javabridge
    
    JVM parameters are harvested from preferences and
    the environment variables:
    
    CP_JDWP_PORT - port # for debugging Java within the JVM
    cpprefs.get_awt_headless() - controls java.awt.headless to prevent
        awt from being invoked
    '''

    args = [
        "-Dloci.bioformats.loaded=true",
        "-Dlogback.configurationFile=logback.xml",
        "-Djava.util.prefs.PreferencesFactory=" +
        "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"
    ]

    class_path = get_jars()
    args += get_patcher_args(class_path)
    awt_headless = cpprefs.get_awt_headless()
    if awt_headless:
        logger.debug("JVM will be started with AWT in headless mode")
        args.append("-Djava.awt.headless=true")

    heap_size = str(cpprefs.get_jvm_heap_mb()) + "m"
    if os.environ.has_key("CP_JDWP_PORT"):
        args.append(("-agentlib:jdwp=transport=dt_socket,address=127.0.0.1:%s"
                     ",server=y,suspend=n") % os.environ["CP_JDWP_PORT"])
    javabridge.start_vm(args=args,
                        class_path=class_path,
                        max_heap_size=heap_size)
    #
    # Enable Bio-Formats directory cacheing
    #
    try:
        c_location = javabridge.JClassWrapper("loci.common.Location")
        c_location.cacheDirectoryListings(True)
        logger.debug("Enabled Bio-formats directory cacheing")
    except:
        logger.warning(
            "Bioformats version does not support directory cacheing")
    #
    # Monkey-patch bioformats.formatreader.get_class_list to add
    # the classes we added to loci.formats.in
    #
    import bioformats.formatreader

    old_get_class_list = bioformats.formatreader.get_class_list

    def get_class_list():
        "Return a wrapped instance of loci.formats.ClassList"

        env = javabridge.get_env()
        class_list = old_get_class_list()
        rais_classname = 'loci/common/RandomAccessInputStream'
        #
        # Move any class to the back that thinks it can read garbage
        #
        fd, path = tempfile.mkstemp(suffix=".garbage")
        stream = None
        try:
            os.write(fd, "This is not an image file")
            os.fsync(fd)
            stream = javabridge.make_instance(rais_classname,
                                              '(Ljava/lang/String;)V', path)
            problem_classes = []
            for klass in env.get_object_array_elements(
                    class_list.get_classes()):
                try:
                    instance = javabridge.call(klass, "newInstance",
                                               "()Ljava/lang/Object;")
                    can_read_garbage = javabridge.call(
                        instance, "isThisType", "(L%s;)Z" % rais_classname,
                        stream)
                    if can_read_garbage:
                        problem_classes.append(klass)
                        class_list.remove_class(klass)
                except:
                    logger.info("Caught exception in %s.isThisType",
                                javabridge.to_string(klass))
        finally:
            os.close(fd)
            javabridge.call(stream, "close", "()V")
            os.remove(path)

        for classname in ("loci.formats.in.FlowSightReader",
                          "loci.formats.in.IM3Reader"):
            klass = javabridge.class_for_name(classname)
            class_list.add_class(klass)
        for klass in problem_classes:
            class_list.add_class(klass)
        return class_list

    bioformats.formatreader.get_class_list = get_class_list
예제 #4
0
def start_cellprofiler_jvm():
    '''Start the Java VM with arguments appropriate for CellProfiler'''
    global logger

    if hasattr(sys, 'frozen'):
        if sys.platform != 'darwin':
            root_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
            bioformats_path = os.path.join(root_path, 'bioformats')
        else:
            bioformats_path = os.path.abspath(os.path.split(__file__)[0])
            root_path = os.path.split(bioformats_path)[0]
        imagej_path = os.path.join(root_path, 'imagej', 'jars')

        def sort_fn(a, b):
            aa, bb = [(0 if x.startswith("cellprofiler-java") else 1, x)
                      for x in a, b]
            return cmp(aa, bb)

        jar_files = [
            jar_filename for jar_filename in os.listdir(imagej_path)
            if jar_filename.lower().endswith(".jar")
        ]
        jar_files = sorted(jar_files, cmp=sort_fn)
    else:
        bioformats_path = os.path.abspath(os.path.split(__file__)[0])
        root_path = os.path.split(bioformats_path)[0]
        jar_files = get_cellprofiler_jars()
        imagej_path = os.path.join(root_path, 'imagej', 'jars')

    class_path = os.pathsep.join(
        [os.path.join(imagej_path, jar_file) for jar_file in jar_files])

    if os.environ.has_key("CLASSPATH"):
        class_path += os.pathsep + os.environ["CLASSPATH"]

    plugin_directory = get_ij_plugin_directory()
    logger.debug("Using %s as imagej plugin directory" % plugin_directory)
    if (plugin_directory is not None and os.path.isdir(plugin_directory)):
        #
        # Add the plugin directory to pick up .class files in a directory
        # hierarchy.
        #
        class_path += os.pathsep + plugin_directory
        logger.debug("Adding %s to class path" % plugin_directory)
        #
        # Add any .jar files in the directory
        #
        for jarfile in os.listdir(plugin_directory):
            jarpath = os.path.join(plugin_directory, jarfile)
            if jarfile.lower().endswith(".jar"):
                logger.debug("Adding %s to class path" % jarpath)
                class_path += os.pathsep + jarpath
            else:
                logger.debug("Skipping %s" % jarpath)
    else:
        logger.info("Plugin directory doesn't point to valid folder: " +
                    plugin_directory)

    if sys.platform.startswith("win") and not hasattr(sys, 'frozen'):
        # Have to find tools.jar
        from cellprofiler.utilities.setup import find_jdk
        jdk_path = find_jdk()
        if jdk_path is not None:
            tools_jar = os.path.join(jdk_path, "lib", "tools.jar")
            class_path += os.pathsep + tools_jar
        else:
            logger.warning("Failed to find tools.jar")

    jvm_arg = "%dm" % get_jvm_heap_mb()

    args = [
        r"-Djava.class.path=" + class_path,
        r"-Dloci.bioformats.loaded=true",
        #r"-verbose:class",
        #r"-verbose:jni",
        r"-Dlogback.configurationFile=logback.xml",
        r"-Xmx%s" % jvm_arg
    ]

    if plugin_directory is not None and os.path.isdir(plugin_directory):
        # For IJ1 compatibility
        args += [r"-Dplugins.dir=%s" % plugin_directory]

    # In headless mode, we have to avoid changing the Java preferences.
    #
    # Aside from that, we need to prevent ImageJ from exiting and from
    # displaying the updater dialog - at least temporarily, we do that
    # through preferences. We use the HeadlessPreferencesFactory to
    # limit the scope of the changes to this process - otherwise we'd
    # turn off updating for the machine.
    #
    # TODO: ImageJ is implementing a pluggable mechanism to control the
    #       quit process. We can also contribute a pluggable mechanism
    #       that gives us more control over the updater.
    #
    args += [
        "-Djava.util.prefs.PreferencesFactory="
        "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"
    ]
    run_headless = get_awt_headless()

    logger.debug("JVM arguments: " + " ".join(args))
    jutil.start_vm(args, run_headless)
    logger.debug("Java virtual machine started.")
    jutil.attach()
    try:
        jutil.static_call("loci/common/Location", "cacheDirectoryListings",
                          "(Z)V", True)
    except:
        logger.warning(
            "Bioformats version does not support directory cacheing")