def context_to_locals(context):
    '''convert the local context as a Java map to a dictionary of locals'''
    d = {"JWrapper": JWrapper, "importClass": importClass}
    m = J.get_map_wrapper(context)
    for k in m:
        key = J.to_string(k)
        o = m[k]
        if isinstance(o, J.JB_Object):
            if J.is_instance_of(o, "java/lang/String"):
                d[key] = J.to_string(o)
                continue
            for class_name, method, signature in (("java/lang/Boolean",
                                                   "booleanValue", "()Z"),
                                                  ("java/lang/Byte",
                                                   "byteValue", "()B"),
                                                  ("java/lang/Integer",
                                                   "intValue", "()I"),
                                                  ("java/lang/Long",
                                                   "longValue", "()L"),
                                                  ("java/lang/Float",
                                                   "floatValue", "()F"),
                                                  ("java/lang/Double",
                                                   "doubleValue", "()D")):
                if J.is_instance_of(o, class_name):
                    d[key] = J.call(o, method, signature)
                    break
            else:
                d[key] = JWrapper(o)
        else:
            d[key] = o

    return d
 def test_03_02_command_service_run(self):
     svc = ij2.get_command_service(self.context)
     module_infos = ij2.get_module_service(self.context).getModules()
     for module_info in module_infos:
         if module_info.getClassName() == \
            'net.imagej.app.AboutImageJ':
             d = J.get_map_wrapper(J.make_instance('java/util/HashMap', '()V'))
             future = svc.run(module_info.o, True, d.o)
             module = future.get()
             module = ij2.wrap_module(module)
             module.getOutput('display')
             break
     else:
         raise AssertionError("Could not find target module")
 def test_03_02_command_service_run(self):
     svc = ij2.get_command_service(self.context)
     module_infos = ij2.get_module_service(self.context).getModules()
     for module_info in module_infos:
         if module_info.getClassName() == \
                 'net.imagej.app.AboutImageJ':
             d = J.get_map_wrapper(J.make_instance('java/util/HashMap', '()V'))
             future = svc.run(module_info.o, True, d.o)
             module = future.get()
             module = ij2.wrap_module(module)
             module.getOutput('display')
             break
     else:
         raise AssertionError("Could not find target module")
    def metadata(self):
        """
        Returns the meta-data.

        :return: the meta-data dictionary
        :rtype: dict
        """
        if self._metadata is None:
            map = javabridge.get_map_wrapper(
                javabridge.call(self.jobject, "getPackageMetaData",
                                "()Ljava/util/Map;"))
            self._metadata = dict()
            for k in map:
                self._metadata[javabridge.get_env().get_string(k)] = map[
                    javabridge.get_env().get_string(k)]
        return self._metadata
