<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Kaptain on ... stuff &#187; script</title>
	<atom:link href="http://www.kellyrob99.com/blog/tag/script/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kellyrob99.com/blog</link>
	<description>Tales of development, life and the folly that goes along with both</description>
	<lastBuildDate>Thu, 01 Jul 2010 21:07:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Different Flavors of Embedded Groovy in Java Apps or &#8220;How To Make your Java Groovier!&#8221;</title>
		<link>http://www.kellyrob99.com/blog/2009/11/21/different-flavors-of-embedded-groovy-in-java-apps-or-how-to-make-your-java-groovier/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=different-flavors-of-embedded-groovy-in-java-apps-or-how-to-make-your-java-groovier</link>
		<comments>http://www.kellyrob99.com/blog/2009/11/21/different-flavors-of-embedded-groovy-in-java-apps-or-how-to-make-your-java-groovier/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 04:28:04 +0000</pubDate>
		<dc:creator>TheKaptain</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Console]]></category>
		<category><![CDATA[dynamic execution]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[groovyConsole]]></category>
		<category><![CDATA[GroovyScriptEngine]]></category>
		<category><![CDATA[GroovyShell]]></category>
		<category><![CDATA[Hello world program]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Source code]]></category>
		<category><![CDATA[theKaptain]]></category>

		<guid isPermaLink="false">http://www.kellyrob99.com/blog/?p=858</guid>
		<description><![CDATA[Lately I&#8217;ve been thinking about all the different ways to bring Groovy into a pure Java or command line environment, and ended up diving into some code to explore the various options. Turns out there&#8217;s definitely a good variety of options for running Groovy dynamically inside and out of a Java application. I started out [...]


Related posts:<ol><li><a href='http://www.kellyrob99.com/blog/2009/10/04/groovy-clibuilder-with-multiple-arguments/' rel='bookmark' title='Permanent Link: Groovy CliBuilder with multiple arguments'>Groovy CliBuilder with multiple arguments</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/02/11/a-one-day-griffon-applicationpresentation/' rel='bookmark' title='Permanent Link: A One Day Griffon Application/Presentation'>A One Day Griffon Application/Presentation</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/05/15/achieving-groovy-like-fluency-in-java-with-google-collections/' rel='bookmark' title='Permanent Link: Achieving Groovy-like Fluency in Java with Google Collections'>Achieving Groovy-like Fluency in Java with Google Collections</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been thinking about all the different ways to bring Groovy into a pure Java or command line environment, and ended up diving into some code to explore the various options.  Turns out there&#8217;s definitely a good variety of options for running Groovy dynamically inside and out of a Java application. I started out on <a href="http://groovy.codehaus.org/Embedding+Groovy">this page from the Groovy site</a>.<br />
In particular for the environments I&#8217;ve been working in lately it&#8217;s been important to be able to run the same code both from within a Java application and from the command line. It&#8217;s also been a &#8216;nice to have&#8217; to be able to package a jar with a bunch of the same scripts compiled together. Using maven as a harness also has the benefit of allowing for testing compiled scripts directly through instantiation even though the intended usage is from within a Java app using one of these methods. Source code is <a href="http://github.com/kellyrob99/running-groovy">available here on github</a>.</p>
<p></p>
<h3>Groovy on the command line</h3>
<p>The quickest and simplest way to run a Groovy Script or Class, command line arguments are automatically marshalled into an &#8216;args&#8217; String array. Please note that due to a problem I&#8217;m having with my syntax highlighter plugin the process execution is shown here in single quotes; the actual code requires a GString(double quoted) in order to do the replacement for the inline variable. <code>&amp;quot;</code> THAT WordPress!</p>
<pre class="brush: groovy;">
//the script
myArgs = args
result = args.join(' ')
println result
println myArgs

//...and the test
    void testGroovyCall()
    {
        def proc = 'groovy $groovyScriptOne Hello World'.execute()
        proc.waitFor()
        def result = proc.text.split()
        assert result[0] == 'Hello'
        assert result[1] == 'World'
    }
</pre>
<p></p>
<h3>GroovyShell</h3>
<p>This is the basis of Groovy script execution. The <a href="http://groovy.codehaus.org/api/groovy/lang/GroovyShell.html">GroovyShell</a> allows for executing scripts, passing in a particular Binding context that allows for bi-directional communication between the script and the calling code. Parameters can be passed into the executing script in the Binding and results can be stored there to be returned to the calling context. GroovyShell also allows for running a class from the &#8216;main&#8217; method, passing in String arguments. It will also execute implementers of Runnable and test files for  JUnit or TestNG. Script text can also be declared inline and executed in the same way as files on disk. All in all, pretty bloody handy. Here&#8217;s a straightforward example of running a dirt simple Groovy script and inspecting the results. Note that this isn&#8217;t executable as shown, but I&#8217;ll provide the full source code on github for anyone who wants a closer look. Note that I&#8217;m also passing in an &#8216;out&#8217; variable in the Binding, which effectively redirect System.out to a specified Writer implementation &#8211; a nice touch for inspecting output.</p>
<pre class="brush: groovy;">
//the script
myArgs = args
result = args.join(' ')
println result
println myArgs

 //...and the test
    void testGroovyShell()
    {
        Binding binding = helper.createBinding()
        def shell = new GroovyShell(binding)
        shell.evaluate(new File(groovyScriptOne))
        helper.assertBinding(binding)
    }

//...and the Binding creation/assertion
     def static args = ['Hello', 'World'].asImmutable()
     /**
     * Create a Binding with a single parameter to be passed to scripts and an 'out' Writer to redirect console output.
     */
    private Binding createBinding()
    {
        Binding binding = new Binding()
        def sWriter = new StringWriter()
        def pWriter = new PrintWriter(sWriter)
        binding.setVariable ('args', new ArrayList(args))
        binding.setVariable ('out', pWriter)
        return binding
    }

    /**
     * Assert that the expected 'common' actions are done with the Binding by each of the use cases.
     * The original 'args' should be as expected.
     * A copy of 'args' should have been placed in the Binding during execution.
     * The 'result' should be the concatentation of 'args' separated by spaces.
     */
    private def assertBinding(Binding binding)
    {
        assert binding.variables.size() == 4
        assert binding.variables.args.value[0].toString() == args[0]
        assert binding.variables.args.value[1].toString() == args[1]
        assert binding.variables.result.value.toString() == args.join(' ')
        assert binding.variables.myArgs.value[0].toString() == args[0]
        assert binding.variables.myArgs.value[1].toString() == args[1]
    }
</pre>
<p></p>
<h3>GroovyScriptEngine</h3>
<p>The <a href="http://groovy.codehaus.org/api/groovy/util/GroovyScriptEngine.html">GroovyScriptEngine</a> enables dynamically running Groovy sources located in a fixed set of content roots,  complete with reloading modified scripts in between executions. Running a Groovy script this way is essentially the same as using GroovyShell.</p>
<pre class="brush: groovy;">
    void testGroovyScriptEngine()
    {
        Binding binding = helper.createBinding()
        def gse = new GroovyScriptEngine(new File('.').toURL())
        gse.run(groovyScriptOne, binding)
        helper.assertBinding(binding)
    }
</pre>
<p></p>
<h3>GroovyClassLoader</h3>
<p>An extension to URLClassLoader that enables parsing Groovy sources into Class representations. Once a Class object is created, instances of the class can be created easily and either cast to a known type or manipulated through convention by use of the standard Groovy &#8216;invokeMethod&#8217;.  This works equally well on Groovy and Java btw. Here&#8217;s an example of running a Java class using <a href="http://groovy.codehaus.org/api/groovy/lang/GroovyClassLoader.html">GroovyClassLoader</a>. In this case the Java file has a field called &#8216;binding&#8217; and implements a &#8216;run&#8217; method.</p>
<pre class="brush: groovy;">
    /**
     * Dynamically compile, instantiate, inspect and call methods on a POJO.
     */
    void testGroovyClassLoaderOnJava()
    {
        GroovyClassLoader loader = new GroovyClassLoader();
        Class javaClass = loader.parseClass(new File(javaFileOne));

        def groovyObject = javaClass.newInstance();
        def binding = helper.createBinding()
        groovyObject.binding = binding
        if(groovyObject.metaClass.respondsTo(groovyObject, 'run'))
        {
            groovyObject.invokeMethod('run', null);
            helper.assertBinding(binding)
        }
        if(groovyObject.metaClass.respondsTo(groovyObject, 'main'))
        {
            groovyObject.invokeMethod('main', new ArrayList(helper.args) as String[]);
        }
    }
</pre>
<p></p>
<h3>(Groovy)Console</h3>
<p>The <a href="http://groovy.codehaus.org/gapi/groovy/ui/Console.html">Console</a> can be embedded in Java or Groovy code to provide a dynamic interactive Swing environment. This is the same UI spawned from the command line invocation of &#8216;groovyConsole&#8217;. Internally it uses GroovyShell for actual execution, and so can do everything that GroovyShell can do &#8211; plus a couple of additions. For one, you can add jars and/or directories to the classpath used when executing your scripts.<br />
<a href="http://www.kellyrob99.com/blog/?attachment_id=885" rel="attachment wp-att-885"><img src="http://www.kellyrob99.com/blog/wp-content/uploads/2009/11/Picture-6.png" alt="Groovy Console" title="Groovy Console" class="size-full wp-image-885" width="651" height="457" /></a></p>
<p></p>
<h3>The Best of Both Worlds &#8211; at Least for my use case</h3>
<p>In actual practice these patterns can be used a lot more successfully by observing standard Java practices, like casting classes parsed using GroovyClassLoader to a known interface before interacting with them, or by using Classes to organize business logic inside of a Script that essentially functions as a &#8216;main&#8217; method.  This example defines two dependent internal classes, marshals parameters to them and then returns the results attached to the originally passed in Binding.</p>
<pre class="brush: groovy;">
/**
 * Classes inside of a Script.
 */
class TestableClass
{
    Binding binding

    def run()
    {
        binding.with
        {
            setVariable('myArgs', getVariable('args'))
            setVariable('result', getVariable('args')?.join(' '))
        }
        return binding
    }
}

class TestableClass2
{
    Binding binding

    public TestableClass2(Binding binding)
    {
        this.binding = binding;
    }

    def run()
    {
        return new TestableClass(binding: binding).run()
    }
}

if (args)
{
    def internalBinding = new Binding()
    internalBinding.setVariable('args', new ArrayList(args))
    internalBinding = new TestableClass2(internalBinding).run()
    args = internalBinding.args
    myArgs = internalBinding.myArgs
    result = internalBinding.result  //return value from script
}
else
{
    println 'no args!!'
}
</pre>
<h2 class="wp-table-reloaded-table-name">Summary of Groovy Execution Methods</h2>

<table id="wp-table-reloaded-id-1-no-1" class="wp-table-reloaded wp-table-reloaded-id-1">
<thead>
	<tr class="row-1 odd">
		<th class="column-1">Method</th><th class="column-2">Groovy Scripts</th><th class="column-3">Groovy Classes</th><th class="column-4">Java</th>
	</tr>
</thead>
<tbody>
	<tr class="row-2 even">
		<td class="column-1">groovy exec on the command line</td><td class="column-2">Yes, passes in String command line argments in a variable called 'args'</td><td class="column-3">Yes, calls the main method with String arguments</td><td class="column-4">No</td>
	</tr>
	<tr class="row-3 odd">
		<td class="column-1">GroovyShell</td><td class="column-2">Yes, parameters passed in a Binding object that the Script can mutate</td><td class="column-3">Yes, calls the main method with String arguments</td><td class="column-4">Yes, no apparent way to pass arguments</td>
	</tr>
	<tr class="row-4 even">
		<td class="column-1">GroovyScriptEngine</td><td class="column-2">Yes, parameters passed in a Binding object that the Script can mutate</td><td class="column-3">Yes, no apparent way to pass arguments</td><td class="column-4">Yes, no apparent way to pass arguments</td>
	</tr>
	<tr class="row-5 odd">
		<td class="column-1">GroovyClassLoader</td><td class="column-2">Yes, instantiate a parsed Class and either cast to a known type or use Groovy reflection methods to call methods</td><td class="column-3">Yes, instantiate a parsed Class and either cast to a known type or use Groovy reflection methods to call methods</td><td class="column-4">Yes, instantiate a parsed Class and either cast to a known type or use Groovy reflection methods to call methods</td>
	</tr>
	<tr class="row-6 even">
		<td class="column-1">(Groovy)Console</td><td class="column-2">Same as GroovyShell</td><td class="column-3">Same as GroovyShell</td><td class="column-4">Same as GroovyShell</td>
	</tr>
</tbody>
</table>
<span class="wp-table-reloaded-table-description"></span>

<div class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/8cba1f46-7f81-473a-8fe0-ce5f0a45ec40/" title="Reblog this post [with Zemanta]"><img class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_c.png?x-id=8cba1f46-7f81-473a-8fe0-ce5f0a45ec40" alt="Reblog this post [with Zemanta]" /></a><span class="zem-script more-related pretty-attribution"><script type="text/javascript" src="http://static.zemanta.com/readside/loader.js" defer="defer"></script></span></div>
<!-- AdSense Now! V1.95 -->
<!-- Post[count: 3] -->
<div class="adsense adsense-leadout" style="float:right;margin: 12px;"><script type="text/javascript"><!--
google_ad_client = "pub-6955914197200080";
/* 728x90, created 8/3/09 */
google_ad_slot = "4051815125";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p align="left"><a class="tt" href="http://twitter.com/home/?status=Different+Flavors+of+Embedded+Groovy+in+Java+Apps+or+%E2%80%9CHow+To+Make+your+Java+Groovier...+http://9bnoi.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.kellyrob99.com/blog/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Different+Flavors+of+Embedded+Groovy+in+Java+Apps+or+%E2%80%9CHow+To+Make+your+Java+Groovier...+http://9bnoi.th8.us" title="Post to Twitter">Tweet This Post</a></p>

<p>Related posts:<ol><li><a href='http://www.kellyrob99.com/blog/2009/10/04/groovy-clibuilder-with-multiple-arguments/' rel='bookmark' title='Permanent Link: Groovy CliBuilder with multiple arguments'>Groovy CliBuilder with multiple arguments</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/02/11/a-one-day-griffon-applicationpresentation/' rel='bookmark' title='Permanent Link: A One Day Griffon Application/Presentation'>A One Day Griffon Application/Presentation</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/05/15/achieving-groovy-like-fluency-in-java-with-google-collections/' rel='bookmark' title='Permanent Link: Achieving Groovy-like Fluency in Java with Google Collections'>Achieving Groovy-like Fluency in Java with Google Collections</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.kellyrob99.com/blog/2009/11/21/different-flavors-of-embedded-groovy-in-java-apps-or-how-to-make-your-java-groovier/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Groovy CliBuilder with multiple arguments</title>
		<link>http://www.kellyrob99.com/blog/2009/10/04/groovy-clibuilder-with-multiple-arguments/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=groovy-clibuilder-with-multiple-arguments</link>
		<comments>http://www.kellyrob99.com/blog/2009/10/04/groovy-clibuilder-with-multiple-arguments/#comments</comments>
		<pubDate>Sun, 04 Oct 2009 23:30:07 +0000</pubDate>
		<dc:creator>TheKaptain</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[cli]]></category>
		<category><![CDATA[CliBuilder]]></category>
		<category><![CDATA[command line interface]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[theKaptain]]></category>

		<guid isPermaLink="false">http://www.kellyrob99.com/blog/?p=797</guid>
		<description><![CDATA[I&#8217;ve been writing a lot of Groovy scripts lately and have developed quite a fondness for the CliBuilder along the way. There&#8217;s lots of great examples on the internet, but I could only find one place that demonstrated how to easily consume an unknown number of parameters as a List and that was a copy [...]


Related posts:<ol><li><a href='http://www.kellyrob99.com/blog/2009/11/21/different-flavors-of-embedded-groovy-in-java-apps-or-how-to-make-your-java-groovier/' rel='bookmark' title='Permanent Link: Different Flavors of Embedded Groovy in Java Apps or &#8220;How To Make your Java Groovier!&#8221;'>Different Flavors of Embedded Groovy in Java Apps or &#8220;How To Make your Java Groovier!&#8221;</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/10/25/grails-ui-datatable-using-xml-for-a-model/' rel='bookmark' title='Permanent Link: Grails-UI DataTable using XML for a model'>Grails-UI DataTable using XML for a model</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/10/24/groovy-reverse-map-sort-done-easy/' rel='bookmark' title='Permanent Link: Groovy reverse map sort done easy'>Groovy reverse map sort done easy</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been writing a lot of Groovy scripts lately and have developed quite a fondness for the CliBuilder along the way.<br />
There&#8217;s lots of great examples on the internet, but I could only find one place that demonstrated how to easily consume an unknown number of parameters as a List and that was a copy of the <a href="http://www.koders.com/noncode/fidDB2306122CA9674CE22373B7C018173B53BF66A2.aspx">CliBuilderTest I found on Koders</a>.  There&#8217;s also some explanation for the different behavior inherent in the <a href="http://commons.apache.org/cli/">Apache Commons Cli</a> libraries V1.0 and V1.1 that CliBuilder encapsulates(there is a 1.2 version, but from the documentation it seems CliBuilder may not be fully compatible with it).</p>
<p>Here&#8217;s a GroovyTestCase that exercises CliBuilder with multiple arguments.</p>
<div>
<pre class="brush: groovy;">
package org.kar
import org.apache.commons.cli.Option
/**
 * Demonstrates usage of the CliBuilder with multiple arguments to create a List.
 */
class CliBuilderDemoTest
extends GroovyTestCase {
    /**
     * You can specify multiple arguments one at a time.
     */
    void testMultiOption() {
        CliBuilder cli = new CliBuilder()
        cli.with {
            a longOpt: 'arguments', args: 2, required: true, 'Two arguments'
        }
        def args = ['-a', 'arg1', '-a', 'arg2']
        def options = cli.parse(args)

        assert (options)
        assertEquals('First arg is available with the -a option. ', 'arg1', options.a)
        assertEquals('Should be two args, in order, available with the addition of an &quot;s&quot; to the option.',
                ['arg1', 'arg2'], options.as)
    }

    /**
     * You can specify multiple arguments together in a block, with a defined separator(in this case a comma).
     */
    void testMultiOptionWithSeparator() {
        CliBuilder cli = new CliBuilder()
        cli.with {
            a longOpt: 'arguments', args: 2, required: true, valueSeparator: ',' as char,
                    'Two arguments, separated by a comma'
        }
        def args = ['-a', 'arg1,arg2']
        def options = cli.parse(args)

        assert (options)
        assertEquals('First arg is available with the -a option. ', 'arg1', options.a)
        assertEquals('Should be two args, in order.', ['arg1', 'arg2'], options.as)
    }

    /**
     * You can also have any number of arguments by specifying UNLIMITED_VALUES.
     */
    void testUnlimitedArgs() {
        CliBuilder cli = new CliBuilder()
        cli.with {
            a longOpt: 'arguments', args: Option.UNLIMITED_VALUES, required: true, valueSeparator: ',' as char,
                    'Two arguments, separated by a comma'
        }
        def args = ['-a', 'arg1,arg2,arg3']
        def options = cli.parse(args)

        assert (options)
        assertEquals('First arg is available with the -a option. ', 'arg1', options.a)
        assertEquals('Should be a list of args, in order.', ['arg1', 'arg2', 'arg3'], options.as)

        def args2 = ['-a', 'argOnly']
        def options2 = cli.parse(args2)

        assert (options)
        assertEquals('First arg is available with the -a option.', 'argOnly', options2.a)
        assertEquals('Should be a list of args, with a single entry.', ['argOnly'], options2.as)

        def args3 = []
        //this will automagically print the usage string and any validation errors to System.out
        def options3 = cli.parse(args3)
        assertNull(options3)
    }
}
</pre>
</div>
<p>Anyhow, hope that the next guy finds this info useful &#8211; it certainly has made my recent work writing Groovy scripts much easier!</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Groovy+CliBuilder+with+multiple+arguments+http://fkxpp.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.kellyrob99.com/blog/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Groovy+CliBuilder+with+multiple+arguments+http://fkxpp.th8.us" title="Post to Twitter">Tweet This Post</a></p>

<p>Related posts:<ol><li><a href='http://www.kellyrob99.com/blog/2009/11/21/different-flavors-of-embedded-groovy-in-java-apps-or-how-to-make-your-java-groovier/' rel='bookmark' title='Permanent Link: Different Flavors of Embedded Groovy in Java Apps or &#8220;How To Make your Java Groovier!&#8221;'>Different Flavors of Embedded Groovy in Java Apps or &#8220;How To Make your Java Groovier!&#8221;</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/10/25/grails-ui-datatable-using-xml-for-a-model/' rel='bookmark' title='Permanent Link: Grails-UI DataTable using XML for a model'>Grails-UI DataTable using XML for a model</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/10/24/groovy-reverse-map-sort-done-easy/' rel='bookmark' title='Permanent Link: Groovy reverse map sort done easy'>Groovy reverse map sort done easy</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.kellyrob99.com/blog/2009/10/04/groovy-clibuilder-with-multiple-arguments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
