commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Rony G. Flatscher (Apache)" <r...@apache.org>
Subject BSF 2.4 in one, two nutshell examples (Re: BSF? (Re: [SCXML] Javascript as expression language
Date Mon, 22 Dec 2008 11:43:29 GMT
Hi there,

Rahul Akolkar wrote:
> On Sat, Dec 20, 2008 at 10:52 AM, Ingmar Kliche
> <ingmar.kliche@googlemail.com> wrote:
>   
>> Hi Rony,
>> we used the native Rhino API. Would be interesting to see if BSF is useful
>> for an integration with commons-SCXML.
>>     
> <snip/>
>
> It is, and would be a welcome addition if it became available (in the
> meantime, native rhino API is just fine too).
>   
Surely, an available evaluation using JavaScript is great already.

Making it possible to add additional scripting languages to the table
would make it even more interesting. In order to allow for such a
versatile functionality a tag or attribute which determines the
scripting language to be used to execute the given script would have to
be provided. (The supporting code for allowing for this exploting BSF
2.4 or 3.0=JSR223 is a few lines of Java code.) 

To picture the easiness of adding such a versatile support (from the
script host side) using BSF a little bit better, maybe the following
example may help:

    import org.apache.bsf.*; // BSF 2.4.0 support

    public class TestSimpleExecUsingRhino {

      public static void main (String[] args) throws java.io.IOException
      {
        try {
         * BSFManager mgr    = new BSFManager ();
          String     jsCode = "java.lang.System.out.println(\"JavaScript/Rhino was here!\")";

          mgr.exec ("javascript", "debug infos", 0, 0, jsCode);*

        } catch (BSFException e) { e.printStackTrace(); }
      }
    }
     

The above example does not supply any arguments nor Java objects to
interact with. Compiling and running it will yield:

    JavaScript/Rhino was here!
      


As you can see, it is extremely easy to have scripts executed using BSF 2.4.

-------------------------------------------------------

It is up to the Java programmer to supply arguments, set up Java objects
in the context for the script to retrieve it and fetching any result
from the script.

The following example will demonstrate:

    * a Java programm that sets up a GUI and registers a Java object
      (the awt Panel object) in the context such that the scripts become
      able to address/retrieve it,
    * a JavaScript program which retrieves the Panel object from the
      context.

Java program "ScriptedUI.java" which creates an awt app, processes the
command line (a filename containing a script, where the file extension
determines the scripting language to use for executing the script),
stored as "ScriptedUI.java":

    /* This example shows how a Java app can allow a script to customize a UI */

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;

    import org.apache.bsf.*;
    import org.apache.bsf.util.*;

    public class ScriptedUI {
      *BSFManager mgr = new BSFManager ();*

      public ScriptedUI (String fileName) {
        Frame f = new Frame ("Application's Main Frame");
        f.addWindowListener (new WindowAdapter () {
          public void windowClosing (WindowEvent e) {
    	System.exit (0);
          }
        });

        Panel p = new Panel ();
        f.add ("Center", p);
        f.add ("North", new Button ("North Button"));
        f.add ("South", new Button ("South Button"));

        *mgr.registerBean ("centerPanel", p); *// register p under the name "centerPanel"*
        mgr.registerBean ("parentFrame", f);* // --rgf, 2006-08-08: to allow Jacl to get to
frame ...

        // exec script engine code to do its thing for this
        try {
          *String language = BSFManager.getLangFromFilename (fileName); // get scripting language
name
          FileReader in = new FileReader (fileName);
          String script = IOUtils.getStringFromReader (in);            // read script from
file

          mgr.exec (language, fileName, -1, -1, script);  // execute script using appropriate
engine*
        } catch (BSFException e) {
          System.err.println ("Ouch: " + e.getMessage ());
          e.printStackTrace ();
        } catch (IOException e) {
          System.err.println ("Ouch: " + e.getMessage ());
          e.printStackTrace ();
        }

        // now pack and show the frame
        f.pack ();
        f.show ();
      }

      public static void main (String[] args) throws Exception {
        if (args.length != 1) {
          System.err.println ("Usage: java ScriptedUI filename");
          System.err.println ("       where filename is the name of the script");
          System.exit (1);
        }
        new ScriptedUI (args[0]);
      }
    }

      

Here is a JavaScript program that retrieves the Panel object from the
context (in bold) and sets various parts of it and finally retrieves the
frame object to change the title, stored as "ui.js":

    /* pick up the center panel bean */
    *p = bsf.lookupBean ("centerPanel");  // get access to the Java
    Panel object*

    /* set the layout manager to border */
    p.setLayout (new java.awt.BorderLayout ());

    /* add a few things */
    p.add ("Center", new java.awt.Label ("Middle from JavaScript"));
    p.add ("North", new java.awt.TextField ("north text from JavaScript"));
    p.add ("South", new java.awt.TextField ("south text from JavaScript"));
    p.add ("East", new java.awt.Button ("inner east from JavaScript"));
    p.add ("West", new java.awt.Button ("inner west from JavaScript"));

    /* configure p a bit */
    p.setBackground (java.awt.Color.red);

    /* configure the frame that p is in */
    f = p.getParent ();
    f.setTitle ("Hello from JavaScript (title reset from JavaScript)");


To invoke this and have the JavaScript program executed from the command
line:

    java ScriptedUI ui.js

---

If you wish to execute a Python/Jython script instead, you could have
stored a matching script as "ui.py":

    """\
    A Python/Jython example for interacting with ScriptedUI.java.
    Rony G. Flatscher, 2006-08-08
    """

    import java
    from java import awt

    *p = bsf.lookupBean('centerPanel')*
    p.setLayout ( awt.BorderLayout () )

    p.add ("Center", java.awt.Label ("Middle from Jython"))
    p.add ("North",  java.awt.TextField ("north text from Jython"))
    p.add ("South",  java.awt.TextField ("south text from Jython"))
    p.add ("East",   java.awt.Button ("inner east from Jython"))
    p.add ("West",   java.awt.Button ("inner west from Jython"))

    p.setBackground (java.awt.Color.orange)

    f = p.getParent ()
    f.setTitle ("Hello from Jython (title reset from Jython)")
      


To invoke this and have the JavaScript program executed from the command
line:

    java ScriptedUI ui.py

----

Or a little bit "exotic" (because most people have never heard of it)
scripting language named Object Rexx (implemented in C++ not Java, still
available because of a BSF-compliant scripting engine), code maybe
stored in a file named "ui.rex":

    *p = .bsf~bsf.lookupBean("centerPanel")*  

    /* set the layout manager to border */
    p~setLayout(.bsf~new("java.awt.BorderLayout"))

    /* add a few things */
    p~add("Center", .bsf~new("java.awt.Label",     "Middle from Object Rexx"))
    p~add("North",  .bsf~new("java.awt.TextField", "North text from Object Rexx"))
    p~add("South",  .bsf~new("java.awt.TextField", "South text from Object Rexx"))
    p~add("East",   .bsf~new("java.awt.Button",    "Inner east text from Object Rexx"))
    p~add("West",   .bsf~new("java.awt.Button",    "Inner west text from Object Rexx"))

    /* configure p a bit */
    p~setBackground(.bsf~bsf.getStaticValue("java.awt.Color", "green"))

    /* configure the frame that p is in */
    f=p~getParent
    f~setTitle("Hello from Object REXX (title reset from Object Rexx)")

    ::requires BSF.CLS    -- get Object Rexx wrapper support for BSF

      

To invoke this and have the JavaScript program executed from the command
line:

    java ScriptedUI ui.rex

---

Again, you can see that once the infrastructure is in place for using
BSF, one can interchange the scripts and also add the scripts
independently of the Java program (the Java program never needs to be
changed in this case).

These were examples for using BSF 2.4.

---

The examples would slightly differ if you were using BSF 3.0 instead.
BSF 3.0 is a totally independent implementation from BSF 2.4 and uses
the package name "javax.script". It is a JSR-223 implementation and
available to Java 1.4 and Java 1.5 installations. Starting with Java
1.6/6 the Java-supplied "javax.script" would be transparently used
instead, because "javax.script" has become part of Java with version 6.
(BSF 3.0 is used in Harmony as an implementation for "javax.script" AFAIK.)

HTH,

---rony





>> 2008/12/16 Rony G. Flatscher (Apache) <rony@apache.org>
>>
>>     
>>> Hi Ingmar,
>>>
>>> how did that get implemented?
>>>
>>> Did you use by any chance BSF <http://jakarta.apache.org/bsf>? If so,
>>> then not only JavaScript/Rhino would be available, but any of the
>>> supported scripting languages!
>>>
>>> ---rony
>>>
>>>
>>>
>>> Ingmar Kliche wrote:
>>>       
>>>> Hi Roger,
>>>>
>>>> yes, we have implemented it and plan to provide it to the project quite
>>>> soon. But the licensing issue is a good point and should be clarified.
>>>> Technically the implementation needs some final cleanup and things like
>>>>         
>>> test
>>>       
>>>> cases. If you can wait another couple of weeks (due to holiday season) it
>>>> should be available.
>>>>
>>>> Regards,
>>>> Ingmar.
>>>>
>>>> 2008/12/16 Roger Hoover <roger.hoover@gmail.com>
>>>>
>>>>
>>>>         
>>>>> Hi,
>>>>>
>>>>> Has anyone implemented Javascript as an expression language in SCXML
>>>>>           
>>> Common
>>>       
>>>>> with Rhino?  Would there be licensing issues with SCXML under Apache
>>>>> license
>>>>> and Rhino under MPL/GPL/LGPL triple license?
>>>>>
>>>>> If it can't be done as part of this project, how hard would it be to
>>>>> implement externally and do others have interest in it?
>>>>>
>>>>> Thanks,
>>>>>
>>>>> Roger
>>>>>
>>>>>           


Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message