def run_maven(pom_path,
              goal="package",
              quiet=False,
              run_tests=True,
              aggressive_update=True,
              return_stdout=False,
              additional_args=[]):
    '''Run a Maven pom to install all of the needed jars
    
    pom_path - the directory hosting the Maven POM
    
    goal - the maven goal. "package" is the default which is pretty much
           "do whatever the POM was built to do"
    
    quiet - feed Maven the -q switch if true to make it run in quiet mode
    
    run_tests - if False, set the "skip tests" maven flag. This is appropriate
                if you're silently building a known-good downloaded source.
    
    aggressive_update - if True, use the -U switch to make Maven go to the
                internet and check for updates. If False, default behavior.
                If None, use the -o switch to prevent Maven from any online
                updates.
                
    return_stdout - redirect stdout to capture a string and return it if True,
                    dump Maven output to console if False
                    
    additional_args - additional arguments for the command-line
    
    Runs mvn package on the POM
    '''
    from cellprofiler.utilities.setup import find_jdk

    maven_install_path = get_maven_install_path()
    jdk_home = find_jdk()
    env = os.environ.copy()
    if jdk_home is not None:
        env["JAVA_HOME"] = jdk_home.encode("utf-8")

    executeable_path = get_mvn_executable_path(maven_install_path)
    args = [executeable_path]
    if aggressive_update:
        args.append("-U")
    elif aggressive_update is None:
        args.append("-o")
    if quiet:
        args.append("-q")
    if not run_tests:
        args.append("-Dmaven.test.skip=true")
    args += additional_args
    args.append(goal)
    logging.debug("Running %s" % (" ".join(args)))
    if return_stdout:
        return check_output(args, cwd=pom_path, env=env)
    else:
        subprocess.check_call(args, cwd=pom_path, env=env)
def run_maven(pom_path, goal="package",
              quiet=False, run_tests=True, aggressive_update = True,
              return_stdout = False, additional_args = []):
    '''Run a Maven pom to install all of the needed jars
    
    pom_path - the directory hosting the Maven POM
    
    goal - the maven goal. "package" is the default which is pretty much
           "do whatever the POM was built to do"
    
    quiet - feed Maven the -q switch if true to make it run in quiet mode
    
    run_tests - if False, set the "skip tests" maven flag. This is appropriate
                if you're silently building a known-good downloaded source.
    
    aggressive_update - if True, use the -U switch to make Maven go to the
                internet and check for updates. If False, default behavior.
                If None, use the -o switch to prevent Maven from any online
                updates.
                
    return_stdout - redirect stdout to capture a string and return it if True,
                    dump Maven output to console if False
                    
    additional_args - additional arguments for the command-line
    
    Runs mvn package on the POM
    '''
    from cellprofiler.utilities.setup import find_jdk
    
    maven_install_path = get_maven_install_path()
    jdk_home = find_jdk()
    env = os.environ.copy()
    if jdk_home is not None:
        env["JAVA_HOME"] = jdk_home.encode("utf-8")
            
    executeable_path = get_mvn_executable_path(maven_install_path)
    args = [executeable_path]
    if aggressive_update:
        args.append("-U")
    elif aggressive_update is None:
        args.append("-o")
    if quiet:
        args.append("-q")
    if not run_tests:
        args.append("-Dmaven.test.skip=true")
    args += additional_args
    args.append(goal)
    logging.debug("Running %s" % (" ".join(args)))
    if return_stdout:
        return check_output(args, cwd = pom_path, env=env)
    else:
        subprocess.check_call(args, cwd = pom_path, env=env)
Example #3
0
data_files += [('cellprofiler\\icons',
               ['cellprofiler\\icons\\%s'%(x) 
                for x in os.listdir('cellprofiler\\icons')
                if x.endswith(".png") 
                or x.endswith(".psd") or x.endswith(".txt")]),
              ('imagej\\jars', 
               ['imagej\\jars\\%s' % x for x in os.listdir('imagej\\jars')])]
data_files += matplotlib.get_py2exe_datafiles()
################################
#
# Collect the JVM
#
################################

from cellprofiler.utilities.setup import find_jdk
jdk_dir = find_jdk()
def add_jre_files(path):
    files = []
    directories = []
    local_path = os.path.join(jdk_dir, path)
    for filename in os.listdir(local_path):
        if filename.startswith("."):
            continue
        local_file = os.path.join(jdk_dir, path, filename)
        relative_path = os.path.join(path, filename) 
        if os.path.isfile(local_file):
            files.append(local_file)
        elif os.path.isdir(local_file):
            directories.append(relative_path)
    if len(files):
        data_files.append([path, files])