Beispiel #5
0
def main(args):
    javabridge.activate_awt()
    script = """
    //--------------------------------------
    //
    // The anonymous callable runs on the thread
    // that started Java - that's the rule with AWT.
    //
    // The callable returns a Java Map whose keys
    // have the labels of objects like "qUp" for
    // the upward queue. Python can then fetch
    // whichever ones it wants and do Java stuff
    // with them.
    //
    //--------------------------------------
    new java.util.concurrent.Callable() {
        call: function() {
            importClass(javax.swing.SpringLayout);
            importClass(javax.swing.JFrame);
            importClass(javax.swing.JTextField);
            importClass(javax.swing.JButton);
            importClass(javax.swing.JScrollPane);
            importClass(javax.swing.JTextArea);
            importClass(java.util.Hashtable);
            importClass(java.awt.event.ActionListener);
            importClass(java.awt.event.WindowAdapter);
            importClass(java.util.concurrent.SynchronousQueue);
            
            d = new Hashtable();
            frame = new JFrame("Callbacks in Java");
            d.put("frame", frame);
            contentPane = frame.getContentPane();
            layout = new SpringLayout();
            contentPane.setLayout(layout);
            
            textField = new JTextField("'Hello, world.'", 60);
            d.put("textField", textField);
            contentPane.add(textField);
            
            execButton = new JButton("Exec");
            contentPane.add(execButton);
            
            evalButton = new JButton("Eval");
            contentPane.add(evalButton);
            
            result = new JTextArea("None");
            scrollPane = new JScrollPane(result)
            contentPane.add(scrollPane);
            d.put("result", result);
            
            //-----------------------------------------------------
            //
            // The layout is:
            //
            // [ textField] [execButton] [evalButton]
            // [    scrollPane                      ]
            //
            //-----------------------------------------------------

            layout.putConstraint(SpringLayout.WEST, textField,
                                 5, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, textField,
                                 5, SpringLayout.NORTH, contentPane);

            layout.putConstraint(SpringLayout.WEST, execButton,
                                 5, SpringLayout.EAST, textField);
            layout.putConstraint(SpringLayout.NORTH, execButton,
                                 0, SpringLayout.NORTH, textField);
                                 
            layout.putConstraint(SpringLayout.WEST, evalButton,
                                 5, SpringLayout.EAST, execButton);
            layout.putConstraint(SpringLayout.NORTH, evalButton,
                                 0, SpringLayout.NORTH, textField);

            layout.putConstraint(SpringLayout.NORTH, scrollPane,
                                 5, SpringLayout.SOUTH, textField);
            layout.putConstraint(SpringLayout.WEST, scrollPane,
                                 0, SpringLayout.WEST, textField);
            layout.putConstraint(SpringLayout.EAST, scrollPane,
                                 0, SpringLayout.EAST, evalButton);
                                 
            layout.putConstraint(SpringLayout.EAST, contentPane,
                                 5, SpringLayout.EAST, evalButton);
            layout.putConstraint(SpringLayout.SOUTH, contentPane,
                                 20, SpringLayout.SOUTH, scrollPane);
            
            //------------------------------------------------
            //
            // qUp sends messages from Java to Python
            // qDown sends messages from Python to Java
            //
            // The communications protocol is that qUp sends
            // a command. For Exec and Eval commands, qUp sends
            // text and qDown must send a reply to continue.
            // For the Exit command, qUp sends the command and
            // Python must dispose of Java
            //
            //-------------------------------------------------
            
            qUp = new SynchronousQueue();
            qDown = new SynchronousQueue();
            d.put("qUp", qUp);
            d.put("qDown", qDown);
            
            //-----------------------------------------------
            //
            // Create an action listener that binds the execButton
            // action to a function that instructs Python to
            // execute the contents of the text field.
            //
            //-----------------------------------------------
            alExec = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Exec");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            execButton.addActionListener(alExec);

            //-----------------------------------------------
            //
            // Create an action listener that binds the evalButton
            // action to a function that instructs Python to
            // evaluate the contents of the text field.
            //
            //-----------------------------------------------
            alEval = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Eval");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            evalButton.addActionListener(alEval);
            
            //-----------------------------------------------
            //
            // Create a window listener that binds the frame's
            // windowClosing action to a function that instructs 
            // Python to exit.
            //
            //-----------------------------------------------
            wl = new WindowAdapter() {
                windowClosing: function(e) {
                    qUp.put("Exit");
                }
            };
            
            frame.addWindowListener(wl);

            frame.pack();
            frame.setVisible(true);
            return d;
        }
    };"""
    c = javabridge.run_script(script)
    f = javabridge.make_future_task(c)
    d = javabridge.execute_future_in_main_thread(f)
    d = javabridge.get_map_wrapper(d)
    qUp = d["qUp"]
    qDown = d["qDown"]
    frame = d["frame"]
    while True:
        cmd = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Exit":
            break
        text = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Eval":
            try:
                result = eval(text, globals(), locals())
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"
        else:
            try:
                exec(text, globals(), locals())
                result = "Operation succeeded"
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"

        javabridge.run_script("qDown.put(result);",
                              dict(qDown=qDown, result=str(result)))
    javabridge.run_script("frame.dispose();", dict(frame=frame))
