Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Introduction

 As I read in the Groovy user mailinglist that some people complained missing information about how to integrate Groovy into Java applications, I decided to give one example of how we integrated Groovy as extension language for our graphical developer tool.

First a bit of background regarding the application to be scripted:

It is a little SDE GUI for starting different build targets for different components in a workarea. As we noticed that, depending on some individual tasks or different roles a developer takes in a team, extension and customisation would be a nice feature, we integrated Groovy as scripting language used to plug in individual features at the user site.

The solution in overview 

 Extension points in the GUI:

We created two "extension points" in the GUI:  An empty "user" menu ready to be filled with items and an empty panel at the bottom of the GUI being able to be filled with e.g. custom buttons.

There is also a specific script output window, where the script can place messages or other textual output. The opening of this window is part of the API (see point 2).

 Integration point:

To keep the Groovy integration at one location, we created the class ScriptConnector, which is the adaptor between Groovy and the application.
It calls the Groovy engine, maintains the binding, provides some API methods to be called inside the Groovy script, leading to better separation which keeps the script clean from the application's intera.

BTW: One requirement was, that errors in the Groovy integration should not break the rest of the application, but should only affect the customised parts, so exceptions are caught and shown as 'warnings' in a dialog window.

 One plugin script:

The plugin feature is provided by one dedicated plugin script which is customisable/extensible by the user. He can use all features the Groovy language provides, so external scripts and programs can be integrated via this script.

Coming to details 

Let us have a look at the main class first, so you will see it all from startup on.
Please be aware that the shown source is a simplified form of our productive code.

 The application main class

 

Code Block
// The main application class
public class SDEGui {

    public static void main(String[] args) {
        SDEGui sdegui =  new SDEGui();
        sdegui.startGui();
    }

    private void startGui() {
        ....
        final SDEGuiWindow window = SDEGuiWindow.getInstance();  // Create the whole "GUI"
        window.show();

        Workspace workarea = SettingManager.getCurrentWorkspace();   // Create the workarea, the object to be scripted
        ....

        // starting the Groovy interpreter
        try {
            startScript(workarea, window);
        }
        catch (Exception e) {
               JOptionPane.showMessageDialog(window, "Exception in groovy script connection: " + e.getMessage(),
                                             "Groovy-error", JOptionPane.WARNING_MESSAGE);
        }
    }

    // Starts the standard Groovy script to setup additional (customised) gui elements
    private void startScript(final Workspace workarea, final SDEGuiWindow window) {

        ScriptConnector connector = new ScriptConnector(workarea, window);   // instanciate the connector ...
        connector.runGuiComponentScript("plugins.groovy");                   // ... and run the plugin script

        window.show();
    }
}



 The script connector

 Now let's look at the ScriptConnector,  as this is the important place of Groovy integration:

Code Block
....
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
....

public class ScriptConnector {
    Binding      binding;  // The 'binding' makes instances of the application objects available as 'variables' in the script
    SDEGuiWindow window;   // The main application window, the GUI in general
    String[]     roots;    // A list of directories to search for Groovy scripts (think of it as a PATH).

    public ScriptConnector(Workspace workarea, SDEGuiWindow window) {
        roots     = new String[]{System.getProperty("user.home"), "." };   // The root list is filled with the locations to be searched for the script
        Binding  scriptenv = new Binding();    // A new Binding is created ...

        scriptenv.setVariable("workarea", workarea);  // ... and filled with two 'variables': the workarea to work on
        scriptenv.setVariable("SDE", this);           // and the current ScriptConnector instance as API provider.
        this.binding = scriptenv;
        this.window  = window;
    }

    // Method to show Groovy related errors/warnings in a dialog window.
    public void showWarning(String message) {
        JOptionPane.showMessageDialog(window, message, "Groovy-error", JOptionPane.WARNING_MESSAGE);
    }