Example #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 = [x.groups()[0] for x in [
        re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv]
               if x is not None]
    if len(jvm_arg) > 0:
        jvm_arg = jvm_arg[0]
    else:
        jvm_arg = "512m"
        
    args = [r"-Djava.class.path="+class_path,
            r"-Dloci.bioformats.loaded=true",
            #r"-verbose:class",
            #r"-verbose:jni",
            r"-Xmx%s" % jvm_arg]
    #
    # Get the log4j logger setup from a file in the bioformats directory
    # if such a file exists.
    #
    log4j_properties = os.path.join(bioformats_path, "log4j.properties")
    if os.path.exists(log4j_properties):
        log4j_properties = "file:/"+log4j_properties.replace(os.path.sep, "/")
        args += [r"-Dlog4j.configuration="+log4j_properties]
        init_logger = False
    else:
        init_logger = True
    
    if get_headless():
        # We're running silently, so don't change the Java preferences
        # The following definition uses a process-scope preferences factory
        args += [
            "-Djava.util.prefs.PreferencesFactory="
            "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"]
    run_headless = (get_headless() and 
                    not os.environ.has_key("CELLPROFILER_USE_XVFB"))
    run_headless = False
        
    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")
    
    #
    # Start the log4j logger to avoid error messages.
    #
    if init_logger:
        try:
            jutil.static_call("org/apache/log4j/BasicConfigurator",
                              "configure", "()V")
            log4j_logger = jutil.static_call("org/apache/log4j/Logger",
                                             "getRootLogger",
                                             "()Lorg/apache/log4j/Logger;")
            warn_level = jutil.get_static_field("org/apache/log4j/Level","WARN",
                                                "Lorg/apache/log4j/Level;")
            jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", 
                       warn_level)
            del logger
            del warn_level
        except:
            logger.error("Failed to initialize log4j\n", exc_info=True)
    if not get_headless():
        jutil.activate_awt()
Example #5
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"]

    if (get_ij_plugin_directory() is not None
            and os.path.isdir(get_ij_plugin_directory())):
        plugin_directory = get_ij_plugin_directory()
        #
        # Add the plugin directory to pick up .class files in a directory
        # hierarchy.
        #
        class_path += os.pathsep + plugin_directory
        #
        # Add any .jar files in the directory
        #
        class_path += os.pathsep + os.pathsep.join([
            os.path.join(plugin_directory, jarfile)
            for jarfile in os.listdir(plugin_directory)
            if jarfile.lower().endswith(".jar")
        ])

    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 = [
        x.groups()[0] for x in
        [re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv]
        if x is not None
    ]
    if len(jvm_arg) > 0:
        jvm_arg = jvm_arg[0]
    else:
        jvm_arg = "512m"

    args = [
        r"-Djava.class.path=" + class_path,
        r"-Dloci.bioformats.loaded=true",
        #r"-verbose:class",
        #r"-verbose:jni",
        r"-Xmx%s" % jvm_arg
    ]
    #
    # Get the log4j logger setup from a file in the bioformats directory
    # if such a file exists.
    #
    log4j_properties = os.path.join(bioformats_path, "log4j.properties")
    if os.path.exists(log4j_properties):
        log4j_properties = "file:/" + log4j_properties.replace(
            os.path.sep, "/")
        args += [r"-Dlog4j.configuration=" + log4j_properties]
        init_logger = False
    else:
        init_logger = True

    if get_headless():
        # We're running silently, so don't change the Java preferences
        # The following definition uses a process-scope preferences factory
        args += [
            "-Djava.util.prefs.PreferencesFactory="
            "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"
        ]
    run_headless = (get_headless()
                    and not os.environ.has_key("CELLPROFILER_USE_XVFB"))
    run_headless = False

    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")

    #
    # Start the log4j logger to avoid error messages.
    #
    if init_logger:
        try:
            jutil.static_call("org/apache/log4j/BasicConfigurator",
                              "configure", "()V")
            log4j_logger = jutil.static_call("org/apache/log4j/Logger",
                                             "getRootLogger",
                                             "()Lorg/apache/log4j/Logger;")
            warn_level = jutil.get_static_field("org/apache/log4j/Level",
                                                "WARN",
                                                "Lorg/apache/log4j/Level;")
            jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V",
                       warn_level)
            del logger
            del warn_level
        except:
            logger.error("Failed to initialize log4j\n", exc_info=True)
    if not get_headless():
        jutil.activate_awt()
        "msvcr90.dll", "msvcm90.dll", "msvcp90.dll"
    ]