def main(args):
    javabridge.activate_awt()
    script = """
    //--------------------------------------
    //
    // The anonymous callable runs on the thread
    // that started Java - that's the rule with AWT.
    //
    // The callable returns a Java Map whose keys
    // have the labels of objects like "qUp" for
    // the upward queue. Python can then fetch
    // whichever ones it wants and do Java stuff
    // with them.
    //
    //--------------------------------------
    new java.util.concurrent.Callable() {
        call: function() {
            importClass(javax.swing.SpringLayout);
            importClass(javax.swing.JFrame);
            importClass(javax.swing.JTextField);
            importClass(javax.swing.JButton);
            importClass(javax.swing.JScrollPane);
            importClass(javax.swing.JTextArea);
            importClass(java.util.Hashtable);
            importClass(java.awt.event.ActionListener);
            importClass(java.awt.event.WindowAdapter);
            importClass(java.util.concurrent.SynchronousQueue);
            
            d = new Hashtable();
            frame = new JFrame("Callbacks in Java");
            d.put("frame", frame);
            contentPane = frame.getContentPane();
            layout = new SpringLayout();
            contentPane.setLayout(layout);
            
            textField = new JTextField("'Hello, world.'", 60);
            d.put("textField", textField);
            contentPane.add(textField);
            
            execButton = new JButton("Exec");
            contentPane.add(execButton);
            
            evalButton = new JButton("Eval");
            contentPane.add(evalButton);
            
            result = new JTextArea("None");
            scrollPane = new JScrollPane(result)
            contentPane.add(scrollPane);
            d.put("result", result);
            
            //-----------------------------------------------------
            //
            // The layout is:
            //
            // [ textField] [execButton] [evalButton]
            // [    scrollPane                      ]
            //
            //-----------------------------------------------------

            layout.putConstraint(SpringLayout.WEST, textField,
                                 5, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, textField,
                                 5, SpringLayout.NORTH, contentPane);

            layout.putConstraint(SpringLayout.WEST, execButton,
                                 5, SpringLayout.EAST, textField);
            layout.putConstraint(SpringLayout.NORTH, execButton,
                                 0, SpringLayout.NORTH, textField);
                                 
            layout.putConstraint(SpringLayout.WEST, evalButton,
                                 5, SpringLayout.EAST, execButton);
            layout.putConstraint(SpringLayout.NORTH, evalButton,
                                 0, SpringLayout.NORTH, textField);

            layout.putConstraint(SpringLayout.NORTH, scrollPane,
                                 5, SpringLayout.SOUTH, textField);
            layout.putConstraint(SpringLayout.WEST, scrollPane,
                                 0, SpringLayout.WEST, textField);
            layout.putConstraint(SpringLayout.EAST, scrollPane,
                                 0, SpringLayout.EAST, evalButton);
                                 
            layout.putConstraint(SpringLayout.EAST, contentPane,
                                 5, SpringLayout.EAST, evalButton);
            layout.putConstraint(SpringLayout.SOUTH, contentPane,
                                 20, SpringLayout.SOUTH, scrollPane);
            
            //------------------------------------------------
            //
            // qUp sends messages from Java to Python
            // qDown sends messages from Python to Java
            //
            // The communications protocol is that qUp sends
            // a command. For Exec and Eval commands, qUp sends
            // text and qDown must send a reply to continue.
            // For the Exit command, qUp sends the command and
            // Python must dispose of Java
            //
            //-------------------------------------------------
            
            qUp = new SynchronousQueue();
            qDown = new SynchronousQueue();
            d.put("qUp", qUp);
            d.put("qDown", qDown);
            
            //-----------------------------------------------
            //
            // Create an action listener that binds the execButton
            // action to a function that instructs Python to
            // execute the contents of the text field.
            //
            //-----------------------------------------------
            alExec = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Exec");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            execButton.addActionListener(alExec);

            //-----------------------------------------------
            //
            // Create an action listener that binds the evalButton
            // action to a function that instructs Python to
            // evaluate the contents of the text field.
            //
            //-----------------------------------------------
            alEval = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Eval");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            evalButton.addActionListener(alEval);
            
            //-----------------------------------------------
            //
            // Create a window listener that binds the frame's
            // windowClosing action to a function that instructs 
            // Python to exit.
            //
            //-----------------------------------------------
            wl = new WindowAdapter() {
                windowClosing: function(e) {
                    qUp.put("Exit");
                }
            };
            
            frame.addWindowListener(wl);

            frame.pack();
            frame.setVisible(true);
            return d;
        }
    };"""
    c = javabridge.run_script(script);
    f = javabridge.make_future_task(c)
    d = javabridge.execute_future_in_main_thread(f);
    d = javabridge.get_map_wrapper(d)
    qUp = d["qUp"]
    qDown = d["qDown"]
    frame = d["frame"]
    while True:
        cmd = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Exit":
            break
        text = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Eval":
            try:
                result = eval(text, globals(), locals())
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"
        else:
            try:
                exec(text, globals(), locals())
                result = "Operation succeeded"
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"
            
        javabridge.run_script("qDown.put(result);", 
                              dict(qDown=qDown, result = str(result)))
    javabridge.run_script("frame.dispose();", dict(frame=frame))