    // This is the main method called from the application code to start the Groovy integration
    public void runGuiComponentScript(String filename) {
         GroovyScriptEngine gse = null;
         try {
             gse = new GroovyScriptEngine(roots);   // instanciating the script engine ...
         } catch (IOException ioe) {
             ioe.printStackTrace();
             showWarning("I/O-Exception in starting Groovy engine. Message is:\n"
                         + ioe.getMessage()
                         + "\n" + prepareStackTrace(ioe));
         }

         if (gse != null) {
             try {
                 gse.run(filename, binding);      // ... and running the specified script
             } catch (ResourceException re) {
                 re.printStackTrace();
                 showWarning("ResourceException in calling groovy script '" + filename +
                             "' Message is:\n" +re.getMessage()
                             + "\n" + prepareStackTrace(re));

             } catch (ScriptException se) {
                 se.printStackTrace();
                 showWarning("ScriptException in calling groovy script '" + filename +
                             "' Message is:\n" +se.getMessage()
                             + "\n" + prepareStackTrace(se));
             }
         }

     }



    // prepare a stacktrace to be shown in an output window
    private String prepareStackTrace(Exception e) {
        Throwable exc = e;
        StringBuffer output = new StringBuffer();
        collectTraces(exc, output);
        if (exc.getCause() != null) {
           exc = exc.getCause();
           output.append("caused by::\n");
           output.append(exc.getMessage());
           output.append("\n");
           collectTraces(exc, output);
        }
        return output.toString();
    }

    private void collectTraces(Throwable e, StringBuffer output) {
        StackTraceElement[] trace = e.getStackTrace();
        for (int i=0; i < trace.length; i++) {
            output.append(trace[i].toString());
            output.append("\n");
        }
    }

    // ----------------- API to be used inside scripts --------------------

    // create a new dialog to display textual output from running scripts
    public ScriptOutputDialog newOutputDialog(String title, String tabTitle) {
        return window.newOutputDialog(title, tabTitle);
    }

    // get the panel instance prepared to contain customised GUI elements, e.g. buttons
    public DynamicPanel getDynpanel() {
        return window.getDynamicPanel();
    }

    // get the user menu instance to add custom items and submenus to.
    public JMenu getUsermenu() {
        return window.getSDEUserMenu();
    }

    // create a process to run a shell command in a given directory
    public Process exec(String command, File inDir) {
        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec(command, null, inDir);
        } catch (Exception e) {
            displayExecError(e.toString());
        }
        return proc;
    }

    // create a process to run a shell command
    public Process exec(String command) {
        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            displayExecError(e.toString());
        }
        return proc;
    }

    private void displayExecError(String message) {
        ScriptOutputDialog win = window.newOutputDialog("Groovy Error", "Error during exec");
        win.addTabPane("error");
        win.println("error", message);
    }

}



 Customisation: The script plugin.groovy

 This is only an (senseless) example of how to create custom buttons and menu items, but in combination with the connector class it will give you an idea of how an application can be customised/scripted with Groovy as scripting language.

Code Block
import groovy.swing.SwingBuilder

// --  declare standard elements --
allButtons = []
allItems   = []
builder    = new SwingBuilder()

// USER CODE ----->

// custom methods doing the different tasks

def runDoSomething() {
    def outp = SDE.newOutputDialog("Plugin-Window")
    outp.show()
    dir = workarea.workdir
    Thread.start() {
            outp.println ("=== ${dir}" )
            def proc = SDE.exec("doSomething.bat", new File("${dir}") )
            outp.useInputStream(proc.in)
            proc.waitFor()
        }
        outp.println("end")
    }
}


def showLogfile() {
    def outp = SDE.newOutputDialog("Plugin-Window")
    outp.show()
    def logfile = new File("logfile.txt")
    logfile.eachLine{ line ->
        outp.println(line)
    }
}


// user gui elements

allButtons << builder.button( text: 'Do Something', actionPerformed: { runDoSomething() } )
allButtons << builder.button( text: 'showLogfile',  actionPerformed: { showLogfile()    } )

allItems << builder.menuItem( text: 'TestItemOne', actionPerformed: { /* more code, you know ... */ } )
allItems << builder.menuItem( text: 'TestItemTwo', actionPerformed: { /* ... here too ... */ } )

// < ------   USER CODE


 // -----  add custom gui elements to the dynamic panel and user menu ---------
allButtons.each { SDE.dynpanel.add(it) }
allItems.each { SDE.usermenu.add(it) }





 I hope this spontaneous little article could give you a help in Groovy application integration and give  a slight idea of what Groovy could do for you.