Skip to content
Skip to breadcrumbs
Skip to header menu
Skip to action menu
Skip to quick search
Quick Search
Browse
Pages
Blog
Labels
Attachments
Mail
Advanced
What’s New
Space Directory
Feed Builder
Keyboard Shortcuts
Confluence Gadgets
Log In
Sign Up
Dashboard
Groovy
Copy Page
You are not logged in. Any changes you make will be marked as
anonymous
. You may want to
Log In
if you already have an account. You can also
Sign Up
for a new account.
This page is being edited by
.
Paragraph
Paragraph
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Preformatted
Quote
Bold
Italic
Underline
More colours
Strikethrough
Subscript
Superscript
Monospace
Clear Formatting
Bullet list
Numbered list
Outdent
Indent
Align left
Align center
Align right
Link
Table
Insert
Insert Content
Image
Link
Attachment
Symbol
Emoticon
Wiki Markup
Horizontal rule
tinymce.confluence.insert_menu.macro_desc
Info
JIRA Issue
Status
Gallery
Tasklist
Table of Contents
Other Macros
Page Layout
No Layout
Two column (simple)
Two column (simple, left sidebar)
Two column (simple, right sidebar)
Three column (simple)
Two column
Two column (left sidebar)
Two column (right sidebar)
Three column
Three column (left and right sidebars)
Undo
Redo
Find/Replace
Keyboard Shortcuts Help
<h2>Introduction</h2><p> 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.</p><p>First a bit of background regarding the application to be scripted:</p><p>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.</p><h2>The solution in overview </h2><h3> Extension points in the GUI:</h3><p>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.</p><p>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).</p><h3> Integration point:</h3><p>To keep the Groovy integration at one location, we created the class ScriptConnector, which is the adaptor between Groovy and the application.<br /> 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.</p><p>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.</p><h3> One plugin script:</h3><p>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.</p><h2>Coming to details </h2><p>Let us have a look at the main class first, so you will see it all from startup on.<br /> Please be aware that the shown source is a simplified form of our productive code.</p><h3> The application main class</h3><p> </p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>// 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(); } } </pre></td></tr></table><p><br class="atl-forced-newline" /> <br class="atl-forced-newline" /> </p><h3> The script connector</h3><p> Now let's look at the ScriptConnector, as this is the important place of Groovy integration:</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>.... 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); } } </pre></td></tr></table><p><br class="atl-forced-newline" /> <br class="atl-forced-newline" /> </p><h3> Customisation: The script plugin.groovy</h3><p> 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.</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>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) } </pre></td></tr></table><p><br class="atl-forced-newline" /> <br class="atl-forced-newline" /> <br class="atl-forced-newline" /> <br class="atl-forced-newline" /> </p><p> 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. </p>
Please type the word appearing in the picture.
Attachments
Labels
Location
Watch this page
< Edit
Preview >
Loading…
Save
Cancel
Next hint
search
attachments
weblink
advanced