Saturday, October 4, 2008

Groovy as extension for Netbeans editor

As you know I work a lot with xml files (see my Xml/Xsl posts). Xml files are perfect for storing informations in structured way. Sometimes there is need for refactoring those informations. By refactoring I mean nodes/attributes renaming, changing value or place of those. If file is too big, that task may be very-very boring doing it by hand. Of course you can use your favorite text editor's search-replace feature but for complex tasks you will end writing utility for processing xml.
I played a little bit with Groovy and GroovyShell and noticed that you can easily pass your (java) variables to it. It means that you can pass your editor's document and process it with Groovy.
I created simple module for processing xml files. It is based on XPathEvaluator module. It adds a new window to Netbeans where you can write Groovy scripts.


Code for "Run Script" button looks like this:
Binding binding = new Binding();
binding.setVariable("doc", xmlDoc);
binding.setVariable("output", jTextArea1);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate(jEditorPane1.getText());

It binds xmlDoc, which is EditorCookie.getDocument(), to doc variable and evaluates the script which is in jEditorArea.

Maybe a Groovy could be a new way for extending Netbeans? Tell me what you think.

3 comments:

Anonymous said...

thank u r information

it very useful

Alex Kochnev said...

Damir,
quite interesting. I've tried to do something similar (e.g. embedding a groovy console inside NetBeans, but I ran into some issues doing so, see details at http://www.nabble.com/Groovy-Editor-%3A-exposing-packages-from-groovy-all.jar-as-public-packages-td20287396.html#a20287396). Would you consider posting the source code to your module ?

damir said...

Thanks Alex!
I don't use Groovy Console in my sample. I just run some code using GroovyShell. I will post the source code after I cleaned it. Sometime on weekend. If you can't wait until then you can download XPathEvaluator module and extend it with Groovy specific code. You need to download Groovy And Grails plugin and include groovy libs (implementation version) in project.