data_files += [('cellprofiler\\icons', [
    'cellprofiler\\icons\\%s' % (x) for x in os.listdir('cellprofiler\\icons')
    if x.endswith(".png") or x.endswith(".psd")
]), ('bioformats', ['bioformats\\loci_tools.jar']),
               ('imagej', [
                   'imagej\\' + jar_file for jar_file in os.listdir('imagej')
                   if jar_file.endswith('.jar')
               ])]
data_files += matplotlib.get_py2exe_datafiles()
# Collect the JVM
#
from cellprofiler.utilities.setup import find_jdk
jdk_dir = find_jdk()


def add_jre_files(path):
    files = []
    directories = []
    local_path = os.path.join(jdk_dir, path)
    for filename in os.listdir(local_path):
        if filename.startswith("."):
            continue
        local_file = os.path.join(jdk_dir, path, filename)
        relative_path = os.path.join(path, filename)
        if os.path.isfile(local_file):
            files.append(local_file)
        elif os.path.isdir(local_file):
            directories.append(relative_path)
Example #7
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 = jutil.get_jvm_heap_size_arg()
    if jvm_arg is None:
        jvm_arg = "512m"
        
    args = [r"-Djava.class.path="+class_path,
            r"-Dloci.bioformats.loaded=true",
            #r"-verbose:class",
            #r"-verbose:jni",
            r"-Xmx%s" % jvm_arg]
    #
    # Get the log4j logger setup from a file in the bioformats directory
    # if such a file exists.
    #
    log4j_properties = os.path.join(bioformats_path, "log4j.properties")
    if os.path.exists(log4j_properties):
        log4j_properties = "file:/"+log4j_properties.replace(os.path.sep, "/")
        args += [r"-Dlog4j.configuration="+log4j_properties]
        init_logger = False
    else:
        init_logger = True
        
    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_headless() and 
                    not os.environ.has_key("CELLPROFILER_USE_XVFB"))
    run_headless = False
        
    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")
    
    #
    # Start the log4j logger to avoid error messages.
    #
    if init_logger:
        try:
            jutil.static_call("org/apache/log4j/BasicConfigurator",
                              "configure", "()V")
            log4j_logger = jutil.static_call("org/apache/log4j/Logger",
                                             "getRootLogger",
                                             "()Lorg/apache/log4j/Logger;")
            warn_level = jutil.get_static_field("org/apache/log4j/Level","WARN",
                                                "Lorg/apache/log4j/Level;")
            jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", 
                       warn_level)
            del logger
            del warn_level
        except:
            logger.error("Failed to initialize log4j\n", exc_info=True)
    if not get_headless():
        jutil.activate_awt()
Example #8
0
__precompiled_headless_jar = os.path.join(__imagej_path, "precompiled_headless.jar")
__class_path = os.pathsep.join((__loci_jar, __ij_jar, __imglib_jar, 
                                __javacl_jar))
if sys.platform == "darwin":
    # Start ImageJ headless
    # precompiled_headless.jar contains substitute classes for running
    # headless.
    #
    __class_path = os.pathsep.join((__precompiled_headless_jar, __class_path))
if os.environ.has_key("CLASSPATH"):
    __class_path += os.pathsep + os.environ["CLASSPATH"]
    
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 = [x.groups()[0] for x in [
    re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv]
           if x is not None]
if len(jvm_arg) > 0:
    jvm_arg = jvm_arg[0]
else:
    jvm_arg = "512m"
    
__args = [r"-Djava.class.path="+__class_path,
Example #9
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 = jutil.get_jvm_heap_size_arg()
    if jvm_arg is None:
        jvm_arg = "512m"

    args = [
        r"-Djava.class.path=" + class_path,
        r"-Dloci.bioformats.loaded=true",
        #r"-verbose:class",
        #r"-verbose:jni",
        r"-Xmx%s" % jvm_arg
    ]
    #
    # Get the log4j logger setup from a file in the bioformats directory
    # if such a file exists.
    #
    log4j_properties = os.path.join(bioformats_path, "log4j.properties")
    if os.path.exists(log4j_properties):
        log4j_properties = "file:/" + log4j_properties.replace(
            os.path.sep, "/")
        args += [r"-Dlog4j.configuration=" + log4j_properties]
        init_logger = False
    else:
        init_logger = True

    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_headless()
                    and not os.environ.has_key("CELLPROFILER_USE_XVFB"))
    run_headless = False

    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")

    #
    # Start the log4j logger to avoid error messages.
    #
    if init_logger:
        try:
            jutil.static_call("org/apache/log4j/BasicConfigurator",
                              "configure", "()V")
            log4j_logger = jutil.static_call("org/apache/log4j/Logger",
                                             "getRootLogger",
                                             "()Lorg/apache/log4j/Logger;")
            warn_level = jutil.get_static_field("org/apache/log4j/Level",
                                                "WARN",
                                                "Lorg/apache/log4j/Level;")
            jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V",
                       warn_level)
            del logger
            del warn_level
        except:
            logger.error("Failed to initialize log4j\n", exc_info=True)
    if not get_headless():
        jutil.activate_awt()