Beispiel #7
0
def main(args):
    javabridge.activate_awt()
    cpython = javabridge.make_instance(
        "org/cellprofiler/javabridge/CPython", "()V")
    script = """
    //--------------------------------------
    //
    // The anonymous callable runs on the thread
    // that started Java - that's the rule with AWT.
    //
    // The callable returns a Java Map whose keys
    // have the labels of objects like "qUp" for
    // the upward queue. Python can then fetch
    // whichever ones it wants and do Java stuff
    // with them.
    //
    //--------------------------------------
    new java.util.concurrent.Callable() {
        call: function() {
            importClass(javax.swing.SpringLayout);
            importClass(javax.swing.JFrame);
            importClass(javax.swing.JTextField);
            importClass(javax.swing.JButton);
            importClass(javax.swing.JScrollPane);
            importClass(javax.swing.JTextArea);
            importClass(java.util.Hashtable);
            importClass(java.util.ArrayList);
            importClass(java.util.concurrent.CountDownLatch);
            importClass(java.awt.event.ActionListener);
            importClass(java.awt.event.WindowAdapter);
            
            d = new Hashtable();
            signal = new CountDownLatch(1);
            d.put("signal", signal);
            frame = new JFrame("Callbacks in Java");
            d.put("frame", frame);
            contentPane = frame.getContentPane();
            layout = new SpringLayout();
            contentPane.setLayout(layout);
            
            textField = new JTextField("'Hello, world.'", 60);
            d.put("textField", textField);
            contentPane.add(textField);
            
            execButton = new JButton("Exec");
            contentPane.add(execButton);
            
            evalButton = new JButton("Eval");
            contentPane.add(evalButton);
            
            result = new JTextArea("None");
            scrollPane = new JScrollPane(result)
            contentPane.add(scrollPane);
            d.put("result", result);
            
            //-----------------------------------------------------
            //
            // The layout is:
            //
            // [ textField] [execButton] [evalButton]
            // [    scrollPane                      ]
            //
            //-----------------------------------------------------

            layout.putConstraint(SpringLayout.WEST, textField,
                                 5, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, textField,
                                 5, SpringLayout.NORTH, contentPane);

            layout.putConstraint(SpringLayout.WEST, execButton,
                                 5, SpringLayout.EAST, textField);
            layout.putConstraint(SpringLayout.NORTH, execButton,
                                 0, SpringLayout.NORTH, textField);
                                 
            layout.putConstraint(SpringLayout.WEST, evalButton,
                                 5, SpringLayout.EAST, execButton);
            layout.putConstraint(SpringLayout.NORTH, evalButton,
                                 0, SpringLayout.NORTH, textField);

            layout.putConstraint(SpringLayout.NORTH, scrollPane,
                                 5, SpringLayout.SOUTH, textField);
            layout.putConstraint(SpringLayout.WEST, scrollPane,
                                 0, SpringLayout.WEST, textField);
            layout.putConstraint(SpringLayout.EAST, scrollPane,
                                 0, SpringLayout.EAST, evalButton);
                                 
            layout.putConstraint(SpringLayout.EAST, contentPane,
                                 5, SpringLayout.EAST, evalButton);
            layout.putConstraint(SpringLayout.SOUTH, contentPane,
                                 20, SpringLayout.SOUTH, scrollPane);
            
            //-----------------------------------------------
            //
            // Create an action listener that binds the execButton
            // action to a function that instructs Python to
            // execute the contents of the text field.
            //
            //-----------------------------------------------
            alExec = new ActionListener() {
                actionPerformed: function(e) {
                    try {
                        cpython.exec(textField.getText());
                        result.setText("OK");
                    } catch(err) {
                        result.setText(err.message);
                    }
                }
            };
            execButton.addActionListener(alExec);

            //-----------------------------------------------
            //
            // Create an action listener that binds the evalButton
            // action to a function that instructs Python to
            // evaluate the contents of the text field.
            //
            //-----------------------------------------------
            alEval = new ActionListener() {
                actionPerformed: function(e) {
                    try {
                        locals = new Hashtable();
                        jresult = new ArrayList();
                        locals.put("script", textField.getText());
                        locals.put("jresult", jresult);
                        script = "import javabridge\\n" +
                                 "result=eval(javabridge.to_string(script))\\n" +
                                 "jwresult=javabridge.JWrapper(jresult)\\n" +
                                 "jwresult.add(str(result))"
                        cpython.exec(script, locals, null);
                        result.setText(jresult.get(0));
                    } catch(err) {
                        result.setText(err.message);
                    }
                }
            };
            evalButton.addActionListener(alEval);
            
            //-----------------------------------------------
            //
            // Create a window listener that binds the frame's
            // windowClosing action to a function that instructs 
            // Python to exit.
            //
            //-----------------------------------------------
            wl = new WindowAdapter() {
                windowClosing: function(e) {
                    signal.countDown();
                }
            };
            
            frame.addWindowListener(wl);

            frame.pack();
            frame.setVisible(true);
            return d;
        }
    };"""
    c = javabridge.run_script(script, dict(cpython=cpython));
    f = javabridge.make_future_task(c)
    d = javabridge.execute_future_in_main_thread(f);
    d = javabridge.get_map_wrapper(d)
    frame = javabridge.JWrapper(d["frame"])
    signal = javabridge.JWrapper(d["signal"]);
    signal.await();
    frame.dispose();