def getColorModel( color_space, has_alpha=False, is_alpha_premultiplied=False, transparency=OPAQUE, transfer_type=TYPE_BYTE ): """Return a java.awt.image.ColorModel color model color_space - a java.awt.color.ColorSpace such as returned by getGrayColorSpace or getRGBColorSpace has_alpha - True if alpha channel is specified is_alpha_premultiplied - True if other channel values have already been reduced by the alpha multiplier, False if the channel values are independent of the multiplier. transparency - one of BITMASK, OPAQUE or TRANSPARENT. transfer_type - one of TYPE_BYTE, TYPE_USHORT, TYPE_INT """ jtransparency = jutil.get_static_field("java/awt/Transparency", transparency, "I") jtransfer_type = jutil.get_static_field("java/awt/image/DataBuffer", transfer_type, "I") return jutil.make_instance( "java/awt/image/ComponentColorModel", "(Ljava/awt/color/ColorSpace;ZZII)V", color_space, has_alpha, is_alpha_premultiplied, jtransparency, jtransfer_type, )
def getColorModel(color_space, has_alpha=False, is_alpha_premultiplied = False, transparency = OPAQUE, transfer_type = TYPE_BYTE): '''Return a java.awt.image.ColorModel color model color_space - a java.awt.color.ColorSpace such as returned by getGrayColorSpace or getRGBColorSpace has_alpha - True if alpha channel is specified is_alpha_premultiplied - True if other channel values have already been reduced by the alpha multiplier, False if the channel values are independent of the multiplier. transparency - one of BITMASK, OPAQUE or TRANSPARENT. transfer_type - one of TYPE_BYTE, TYPE_USHORT, TYPE_INT ''' jtransparency = jutil.get_static_field('java/awt/Transparency', transparency, 'I') jtransfer_type = jutil.get_static_field('java/awt/image/DataBuffer', transfer_type, 'I') return jutil.make_instance('java/awt/image/ComponentColorModel', '(Ljava/awt/color/ColorSpace;ZZII)V', color_space, has_alpha, is_alpha_premultiplied, jtransparency, jtransfer_type)
class ModuleItem(object): def __init__(self): self.o = instance IV_NORMAL = J.get_static_field("imagej/module/ItemVisibility", "NORMAL", "Limagej/module/ItemVisibility;") IV_TRANSIENT = J.get_static_field("imagej/module/ItemVisibility", "TRANSIENT", "Limagej/module/ItemVisibility;") IV_INVISIBLE = J.get_static_field("imagej/module/ItemVisibility", "INVISIBLE", "Limagej/module/ItemVisibility;") IV_MESSAGE = J.get_static_field("imagej/module/ItemVisibility", "MESSAGE", "Limagej/module/ItemVisibility;") def getType(self): jtype = J.call(self.o, "getType", "()Ljava/lang/Class;") type_name = J.call(jtype, "getCanonicalName", "()Ljava/lang/String;") if field_mapping.has_key(type_name): return field_mapping[type_name] for class_instance, result in field_class_mapping(): if J.call(class_instance, "isAssignableFrom", "(Ljava/lang/Class;)Z", jtype): return result return None getWidgetStyle = J.make_method("getWidgetStyle", "()Ljava/lang/String;") getMinimumValue = J.make_method("getMinimumValue", "()Ljava/lang/Object;") getMaximumValue = J.make_method("getMaximumValue", "()Ljava/lang/Object;") getStepSize = J.make_method("getStepSize", "()Ljava/lang/Number;") getColumnCount = J.make_method("getColumnCount", "()I") getChoices = J.make_method("getChoices", "()Ljava/util/List;") getValue = J.make_method("getValue", "(Limagej/module/Module;)Ljava/lang/Object;") setValue = J.make_method( "setValue", "(Limagej/module/Module;Ljava/lang/Object;)V", "Set the value associated with this item on the module") getName = J.make_method("getName", "()Ljava/lang/String;") getLabel = J.make_method("getLabel", "()Ljava/lang/String;") getDescription = J.make_method("getDescription", "()Ljava/lang/String;") loadValue = J.make_method("loadValue", "()Ljava/lang/Object;") isInput = J.make_method("isInput", "()Z") isOutput = J.make_method("isOutput", "()Z")
def test_03_08_cw_get_field(self): c = J.get_class_wrapper('java.lang.String') field = c.getField('CASE_INSENSITIVE_ORDER') modifiers = J.call(field, 'getModifiers', '()I') static = J.get_static_field('java/lang/reflect/Modifier', 'STATIC', 'I') self.assertEqual((modifiers & static), static)
def getGrayColorSpace(): """Get a Java object that represents an RGB color space See java.awt.color.ColorSpace: this returns the linear RGB color space """ cs_gray = jutil.get_static_field("java/awt/color/ColorSpace", "CS_GRAY", "I") return jutil.static_call("java/awt/color/ColorSpace", "getInstance", "(I)Ljava/awt/color/ColorSpace;", cs_gray)
class ModuleItem(object): def __init__(self, instance): self.o = instance IV_NORMAL = J.get_static_field("imagej/ext/module/ItemVisibility", "NORMAL", "Limagej/ext/module/ItemVisibility;") IV_TRANSIENT = J.get_static_field( "imagej/ext/module/ItemVisibility", "TRANSIENT", "Limagej/ext/module/ItemVisibility;") IV_INVISIBLE = J.get_static_field( "imagej/ext/module/ItemVisibility", "INVISIBLE", "Limagej/ext/module/ItemVisibility;") IV_MESSAGE = J.get_static_field("imagej/ext/module/ItemVisibility", "MESSAGE", "Limagej/ext/module/ItemVisibility;") WS_DEFAULT = J.get_static_field("imagej/ext/module/ui/WidgetStyle", "DEFAULT", "Limagej/ext/module/ui/WidgetStyle;") WS_NUMBER_SPINNER = J.get_static_field( "imagej/ext/module/ui/WidgetStyle", "NUMBER_SPINNER", "Limagej/ext/module/ui/WidgetStyle;") WS_NUMBER_SLIDER = J.get_static_field( "imagej/ext/module/ui/WidgetStyle", "NUMBER_SLIDER", "Limagej/ext/module/ui/WidgetStyle;") WS_NUMBER_SCROLL_BAR = J.get_static_field( "imagej/ext/module/ui/WidgetStyle", "NUMBER_SCROLL_BAR", "Limagej/ext/module/ui/WidgetStyle;") def getType(self): jtype = J.call(self.o, "getType", "()Ljava/lang/Class;") type_name = J.call(jtype, "getCanonicalName", "()Ljava/lang/String;") if field_mapping.has_key(type_name): return field_mapping[type_name] for class_instance, result in field_class_mapping: if J.call(class_instance, "isAssignableFrom", "(Ljava/lang/Class;)Z", jtype): return result return None getWidgetStyle = J.make_method("getWidgetStyle", "()Limagej/ext/module/ui/WidgetStyle;") getMinimumValue = J.make_method("getMinimumValue", "()Ljava/lang/Object;") getMaximumValue = J.make_method("getMaximumValue", "()Ljava/lang/Object;") getStepSize = J.make_method("getStepSize", "()Ljava/lang/Number;") getColumnCount = J.make_method("getColumnCount", "()I") getChoices = J.make_method("getChoices", "()Ljava/util/List;") getValue = J.make_method( "getValue", "(Limagej/ext/module/Module;)Ljava/lang/Object;") getName = J.make_method("getName", "()Ljava/lang/String;") getLabel = J.make_method("getLabel", "()Ljava/lang/String;") getDescription = J.make_method("getDescription", "()Ljava/lang/String;")
def update_never_remind(): """Tell ImageJ never to remind us of updates Not as harsh as it sounds - this is done with headless preferences which go to /dev/null. """ never = J.get_static_field("java/lang/Long", "MAX_VALUE", "J") J.static_call("imagej/updater/core/UpToDate", "setLatestNag", "(J)V", never)
def update_never_remind(): '''Tell ImageJ never to remind us of updates Not as harsh as it sounds - this is done with headless preferences which go to /dev/null. ''' never = J.get_static_field("java/lang/Long", "MAX_VALUE", "J") J.static_call("imagej/updater/core/UpToDate", "setLatestNag", "(J)V", never)
def getGrayColorSpace(): '''Get a Java object that represents an RGB color space See java.awt.color.ColorSpace: this returns the linear RGB color space ''' cs_gray = jutil.get_static_field('java/awt/color/ColorSpace', 'CS_GRAY', 'I') return jutil.static_call('java/awt/color/ColorSpace', 'getInstance', '(I)Ljava/awt/color/ColorSpace;', cs_gray)
def test_03_09_cw_get_method(self): sclass = J.class_for_name('java.lang.String') iclass = J.get_static_field('java/lang/Integer', 'TYPE', 'Ljava/lang/Class;') c = J.get_class_wrapper('java.lang.String') m = c.getMethod('charAt', [ iclass ]) self.assertEqual(J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'char') m = c.getMethod('concat', [ sclass]) self.assertEqual(J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'class java.lang.String')
def get_metadata_options(level): '''Get an instance of the MetadataOptions interface level - MINIMUM, NO_OVERLAYS or ALL to set the metadata retrieval level The object returned can be used in setMetadataOptions in a format reader. ''' jlevel = jutil.get_static_field('loci/formats/in/MetadataLevel', level, 'Lloci/formats/in/MetadataLevel;') return jutil.make_instance('loci/formats/in/DefaultMetadataOptions', '(Lloci/formats/in/MetadataLevel;)V', jlevel)
def create_img_plus(a, name): '''Create an ImagePlus from a numpy array a - numpy array. The values should be scaled to the range 0-255 name - a user-visible name for the image returns an ImagePlus. The metadata axes will be Y, X and channel (if 3-d) ''' x = J.get_static_field("net/imglib2/img/Axes", "X", "Lnet/imglib2/img/Axes;") y = J.get_static_field("net/imglib2/img/Axes", "Y", "Lnet/imglib2/img/Axes;") c = J.get_static_field("net/imglib2/img/Axes", "CHANNEL", "Lnet/imglib2/img/Axes;") img = create_planar_img(a) img_plus = J.make_instance( "net/imglib2/img/ImgPlus", "(Lnet/imglib2/img/Img;Ljava/lang/String;[Lnet/imglib2/img/Axis;)V", img, name, [y, x] if a.ndim == 2 else [y, x, c])
def test_03_09_cw_get_method(self): sclass = J.class_for_name('java.lang.String') iclass = J.get_static_field('java/lang/Integer', 'TYPE', 'Ljava/lang/Class;') c = J.get_class_wrapper('java.lang.String') m = c.getMethod('charAt', [iclass]) self.assertEqual( J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'char') m = c.getMethod('concat', [sclass]) self.assertEqual( J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'class java.lang.String')
def test_10_04_engine_factory_wrapper(self): svc = ij2.get_script_service(self.context) factory = svc.getByName("ECMAScript") factory.getEngineName() factory.getEngineVersion() factory.getExtensions() factory.getMimeTypes() factory.getNames() factory.getLanguageName() factory.getLanguageVersion() factory.getParameter(J.get_static_field('javax/script/ScriptEngine', 'NAME', 'Ljava/lang/String;')) factory.getMethodCallSyntax("myobject", "mymethod", ["param1", "param2"]) factory.getOutputStatement("Hello, world") factory.getProgram(["I.do.this()", "I.do.that()"]) factory.getScriptEngine()
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()
class ScriptEngine(object): def __init__(self, o=o): self.o = o ARGV = J.get_static_field(klass, "ARGV", "Ljava/lang/String;") FILENAME = J.get_static_field(klass, "FILENAME", "Ljava/lang/String;") ENGINE = J.get_static_field(klass, "ENGINE", "Ljava/lang/String;") ENGINE_VERSION = J.get_static_field(klass, "ENGINE_VERSION", "Ljava/lang/String;") NAME = J.get_static_field(klass, "NAME", "Ljava/lang/String;") LANGUAGE = J.get_static_field(klass, "LANGUAGE", "Ljava/lang/String;") LANGUAGE_VERSION = J.get_static_field(klass, "LANGUAGE_VERSION", "Ljava/lang/String;") evalSSC = J.make_method( "eval", "(Ljava/lang/String;Ljavax/scriptScriptContext;)Ljava/lang/Object;", doc="""Evaluate a script within a context script - the script to run script_context - The context describing the operational scope during the evaluation.""") evalRSC = J.make_method( "eval", "(Ljava/io/Reader;Ljavax/scriptScriptContext;)Ljava/lang/Object;", doc="""Evaluate a script within a context reader - read the script from this reader script_context - The context describing the operational scope during the evaluation.""") evalS = J.make_method( "eval", "(Ljava/lang/String;)Ljava/lang/Object;", doc="""Evaluate a script within the engine's default context script - script to evaluate """) evalR = J.make_method( "eval", "(Ljava/io/Reader;)Ljava/lang/Object;", doc="""Evaluate a script within the engine's default context reader - read the script from here """) evalSB = J.make_method( "eval", "(Ljava/lang/String;Ljavax/script/Bindings;)Ljava/lang/Object;", doc="""Evaluate the script using the bindings as the ENGINE_SCOPE script - the script to be run bindings - bindings of values to variables which are combined with the non ENGINE_SCOPE bindings of the default context to provide an execution scope.""") evalRB = J.make_method( "eval", "(Ljava/io/Reader;Ljavax/script/Bindings;)Ljava/lang/Object;", doc="""Evaluate the script using the bindings as the ENGINE_SCOPE reader- read the script from here bindings - bindings of values to variables which are combined with the non ENGINE_SCOPE bindings of the default context to provide an execution scope.""") put = J.make_method("put", "(Ljava/lang/String;Ljava/lang/Object;)V", doc="""Set the value for some script engine key For non-keywords, this generally adds a key/value binding to the default ENGINE_SCOPE for the script engine. key - name of the value to add value - the value to be given to the key """) get = J.make_method("get", "(Ljava/lang/String;)Ljava/lang/Object;", doc="""Get a value set on the engine's state key - the key to look up """) ENGINE_SCOPE = J.get_static_field("javax/script/ScriptContext", "ENGINE_SCOPE", "I") GLOBAL_SCOPE = J.get_static_field("javax/script/ScriptContext", "GLOBAL_SCOPE", "I") getBindings = J.make_method("getBindings", "(I)Ljavax/script/Bindings;", doc="""Returns a scope of named values. scope - either ScriptContext.ENGINE_SCOPE to get the values set on this engine or ScriptContext.GLOBAL_SCOPE to get the values set by a ScriptEngineManager. """) setBindings = J.make_method( "setBindings", "(Ljavax/script/Bindings;I)V", doc="""Sets the bindings to be used for the engine or global scope bindings - the bindings to use scope - ENGINE_SCOPE to set the script engine's bindings or GLOBAL_SCOPE to set the scope at the manager level. """) createBindings = J.make_method( "createBindings", "()Ljavax/script/Bindings;", doc="""Return a bindings instance appropriate for this engine""") getContext = J.make_method( "getContext", "()Ljavax/script/ScriptContext;", doc="""Return the default ScriptContext for this engine""") setContext = J.make_method( "setContext", "(Ljavax/script/ScriptContext;)V", doc="""Set the default ScriptContext for this engine""") getFactory = J.make_method("getFactory", "()Ljavax/script/ScriptEngineFactory;", doc="Get this engine's factory")
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()
def get_named_axis(self, axis_name): return J.get_static_field("net/imglib2/img/Axes", axis_name, "Lnet/imglib2/img/Axes;")
def test_03_08_cw_get_field(self): c = J.get_class_wrapper('java.lang.String') field = c.getField('CASE_INSENSITIVE_ORDER') modifiers = J.call(field, 'getModifiers', '()I') static = J.get_static_field('java/lang/reflect/Modifier','STATIC','I') self.assertEqual((modifiers & static), static)
class ScriptEngine(object): def __init__(self, o=o): self.o = o ARGV = J.get_static_field(klass, "ARGV", "Ljava/lang/String;") FILENAME = J.get_static_field(klass, "FILENAME", "Ljava/lang/String;") ENGINE = J.get_static_field(klass, "ENGINE", "Ljava/lang/String;") ENGINE_VERSION = J.get_static_field(klass, "ENGINE_VERSION", "Ljava/lang/String;") NAME = J.get_static_field(klass, "NAME", "Ljava/lang/String;") LANGUAGE = J.get_static_field(klass, "LANGUAGE", "Ljava/lang/String;") LANGUAGE_VERSION = J.get_static_field(klass, "LANGUAGE_VERSION", "Ljava/lang/String;") evalS = make_invoke_method( "eval", returns_value=True, doc="""Evaluate a script within the engine's default context script - script to evaluate """) put = J.make_method("put", "(Ljava/lang/String;Ljava/lang/Object;)V", doc="""Set the value for some script engine key For non-keywords, this generally adds a key/value binding to the default ENGINE_SCOPE for the script engine. key - name of the value to add value - the value to be given to the key """) get = J.make_method("get", "(Ljava/lang/String;)Ljava/lang/Object;", doc="""Get a value set on the engine's state key - the key to look up """) ENGINE_SCOPE = J.get_static_field("javax/script/ScriptContext", "ENGINE_SCOPE", "I") GLOBAL_SCOPE = J.get_static_field("javax/script/ScriptContext", "GLOBAL_SCOPE", "I") getBindings = J.make_method("getBindings", "(I)Ljavax/script/Bindings;", doc="""Returns a scope of named values. scope - either ScriptContext.ENGINE_SCOPE to get the values set on this engine or ScriptContext.GLOBAL_SCOPE to get the values set by a ScriptEngineManager. """) setBindings = J.make_method( "setBindings", "(Ljavax/script/Bindings;I)V", doc="""Sets the bindings to be used for the engine or global scope bindings - the bindings to use scope - ENGINE_SCOPE to set the script engine's bindings or GLOBAL_SCOPE to set the scope at the manager level. """) createBindings = J.make_method( "createBindings", "()Ljavax/script/Bindings;", doc="""Return a bindings instance appropriate for this engine""") getContext = J.make_method( "getContext", "()Ljavax/script/ScriptContext;", doc="""Return the default ScriptContext for this engine""") setContext = J.make_method( "setContext", "(Ljavax/script/ScriptContext;)V", doc="""Set the default ScriptContext for this engine""") getFactory = J.make_method("getFactory", "()Ljavax/script/ScriptEngineFactory;", doc="Get this engine's factory")
def test_01_05_get_static_field(self): klass = self.env.find_class("java/lang/Short") self.assertEqual(J.get_static_field(klass, "MAX_VALUE", "S"), 2**15 - 1)
logger.warning("Bioformats version does not support directory cacheing") finally: jutil.detach() # if get_headless() or sys.platform=="darwin": # jutil.attach() # jutil.static_call("java/lang/System", "setProperty", '(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;', "java.awt.headless", "true") # jutil.detach() # # Start the log4j logger to avoid error messages. # if __init_logger: jutil.attach() 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) finally: jutil.detach()
class PixelType(object): '''Provide enums from ome.xml.model.enums.PixelType''' klass = jutil.get_env().find_class('ome/xml/model/enums/PixelType') INT8 = jutil.get_static_field(klass, 'INT8', 'Lome/xml/model/enums/PixelType;') INT16 = jutil.get_static_field(klass, 'INT16', 'Lome/xml/model/enums/PixelType;') INT32 = jutil.get_static_field(klass, 'INT32', 'Lome/xml/model/enums/PixelType;') UINT8 = jutil.get_static_field(klass, 'UINT8', 'Lome/xml/model/enums/PixelType;') UINT16 = jutil.get_static_field(klass, 'UINT16', 'Lome/xml/model/enums/PixelType;') UINT32 = jutil.get_static_field(klass, 'UINT32', 'Lome/xml/model/enums/PixelType;') FLOAT = jutil.get_static_field(klass, 'FLOAT', 'Lome/xml/model/enums/PixelType;') BIT = jutil.get_static_field(klass, 'BIT', 'Lome/xml/model/enums/PixelType;') DOUBLE = jutil.get_static_field(klass, 'DOUBLE', 'Lome/xml/model/enums/PixelType;') COMPLEX = jutil.get_static_field( klass, 'COMPLEX', 'Lome/xml/model/enums/PixelType;') DOUBLECOMPLEX = jutil.get_static_field( klass, 'DOUBLECOMPLEX', 'Lome/xml/model/enums/PixelType;')
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()
class FormatTools(object): '''A wrapper for loci.formats.FormatTools See http://hudson.openmicroscopy.org.uk/job/LOCI/javadoc/loci/formats/FormatTools.html ''' env = jutil.get_env() klass = env.find_class('loci/formats/FormatTools') CAN_GROUP = jutil.get_static_field(klass, 'CAN_GROUP', 'I') CANNOT_GROUP = jutil.get_static_field(klass, 'CANNOT_GROUP', 'I') DOUBLE = jutil.get_static_field(klass, 'DOUBLE', 'I') FLOAT = jutil.get_static_field(klass, 'FLOAT', 'I') INT16 = jutil.get_static_field(klass, 'INT16', 'I') INT32 = jutil.get_static_field(klass, 'INT32', 'I') INT8 = jutil.get_static_field(klass, 'INT8', 'I') MUST_GROUP = jutil.get_static_field(klass, 'MUST_GROUP', 'I') UINT16 = jutil.get_static_field(klass, 'UINT16', 'I') UINT32 = jutil.get_static_field(klass, 'UINT32', 'I') UINT8 = jutil.get_static_field(klass, 'UINT8', 'I') @classmethod def getPixelTypeString(cls, pixel_type): return jutil.static_call('loci/formats/FormatTools', 'getPixelTypeString', '(I)Ljava/lang/String;', pixel_type)
def get_named_axis(self, axis_name): return J.get_static_field("net/imglib2/meta/Axes", axis_name, "Lnet/imglib2/meta/Axes;")
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()
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()
jutil.detach() # if get_headless() or sys.platform=="darwin": # jutil.attach() # jutil.static_call("java/lang/System", "setProperty", '(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;', "java.awt.headless", "true") # jutil.detach() # # Start the log4j logger to avoid error messages. # if __init_logger: jutil.attach() 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) finally: jutil.detach() from formatreader import load_using_bioformats