Example #10
0
    __root_path = os.path.abspath(os.path.split(__file__)[0])
    __root_path = os.path.split(__root_path)[0]
__path = os.path.join(__root_path, 'bioformats')
__imagej_path = os.path.join(__root_path, 'imagej')
__loci_jar = os.path.join(__path, "loci_tools.jar")
__ij_jar = os.path.join(__imagej_path, "ij.jar")
__imglib_jar = os.path.join(__imagej_path, "imglib.jar")
__javacl_jar = os.path.join(__imagej_path, "javacl-1.0-beta-4-shaded.jar")
__precompiled_headless_jar = os.path.join(__imagej_path, "precompiled_headless.jar")
__class_path = os.pathsep.join((__loci_jar, __ij_jar, __imglib_jar, 
                                __javacl_jar, __imagej_path))

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\n")
if os.environ.has_key('CLASSPATH'):
    __class_path += os.pathsep + os.environ['CLASSPATH']
os.environ['CLASSPATH'] = __class_path


def get_ij_bridge():
    '''Returns an an ijbridge that will work given the platform and preferences
    '''
    if USE_IJ2:
        return ij2_bridge.getInstance()
Example #11
0
def start_cellprofiler_jvm():
    '''Start the Java VM with arguments appropriate for CellProfiler'''
    global USE_IJ2
    global logger
    
    if hasattr(sys, 'frozen') and sys.platform != 'darwin':
        root_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    else:
        root_path = os.path.abspath(os.path.split(__file__)[0])
        root_path = os.path.split(root_path)[0]
    path = os.path.join(root_path, 'bioformats')
    imagej_path = os.path.join(root_path, 'imagej')
    loci_jar = os.path.join(path, "loci_tools.jar")
    ij2_jar = os.path.join(imagej_path, "imagej-2.0-SNAPSHOT-all.jar")
    ij_jar = os.path.join(imagej_path, "ij.jar")
    imglib_jar = os.path.join(imagej_path, "imglib.jar")
    javacl_jar = os.path.join(imagej_path, "javacl-1.0-beta-4-shaded.jar")
    USE_IJ2 = get_ij_version() == IJ_2
    if os.path.exists(ij2_jar) and USE_IJ2:
        class_path = os.pathsep.join((loci_jar, ij2_jar))
        USE_IJ2 = True
    else:
        USE_IJ2 = False
        class_path = os.pathsep.join((loci_jar, ij_jar, imglib_jar, 
                                      javacl_jar))
    if os.environ.has_key("CLASSPATH"):
        class_path += os.pathsep + os.environ["CLASSPATH"]
        
    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 = [x.groups()[0] for x in [
        re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv]
               if x is not None]
    if len(jvm_arg) > 0:
        jvm_arg = jvm_arg[0]
    else:
        jvm_arg = "512m"
        
    args = [r"-Djava.class.path="+class_path,
            r"-Dloci.bioformats.loaded=true",
            #r"-verbose:class",
            #r"-verbose:jni",
            r"-Xmx%s" % jvm_arg]
    if get_ij_plugin_directory() is not None:
        args.append("-Dplugins.dir="+get_ij_plugin_directory())
    
    #
    # Get the log4j logger setup from a file in the bioformats directory
    # if such a file exists.
    #
    log4j_properties = os.path.join(path, "log4j.properties")
    if os.path.exists(log4j_properties):
        log4j_properties = "file:/"+log4j_properties.replace(os.path.sep, "/")
        args += [r"-Dlog4j.configuration="+log4j_properties]
        init_logger = False
    else:
        init_logger = True
        
    run_headless = (get_headless() and 
                    not os.environ.has_key("CELLPROFILER_USE_XVFB"))
        
    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")
    
    #
    # Start the log4j logger to avoid error messages.
    #
    if init_logger:
        try:
            jutil.static_call("org/apache/log4j/BasicConfigurator",
                              "configure", "()V")
            log4j_logger = jutil.static_call("org/apache/log4j/Logger",
                                             "getRootLogger",
                                             "()Lorg/apache/log4j/Logger;")
            warn_level = jutil.get_static_field("org/apache/log4j/Level","WARN",
                                                "Lorg/apache/log4j/Level;")
            jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", 
                       warn_level)
            del logger
            del warn_level
        except:
            logger.error("Failed to initialize log4j\n", exc_info=True)
    if not run_headless:
        jutil.activate_awt()