def field_class_mapping(): return ( (J.class_for_name('net.imagej.display.ImageDisplay'), FT_IMAGE), (J.class_for_name('net.imagej.Dataset'), FT_IMAGE), (J.class_for_name('net.imagej.display.DatasetView'), FT_IMAGE), (J.class_for_name('net.imagej.table.TableDisplay'), FT_TABLE), (J.class_for_name('org.scijava.plugin.SciJavaPlugin'), FT_PLUGIN) )
def get_plugin(classname): '''Return an instance of the named plugin''' if classname.startswith("ij."): cls = J.class_for_name(classname) else: cls = J.class_for_name(classname, get_user_loader()) cls = J.get_class_wrapper(cls, True) constructor = J.get_constructor_wrapper(cls.getConstructor(None)) return constructor.newInstance(None)
def get_context(): '''Get the ImageJ context This is a singleton ImageJ context. We need a singleton for now because of http://trac.imagej.net/ticket/1413 This is an imagej.ImageJ, which at one point was the context. Call self.getContext() to get the org.scijava.Context which may be what you want. ''' global the_imagej_context if the_imagej_context is None: the_imagej_context = create_context(None) # # We have to turn off the updater and tell ImageJ to never call # System.exit. We have to tell ImageJ that we read the readme file. # # To Do: programatically turn off the updater and take control of # the quitting and exit process. # max_value = J.run_script( "java.lang.Long.toString(java.lang.Long.MAX_VALUE);") prefs = [("net.imagej.updater.UpToDate", "latestNag", max_value), ("net.imagej.options.OptionsMisc", "exitWhenQuitting", "false")] plugin_service = the_imagej_context.getService( "org.scijava.plugin.PluginService") ui_interface = J.class_for_name("org.scijava.ui.UserInterface") script = """ var result = java.lang.System.getProperty('ij.ui'); if (! result) { var infos = pluginService.getPluginsOfType(ui_interface); if (infos.size() > 0) { result = infos.get(0).getClassName(); } } result;""" ui_class = J.run_script( script, dict(pluginService=plugin_service, ui_interface=ui_interface)) first_run = "firstRun-" + the_imagej_context.getVersion() if ui_class: prefs.append((ui_class, first_run, "false")) for class_name, key, value in prefs: c = J.class_for_name(class_name) J.static_call( "org/scijava/util/Prefs", "put", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)V", c, key, value) return the_imagej_context
def get_context(): '''Get the ImageJ context This is a singleton ImageJ context. We need a singleton for now because of http://trac.imagej.net/ticket/1413 This is an imagej.ImageJ, which at one point was the context. Call self.getContext() to get the org.scijava.Context which may be what you want. ''' global the_imagej_context if the_imagej_context is None: the_imagej_context = create_context(None) # # We have to turn off the updater and tell ImageJ to never call # System.exit. We have to tell ImageJ that we read the readme file. # # To Do: programatically turn off the updater and take control of # the quitting and exit process. # max_value = J.run_script( "java.lang.Long.toString(java.lang.Long.MAX_VALUE);") prefs = [ ("net.imagej.updater.UpToDate", "latestNag", max_value), ("net.imagej.options.OptionsMisc", "exitWhenQuitting", "false")] plugin_service = the_imagej_context.getService( "org.scijava.plugin.PluginService") ui_interface = J.class_for_name("org.scijava.ui.UserInterface") script = """ var result = java.lang.System.getProperty('ij.ui'); if (! result) { var infos = pluginService.getPluginsOfType(ui_interface); if (infos.size() > 0) { result = infos.get(0).getClassName(); } } result;""" ui_class = J.run_script(script, dict(pluginService=plugin_service, ui_interface=ui_interface)) first_run = "firstRun-"+the_imagej_context.getVersion() if ui_class: prefs.append((ui_class, first_run, "false")) for class_name, key, value in prefs: c = J.class_for_name(class_name) J.static_call( "org/scijava/util/Prefs", "put", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)V", c, key, value) return the_imagej_context
def __init__(self, class_name): '''Initialize to wrap a class name :param class_name: name of class in dotted form, e.g. java.lang.Integer ''' STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") self.cname = class_name.replace(".", "/") self.klass = J.get_class_wrapper(J.class_for_name(class_name), True) self.static_methods = {} env = J.get_env() jmethods = env.get_object_array_elements(self.klass.getMethods()) methods = {} for jmethod in jmethods: if (J.call(jmethod, "getModifiers", "()I") & STATIC) != STATIC: continue method = J.get_method_wrapper(jmethod) name = method.getName() if name not in methods: methods[name] = [] fn = lambda naame=name: lambda *args: self.__call_static(naame, *args) fn = fn() fn.__doc__ = J.to_string(jmethod) setattr(self, name, fn) else: fn = getattr(self, name) fn.__doc__ = fn.__doc__ +"\n"+J.to_string(jmethod) methods[name].append(method) self.methods = methods
def prepare_run(self, workspace): '''Create an IPD for every url that passes the filter''' if workspace.pipeline.in_batch_mode(): return True file_list = workspace.pipeline.file_list if self.filter_choice != FILTER_CHOICE_NONE: if self.filter_choice == FILTER_CHOICE_IMAGES: expression = FILTER_DEFAULT else: expression = self.filter.value_text env = J.get_env() ifcls = J.class_for_name("org.cellprofiler.imageset.ImageFile") scls = env.find_class("java/lang/String") iffilter = J.make_instance( "org/cellprofiler/imageset/filter/Filter", "(Ljava/lang/String;Ljava/lang/Class;)V", expression, ifcls) file_array = env.make_object_array(len(file_list), scls) for i, url in enumerate(file_list): if isinstance(url, unicode): ourl = env.new_string(url) else: ourl = env.new_string_utf(url) env.set_object_array_element(file_array, i, ourl) passes_filter = J.call( iffilter, "filterURLs", "([Ljava/lang/String;)[Z", file_array) if isinstance(passes_filter, J.JB_Object): passes_filter = J.get_env().get_boolean_array_elements( passes_filter) file_list = [f for f, passes in zip(file_list, passes_filter) if passes] workspace.pipeline.set_filtered_file_list(file_list, self) return True
def __init__(self, base_class_name, d=None): '''Initialize the proxy with the interface name and methods :param base_class_name: the class name of the interface to implement in dotted form (e.g. java.lang.Runnable) :param d: an optional dictionary of method name to implementation ''' self.ref_id, self.ref = J.create_jref(self) self.__d = d or {} jclass = J.class_for_name(base_class_name) loader = J.call(jclass, "getClassLoader", "()Ljava/lang/ClassLoader;") env = J.get_env() classes = env.make_object_array(1, env.find_class("java/lang/Class")) env.set_object_array_element(classes, 0, jclass) handler = J.make_instance( "org/cellprofiler/javabridge/CPythonInvocationHandler", "(Ljava/lang/String;)V", self.ref_id) self.o = J.static_call( "java/lang/reflect/Proxy", "newProxyInstance", "(Ljava/lang/ClassLoader;" "[Ljava/lang/Class;" "Ljava/lang/reflect/InvocationHandler;)" "Ljava/lang/Object;", loader, classes, handler)
def __init__(self): env = jutil.get_env() class_name = 'loci/formats/ImageReader' klass = env.find_class(class_name) base_klass = env.find_class('loci/formats/IFormatReader') self.o = jutil.make_instance( "loci/formats/ClassList", "(Ljava/lang/String;" "Ljava/lang/Class;" # base "Ljava/lang/Class;)V", # location in jar "readers.txt", base_klass, klass) problem_classes = [ # BDReader will read all .tif files in an experiment if it's # called to load a .tif. # 'loci.formats.in.BDReader', # # MRCReader will read .stk files which should be read # by MetamorphReader # 'loci.formats.in.MRCReader' ] for problem_class in problem_classes: # Move to back klass = jutil.class_for_name(problem_class) self.remove_class(klass) self.add_class(klass)
def __init__(self): env = jutil.get_env() class_name = 'loci/formats/ImageReader' klass = env.find_class(class_name) base_klass = env.find_class('loci/formats/IFormatReader') self.o = jutil.make_instance("loci/formats/ClassList", "(Ljava/lang/String;" "Ljava/lang/Class;" # base "Ljava/lang/Class;)V", # location in jar "readers.txt", base_klass, klass) problem_classes = [ # BDReader will read all .tif files in an experiment if it's # called to load a .tif. # 'loci.formats.in.BDReader', # # MRCReader will read .stk files which should be read # by MetamorphReader # 'loci.formats.in.MRCReader' ] for problem_class in problem_classes: # Move to back klass = jutil.class_for_name(problem_class) self.remove_class(klass) self.add_class(klass)
def prepare_run(self, workspace): '''Create an IPD for every url that passes the filter''' if workspace.pipeline.in_batch_mode(): return True file_list = workspace.pipeline.file_list if self.filter_choice != FILTER_CHOICE_NONE: if self.filter_choice == FILTER_CHOICE_IMAGES: expression = FILTER_DEFAULT else: expression = self.filter.value_text env = J.get_env() ifcls = J.class_for_name("org.cellprofiler.imageset.ImageFile") scls = env.find_class("java/lang/String") iffilter = J.make_instance( "org/cellprofiler/imageset/filter/Filter", "(Ljava/lang/String;Ljava/lang/Class;)V", expression, ifcls) file_array = env.make_object_array(len(file_list), scls) for i, url in enumerate(file_list): if isinstance(url, unicode): ourl = env.new_string(url) else: ourl = env.new_string_utf(url) env.set_object_array_element(file_array, i, ourl) passes_filter = J.call(iffilter, "filterURLs", "([Ljava/lang/String;)[Z", file_array) if isinstance(passes_filter, J.JB_Object): passes_filter = J.get_env().get_boolean_array_elements( passes_filter) file_list = [ f for f, passes in zip(file_list, passes_filter) if passes ] workspace.pipeline.set_filtered_file_list(file_list, self) return True
def __init__(self, class_name): '''Initialize to wrap a class name :param class_name: name of class in dotted form, e.g. java.lang.Integer ''' STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") self.cname = class_name.replace(".", "/") self.klass = J.get_class_wrapper(J.class_for_name(class_name), True) self.static_methods = {} methods = env.get_object_array_elements(self.klass.getMethods()) self.methods = {} for jmethod in methods: if (J.call(jmethod, "getModifiers", "()I") & STATIC) != STATIC: continue method = J.get_method_wrapper(jmethod) name = method.getName() if name not in self.methods: self.methods[name] = [] fn = lambda naame=name: lambda *args: self.__call_static( naame, *args) fn = fn() fn.__doc__ = J.to_string(jmethod) setattr(self, name, fn) else: fn = getattr(self, name) fn.__doc__ = fn.__doc__ + "\n" + J.to_string(jmethod) self.methods[name].append(method)
def test_03_11_cw_get_constructor(self): c = javabridge.get_class_wrapper('java.lang.String') sclass = javabridge.class_for_name('java.lang.String') constructor = c.getConstructor([sclass]) self.assertEqual( javabridge.call(constructor, 'getName', '()Ljava/lang/String;'), 'java.lang.String')
def get_jclass(classname): """ Returns the Java class object associated with the dot-notation classname. :param classname: the classname :type classname: str :return: the class object :rtype: JB_Object """ return javabridge.class_for_name(classname=classname)
def test_01_04_call_varargs(self): sclass = J.JWrapper(J.class_for_name("java.lang.String")); for constructor in J.get_env().get_object_array_elements( sclass.getConstructors().o): wconstructor = J.JWrapper(constructor) parameter_types = J.get_env().get_object_array_elements( wconstructor.getParameterTypes().o) c1 = sclass.getConstructor(*parameter_types) self.assertTrue(c1.equals(constructor))
def getIndex(self): index = J.call(self.o, "getIndex", "()Limagej/module/ModuleIndex;") index = J.get_collection_wrapper(index, wrap_module_info) index.getC = lambda c: J.get_collection_wrapper( J.call(index.o, "get", "(Ljava/lang/Class;)Ljava/util/List;",c), wrap_module_info) index.getS = lambda class_name: \ index.getC(J.class_for_name(class_name)) return index
def test_01_04_call_varargs(self): sclass = J.JWrapper(J.class_for_name("java.lang.String")) for constructor in J.get_env().get_object_array_elements( sclass.getConstructors().o): wconstructor = J.JWrapper(constructor) parameter_types = J.get_env().get_object_array_elements( wconstructor.getParameterTypes().o) c1 = sclass.getConstructor(*parameter_types) self.assertTrue(c1.equals(constructor))
def getService(self, class_name): '''Get a service with the given class name class_name - class name in dotted form returns the class or None if no implementor loaded. ''' klass = J.class_for_name(class_name) return J.call(self.o, 'get', '(Ljava/lang/Class;)Lorg/scijava/service/Service;', klass)
def test_03_09_cw_get_method(self): sclass = javabridge.class_for_name('java.lang.String') iclass = javabridge.get_static_field('java/lang/Integer', 'TYPE', 'Ljava/lang/Class;') c = javabridge.get_class_wrapper('java.lang.String') m = c.getMethod('charAt', [ iclass ]) self.assertEqual(javabridge.to_string(javabridge.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'char') m = c.getMethod('concat', [ sclass]) self.assertEqual(javabridge.to_string(javabridge.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'class java.lang.String')
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", dir=cellprofiler.preferences.get_temporary_directory()) 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"): try: klass = javabridge.class_for_name(classname) class_list.add_class(klass) except: logger.warn("Could not find Bio-formats reader %s" % classname, exc_info=1) for klass in problem_classes: class_list.add_class(klass) return class_list
def new_instance(cls, classname, length): """ Creates a new array with the given classname and length; initial values are null. :param classname: the classname in Java notation (eg "weka.core.DenseInstance") :type classname: str :param length: the length of the array :type length: int :return: the Java array :rtype: JB_Object """ return javabridge.static_call( "Ljava/lang/reflect/Array;", "newInstance", "(Ljava/lang/Class;I)Ljava/lang/Object;", javabridge.class_for_name(classname=classname), length)
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", dir=cpprefs.get_temporary_directory()) 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"): try: klass = javabridge.class_for_name(classname) class_list.add_class(klass) except: logger.warn("Could not find Bio-formats reader %s" % classname, exc_info=1) for klass in problem_classes: class_list.add_class(klass) return class_list
def __init__(self, jobject=None, enum=None, member=None): """ Initializes the enum class. :param jobject: the Java object to wrap :type jobject: JB_Object :param enum: the enum class to instantiate (dot notation) :type enum: str :param member: the member of the enum class to instantiate :type member: str """ if jobject is None: enumclass = javabridge.class_for_name(classname=enum) jobject = javabridge.static_call( "java/lang/Enum", "valueOf", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;", enumclass, member) super(Enum, self).__init__(jobject)
def test_valid(self, pipeline): try: import javabridge as J J.run_script( """ importPackage(Packages.org.cellprofiler.imageset.filter); new Filter(expr, klass); """, dict( expr=self.value_text, klass=J.class_for_name( "org.cellprofiler.imageset.ImagePlaneDetailsStack"), ), ) except Exception as e: raise ValidationError(str(e), self)
def __init__(self): if service_classes is None: classes = None ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(false); } }""") else: classes = [ J.class_for_name(x) for x in service_classes or REQUIRED_SERVICES] classes = J.make_list(classes) ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(classes); } }""", dict(classes = classes.o)) self.o = J.call(ctxt_fn, 'call', '()Ljava/lang/Object;')
def __init__(self): if service_classes is None: classes = None ctxt_fn = J.run_script("""new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(false); } }""") else: classes = [ J.class_for_name(x) for x in service_classes or REQUIRED_SERVICES ] classes = J.make_list(classes) ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(classes); } }""", dict(classes=classes.o)) self.o = J.execute_future_in_main_thread( J.make_future_task(ctxt_fn))
def __init__(self): if service_classes is None: classes = None ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(false); } }""") else: classes = [ J.class_for_name(x) for x in service_classes or REQUIRED_SERVICES] classes = J.make_list(classes) ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(classes); } }""", dict(classes = classes.o)) self.o = J.execute_future_in_main_thread( J.make_future_task(ctxt_fn))
def getActiveImageDisplay(self): '''Get the active imagej.data.display.ImageDisplay''' return wrap_display(J.call( self.o, "getActiveDisplay", "()Lorg/scijava/display/Display;", J.class_for_name("net.imagej.display.ImageDisplay")))
def test_03_04_cw_get_annotation(self): c = javabridge.get_class_wrapper('java.security.Identity') annotation = c.getAnnotation( javabridge.class_for_name('java.lang.Deprecated')) self.assertTrue(annotation is not None)
def test_01_11_class_for_name(self): c = javabridge.class_for_name('java.lang.String') name = javabridge.call(c, 'getCanonicalName', '()Ljava/lang/String;') self.assertEqual(name, 'java.lang.String')
def getActiveImageDisplay(self): '''Get the active imagej.data.display.ImageDisplay''' return wrap_display( J.call(self.o, "getActiveDisplay", "()Lorg/scijava/display/Display;", J.class_for_name("net.imagej.display.ImageDisplay")))
def test_03_11_cw_get_constructor(self): c = javabridge.get_class_wrapper('java.lang.String') sclass = javabridge.class_for_name('java.lang.String') constructor = c.getConstructor([sclass]) self.assertEqual(javabridge.call(constructor, 'getName', '()Ljava/lang/String;'), 'java.lang.String')
def test_03_04_cw_get_annotation(self): c = javabridge.get_class_wrapper('java.security.Identity') annotation = c.getAnnotation(javabridge.class_for_name('java.lang.Deprecated')) self.assertTrue(annotation is not None)