<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-8488399678069086976</atom:id><lastBuildDate>Wed, 21 Mar 2012 00:03:54 +0000</lastBuildDate><category>GroovyMud</category><category>reflection</category><category>text editor</category><category>vi</category><category>shebang</category><category>mop</category><category>groovy GroovyScriptEngine</category><category>XML</category><category>interfaces</category><category>GStrings</category><category>Java</category><category>fu</category><category>groovy svn merge</category><category>Groovy</category><category>groovy Hudson triggers builds automated</category><category>GORM</category><category>classloader</category><category>Groovy Interfaces</category><category>groovy splitEachLine mock mocking file</category><category>welcome</category><category>Grape</category><category>persistence</category><category>groovy half partial mock half</category><category>metaclass</category><category>telnet</category><category>GREclipse</category><category>Grails</category><category>groovy sql fu gstrings</category><category>plugins</category><category>Groovy maven pom modify transform DOMCategory</category><category>scripts</category><category>Lists</category><category>groovy DSL groovymud</category><title>mBrainSpace</title><description>random groovy and java musings</description><link>http://mbrainspace.blogspot.com/</link><managingEditor>noreply@blogger.com (matt)</managingEditor><generator>Blogger</generator><openSearch:totalResults>25</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Mbrainspace" /><feedburner:info uri="mbrainspace" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-2919265109702831131</guid><pubDate>Mon, 07 Mar 2011 09:17:00 +0000</pubDate><atom:updated>2011-03-07T05:54:16.422-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">XML</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>simple-x</title><description>Apologies for the short hiatus from blogging here, but I was pretty busy with moving country and all. Hauling your butt across the european continent and back to blightly is a mighty stressful affair, I can tell you!&lt;br /&gt;&lt;br /&gt;Anyway, I started plugging away at a small project some of you might be interested in. Inspired by XStream and my mud, I've written a spin off project that could be quite useful. I wrote it in plain Java but tested it with Groovy, which was fun :)&lt;br /&gt;&lt;br /&gt;&lt;a href="http://code.google.com/p/simple-x/"&gt;Simple-x&lt;/a&gt; is a small fast xml database like ORM tool that allows you to persist an object tree easily. The objects you wish to keep track of can be given an ID annotated field and loaded independently from their parents. You can even lazyload fields with the lazyload annotation. It persists the xml in a directory of your choice, as one file per Id allocated object, much like a FilePersistentStrategy would do but with bells on (no separate collection classes for example).&lt;br /&gt;&lt;br /&gt;I wrote it mainly because I was tired of ORM tools being configuration heavy, and having to specify joins in complicated xml or other files and didn't want to have all that heavy lifting to do. &lt;br /&gt;&lt;br /&gt;An example of how to use it:&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;import org.corbym.simplex.persistence.annotations.Id&lt;br /&gt;...&lt;br /&gt;class SomeObjectWithId(){&lt;br /&gt;    @Id&lt;br /&gt;    def id&lt;br /&gt;}&lt;br /&gt;...&lt;br /&gt;class SomeObjectWithDefFieldAndId{&lt;br /&gt;    @Id&lt;br /&gt;    def id&lt;br /&gt;    def somefield&lt;br /&gt;}&lt;br /&gt;...&lt;br /&gt;final idObject = new SomeObjectWithId()&lt;br /&gt;final someObject = new SomeObjectWithDefFieldAndId(somefield: ["thingy": idObject])&lt;br /&gt;someObject.somefield.put "thing2", new SomeObjectWithoutId()&lt;br /&gt;SimplexDao dao = SimplexDaoFactory.getInstance()&lt;br /&gt;&lt;br /&gt;dao.save(someObject)&lt;br /&gt;&lt;br /&gt;assert someObject.id != null&lt;br /&gt;assert idObject.id != null&lt;br /&gt;&lt;br /&gt;def loaded = dao.load(SomeObjectWithId, idObject.id)&lt;br /&gt;assert loaded, "object should be loaded but was $loaded"&lt;br /&gt;&lt;br /&gt;def otherThatContainedIdObject = dao.load(SomeObjectWithDefFieldAndId, someObject.id)&lt;br /&gt;assert otherThatContainedIdObject.somefield.values().size() == 2&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It's a little incomplete, requires lazyloadable collections and needs a decent caching implementation to prevent slowness but it works ok.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-2919265109702831131?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/syL64QT00T0/simple-x.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2011/03/simple-x.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-2592739141659815471</guid><pubDate>Tue, 11 May 2010 11:34:00 +0000</pubDate><atom:updated>2010-05-11T05:03:03.710-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Groovy maven pom modify transform DOMCategory</category><title>Maven Pom Transformer</title><description>So Craig Tataryn asked about why we were having maven problems, and wanted to know more info. So here it is :)&lt;br /&gt;&lt;br /&gt;Maven is overly strict with version numbers. The release plugin expects either numbers or alphas, but not both, with or without the -SNAPSHOT extension. Another problem is that release:prepare does not change plugin configuration if it depends on a version thats being built in the reactor build. &lt;br /&gt;&lt;br /&gt;Maven plugins can be buggy at the best of times so I prefer to do this stuff myself anyway ;)&lt;br /&gt;&lt;br /&gt;With all that in mind, I took to Groovy to solve my problems. Firstly, I needed a class to hold my pom data:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;&lt;br /&gt;package branch.modify.transform&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.io.File;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;class PomData{&lt;br /&gt; def root&lt;br /&gt; File pomFile&lt;br /&gt; String artifactId&lt;br /&gt; String groupId &lt;br /&gt; boolean persistFile&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;... and then I went on to use DOMCategory to create this little beauty:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;class PomTransformer {&lt;br /&gt; &lt;br /&gt; def skipDirectories = ['.svn', 'src', '.metadata']&lt;br /&gt; &lt;br /&gt; def updateDependencies = { findIn, pomData, newValue -&gt;&lt;br /&gt;  println "updating dependencies for ${pomData.artifactId}, ${pomData.groupId}"&lt;br /&gt;  use(DOMCategory){&lt;br /&gt;   pomData.root.'**'.findAll {&lt;br /&gt;    (it.artifactId.text()  == findIn.artifactId &amp;&amp; it.groupId.text() == findIn.groupId)    &lt;br /&gt;    &lt;br /&gt;   }.each{   &lt;br /&gt;    pomData.persistFile = changeVersion(it.version, newValue, pomData.persistFile)    &lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt;  return pomData&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; def transform(workingDirectory, version){&lt;br /&gt;  File startDir = new File(workingDirectory)&lt;br /&gt;  assert "File is not a directory", startDir.isDirectory()&lt;br /&gt;  List pomList = []&lt;br /&gt;  &lt;br /&gt;  startDir.eachFileRecurse { File file -&gt; &lt;br /&gt;   if(file.isDirectory() &amp;&amp; skipDirectories.any{ it == file.name } ){&lt;br /&gt;    return&lt;br /&gt;   }&lt;br /&gt;   if(file.name == "pom.xml"){&lt;br /&gt;    println "reading file ${file.path}"&lt;br /&gt;    def doc = DOMBuilder.parse(new FileReader(file))&lt;br /&gt;    def project = doc.documentElement&lt;br /&gt;    use(DOMCategory){&lt;br /&gt;     def artifact = project.artifactId[0]?.text()&lt;br /&gt;     def group = project.groupId[0]?.text()&lt;br /&gt;     println "adding group $group and artifact $artifact to list"&lt;br /&gt;     PomData data = new PomData(root: project, artifactId:artifact, groupId: group, pomFile: file)&lt;br /&gt;     pomList.add(data)&lt;br /&gt;    }&lt;br /&gt;   }                     &lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  replaceValues(pomList, version)&lt;br /&gt;  for (PomData it : pomList) {&lt;br /&gt;   File f = new File(it.pomFile.path).asWritable()&lt;br /&gt;   if(f.canWrite() &amp;&amp; it.persistFile){&lt;br /&gt;    String xml = XmlUtil.serialize(it.root)&lt;br /&gt;    println "writing $f.path"&lt;br /&gt;    f.write(xml)&lt;br /&gt;   }else{&lt;br /&gt;    println "${it.persistFile ? 'cannot' : 'no version change, not going to'} write to file ${f.path}"&lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;&lt;br /&gt; &lt;br /&gt; def replaceValues(list, ver){&lt;br /&gt;  use(DOMCategory){&lt;br /&gt;   new ArrayList(list).each{    &lt;br /&gt;    &lt;br /&gt;    it.persistFile = changeVersion(it.root.version, ver, it.persistFile)&lt;br /&gt;    new ArrayList(list).each{ data -&gt;     &lt;br /&gt;     updateDependencies(it, data, ver) // update dependencies in other poms&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt; }&lt;br /&gt; def changeVersion(versionElements, ver, persistFile){&lt;br /&gt;  if(!versionElements){&lt;br /&gt;   println "no element found"&lt;br /&gt;   return&lt;br /&gt;  }&lt;br /&gt;  persistFile = ((versionElements[0]?.text() != ver) || persistFile)  &lt;br /&gt;  if(persistFile){&lt;br /&gt;   versionElements[0]?.value = ver &lt;br /&gt;  }&lt;br /&gt;  return persistFile&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Firstly, you obviously need to check out your dependent projects into a folder. I am assuming here that each project you check out is part of a multi-module build, and that each project is in some way dependent on the others. &lt;br /&gt;&lt;br /&gt;To run the transformer, call "transform" with the working directory (the folder you checked all the projects out in to), and a version (such as 3.1.2-SNAPSHOT). Transform moves through the entire workspace directory by directory, and gathers the poms it needs to change in a list.&lt;br /&gt;&lt;br /&gt;Once it has gathered these, it calls replaceValues. This method goes through each of the gathered poms and changes the version in that pom file, and also any reference to the same module in the other pom files in any element it finds.&lt;br /&gt;&lt;br /&gt;The only thing this does not do is change any scm information, which it can be modified to do but I have not done (yet) - I do it another more convoluted way.&lt;br /&gt;&lt;br /&gt;Hope this is useful :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-2592739141659815471?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/NHnX1Je-Khc/so-someone-asked-about-why-we-were.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/05/so-someone-asked-about-why-we-were.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-7988973918896886246</guid><pubDate>Sun, 09 May 2010 17:21:00 +0000</pubDate><atom:updated>2010-06-11T07:10:35.940-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">groovy Hudson triggers builds automated</category><title>Hudson Build Times</title><description>So we use &lt;a href="https://hudson.dev.java.net/"&gt;Hudson&lt;/a&gt; at work to build stuff.&lt;br /&gt;&lt;br /&gt;I've got it branching all our projects with a branch build using groovy, and because Maven doesn't work properly for us, updating all the project pom versions as well. I'll save that for a another time, the code is fairly in depth.&lt;br /&gt;&lt;br /&gt;The branch scripts also create a build in Hudson too, with this little nugget:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;package my.package&lt;br /&gt;&lt;br /&gt;import groovy.text.GStringTemplateEngine;&lt;br /&gt;import org.apache.commons.httpclient.*&lt;br /&gt;import org.apache.commons.httpclient.auth.*&lt;br /&gt;import org.apache.commons.httpclient.methods.*&lt;br /&gt;&lt;br /&gt;import java.net.URLEncoder;&lt;br /&gt;&lt;br /&gt;@Grab(group='commons-httpclient', module='commons-httpclient', version='3.1')&lt;br /&gt;class HudsonBuildCreator {&lt;br /&gt;   def server = "build"&lt;br /&gt;   def hudsonHost = "http://${server}:8080"&lt;br /&gt; &lt;br /&gt;   def username = "username"&lt;br /&gt;   def password = "password"&lt;br /&gt;   &lt;br /&gt;   def createBuild(String projectName, String svnUrl){&lt;br /&gt;       println "Creating hudson build..."&lt;br /&gt;       def client = new HttpClient()&lt;br /&gt;       client.state.setCredentials(&lt;br /&gt;          new AuthScope( server, 8080, "realm"),&lt;br /&gt;          new UsernamePasswordCredentials( username, password )&lt;br /&gt;       )&lt;br /&gt;       client.params.authenticationPreemptive = true&lt;br /&gt;       projectName = URLEncoder.encode(projectName)&lt;br /&gt;       String postString = "${hudsonHost}/createItem?name=${projectName}"&lt;br /&gt;       println "creating post method to ${postString}"&lt;br /&gt;       def post = new PostMethod( postString )&lt;br /&gt;       post.doAuthentication = true&lt;br /&gt;       String file = this.getClass().getResource("/my/package/config.template").getFile()&lt;br /&gt;       println "loading $file template"&lt;br /&gt;       File input = new File(file)&lt;br /&gt;       def engine = new GStringTemplateEngine()&lt;br /&gt;       def binding = ["svnUrl": "$svnUrl"]&lt;br /&gt;       def template = engine.createTemplate(input).make(binding)&lt;br /&gt;  &lt;br /&gt;       def xml = template.toString()&lt;br /&gt;       println "sending: \n $xml"&lt;br /&gt;       RequestEntity entity = new StringRequestEntity(xml, "application/xml", "UTF-8");&lt;br /&gt;       post.setRequestEntity(entity);&lt;br /&gt;       try {&lt;br /&gt;           int result = client.executeMethod(post)&lt;br /&gt;           println "Return code: ${result}"&lt;br /&gt;           post.responseHeaders.each{ println it.toString().trim() }&lt;br /&gt;           assert result == 200, "$result, failed"&lt;br /&gt;           post.responseHeaders.each{ println it.toString().trim() }&lt;br /&gt;           println post.getResponseBodyAsString()&lt;br /&gt;       } finally {&lt;br /&gt;           post.releaseConnection()&lt;br /&gt;       }&lt;br /&gt;       println "Done creating Hudson build."&lt;br /&gt;     &lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This calls the Hudson API and posts some xml to it to create a new build. I wanted it to be called from outside the Hudson environment too, so that it could be run from one of the dev's local machines without them having to log in to hudson.&lt;br /&gt;&lt;br /&gt;The xml sent to Hudson is a copy of the xml you can find in the api, with some GroovyTemplate coolness added to it so I can specify the build svn url (held in the svnUrl variable). You can find the xml in the following location:&lt;br /&gt;&lt;br /&gt;http://[my build server}/job/[job name]/config.xml&lt;br /&gt;&lt;br /&gt;Just take that, create a resource with it (copy it into the same package as the groovy class) and call it "config.template". &lt;br /&gt;&lt;br /&gt;One thing that was left was to space out my newly created builds. Surfing around the Hudson wiki pages I found something that displayed all the build trigger specs (the objects which take a cron tab like string) that let you specify the time the build is triggered. I wanted to update these, spaced out by 15 minutes or so, and came up with this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;&lt;br /&gt;import hudson.model.*&lt;br /&gt;import hudson.triggers.*&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int hourMax = 23 // could be 8, for 8am, before everyone comes in... &lt;br /&gt;int minMax = 59&lt;br /&gt;int incr = 15&lt;br /&gt;int hr = 0&lt;br /&gt;int m = 0&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;for(item in Hudson.instance.items) {&lt;br /&gt;    item.triggers.each{ descriptor, trigger -&amp;gt;&lt;br /&gt;        if(trigger instanceof TimerTrigger) {&lt;br /&gt;            println("--- Timer trigger for " + item.name + " ---")&lt;br /&gt;            println(trigger.spec + '\n')&lt;br /&gt;            if(item.name != "merge-process"){&lt;br /&gt;                item.removeTrigger descriptor&lt;br /&gt;                item.save()&lt;br /&gt;                item.addTrigger(new TimerTrigger("$m $hr * * *"))&lt;br /&gt;                item.save()&lt;br /&gt;                println "updated to $m $hr * * *"&lt;br /&gt;                m += incr&lt;br /&gt;            }&lt;br /&gt;                       &lt;br /&gt;            &lt;br /&gt;            if(m &amp;gt; minMax){ hr++; m = 0}&lt;br /&gt;            if(hr &amp;gt; hourMax) { hr = 0; }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I run this as a separate build to the branch and merge scripts, triggered from the branch build, as a freestyle project that's sole responsibility is to run a system groovy script. &lt;br /&gt;&lt;br /&gt;The output looks like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;Started by user admin&lt;br /&gt;&lt;br /&gt;bug-fix-1&lt;br /&gt;--- Timer trigger for bug-fix-1 ---&lt;br /&gt;@midnight&lt;br /&gt;&lt;br /&gt;updated to 0 0 * * *&lt;br /&gt;--- Timer trigger for change-batch-1 ---&lt;br /&gt;@midnight&lt;br /&gt;&lt;br /&gt;updated to 15 0 * * *&lt;br /&gt;Finished: SUCCESS&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Neat :)&lt;br /&gt;&lt;br /&gt;NB you will need the &lt;a href="http://wiki.hudson-ci.org/display/HUDSON/Groovy+plugin"&gt;Groovy plugin for Hudson&lt;/a&gt; to run the system Groovy script, and also have Groovy installed on your build server.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;WHOOPS: This, although it seems to work on the surface, fails to trigger the builds once they have been updated. I will post why this might be soon... possibly a hudson bug or something I haven't done?&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-7988973918896886246?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/tkt4CYiXfdU/hudson-build-times.html</link><author>noreply@blogger.com (matt)</author><thr:total>1</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/05/hudson-build-times.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-671686634700638957</guid><pubDate>Sat, 20 Feb 2010 15:10:00 +0000</pubDate><atom:updated>2010-03-12T02:04:34.397-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">shebang</category><category domain="http://www.blogger.com/atom/ns#">scripts</category><category domain="http://www.blogger.com/atom/ns#">reflection</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><category domain="http://www.blogger.com/atom/ns#">classloader</category><category domain="http://www.blogger.com/atom/ns#">fu</category><title>groovy workplace 2</title><description>Well, I've finished development on my Groovy branch and merge scripts for work. I'm quite please with the result: I can now run a Hudson build which runs my groovy scripts whenever I need them. Developers can also check the project out of svn and run them with command line parameters.&lt;br /&gt;&lt;br /&gt;I've even done a parameterized build for the branching script in Hudson, so developers and admins can create their own branch from there. Next step is to enable the branch script to create a build in Hudson, but I'm not sure how best to go about this: I expect I can access the Hudson instance from groovy but I'm not sure of the correct methods to call, or I could do it using an HTTP call to Hudson with parameters. Either way, I'm pretty happy with it all, and the best thing about it is that its Unit Tested and they run before any branch or merge happens :)&lt;br /&gt;&lt;br /&gt;When the developer checked out the script, I felt having to add the classpath everytime they ran the script was a bit much. The only thing I had a problem with was making the command line call easy to use.&lt;br /&gt;&lt;br /&gt;The basic premise to solve the problem was to use a class loader. This is the price I had to pay for using a &lt;a href="http://en.wikipedia.org/wiki/Shebang_(Unix)"&gt;shebang&lt;/a&gt;. Shebangs can only take one parameter, and the groovy start app requires two; one for the "-cp" and one for the actual classpath you send. So I created a special ClassPathHelper class to help find the relative location of the script to the file system, in the same directory as the scripts I want to run:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;import java.net.URI;&lt;br /&gt;import java.net.URL;&lt;br /&gt;&lt;br /&gt;class ClassPathHelper {&lt;br /&gt; &lt;br /&gt; static def include(caller, packageName){ &lt;br /&gt;  def url = new File(new File(caller.getClass().protectionDomain.codeSource.location.path).parent + "/$packageName/") // protectionDomain.codeSource.location.path may not exist in compiled groovy classes..&lt;br /&gt;  caller.getClass().classLoader.rootLoader.addURL(url.toURI().toURL())&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Then all you need to do then is to "include" your dependent directories:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;#!/usr/bin/env groovy&lt;br /&gt;&lt;br /&gt;import static ClassPathHelper.include &lt;br /&gt;&lt;br /&gt;include(this, "../src/main/groovy") // include the directory above in the classpath&lt;br /&gt;&lt;br /&gt;include(this, "../lib/foo.jar") // include a jar in lib directory (could use grape)&lt;br /&gt;&lt;br /&gt;classLoader = this.getClass().classLoader&lt;br /&gt;&lt;br /&gt;ProcessHandler = classLoader.loadClass("com.vcint.process.ProcessHandler")&lt;br /&gt;// .. rest of script&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Despite the &lt;a href="http://groovy.codehaus.org/Class+Loading"&gt;documentation&lt;/a&gt; saying that you should use Class.forName, this does not always work because (according to Jochen) forName "does some stack tricks to find the right class loader, tricks that won't always work with Groovy" (thanks, Jochen :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-671686634700638957?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/i_VWEJdtVdY/groovy-workplace-2.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/02/groovy-workplace-2.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-7315629763425071866</guid><pubDate>Wed, 10 Feb 2010 12:16:00 +0000</pubDate><atom:updated>2010-02-10T08:37:31.022-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">groovy half partial mock half</category><title>Partial (Half) mocks: Why they're good - a real world example</title><description>Following up from the post on &lt;a href="http://groovyblogs.org/entries/jump/14081"&gt;DZone&lt;/a&gt;, I found a use case for the "half mock" approach they discuss here that relates to a real life problem.&lt;br /&gt;&lt;br /&gt;Currently I'm creating a groovy app that runs a lot of command line processes and processes their results. Unit testing for the usual:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;...&lt;br /&gt;   def output = "ls -lart".execute().text&lt;br /&gt;   println output.length()&lt;br /&gt;...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;... is a little tricky to say the least. This is because the object that you are calling execute on is a string and is effectively this code:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;    def output = new String("ls -lart").execute().text&lt;br /&gt;    println output.length()&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;One option is to create a delegate to actually execute the command and return the Process object. But that's not very groovy. Another is to use MockFor:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;  def bArray = "Hello World".getBytes();&lt;br /&gt;  def stream = new ByteArrayInputStream(bArray);&lt;br /&gt; &lt;br /&gt;  def mockProcess = [getInputStream : {stream}] as Process&lt;br /&gt;  def myMockString = new MockFor(String)&lt;br /&gt;  myMockString.demand.execute {&lt;br /&gt;       return mockProcess&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;.. but in 1.7.0, this also mocks out all the other calls String, on any instance of String anywhere in the method. The method length() on the string will say there is no demand for "length", when actually we really need the string returned from the mock process to behave like a real string. We could add "demand.length" to the mockFor String, but if we have many cases where strings are used there could be very annoying to catch all the cases, especially if we are trying to process the string in any way.&lt;br /&gt;&lt;br /&gt;With partial mocks, we can do this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;  byte[] bArray = "Hello World".getBytes();&lt;br /&gt;  def stream = new ByteArrayInputStream(bArray);&lt;br /&gt; &lt;br /&gt;  def mockProcess = [getInputStream : {stream}] as Process&lt;br /&gt;&lt;br /&gt;  def myMockString = new MockFor(String)&lt;br /&gt;  myMockString.ignore(~'get.*')  // don't mock any getters&lt;br /&gt;  myMockString.ignore(~'length.*') // don't mock String.length()&lt;br /&gt;&lt;br /&gt;  myMockString.demand.execute {&lt;br /&gt;       return mockProcess&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is obviously a contrived example, but it's applications are deep... pretty groovy stuff :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-7315629763425071866?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/W0xrA67FCRA/partial-half-mocks-why-theyre-good-real.html</link><author>noreply@blogger.com (matt)</author><thr:total>2</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/02/partial-half-mocks-why-theyre-good-real.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-4703412686245603376</guid><pubDate>Wed, 10 Feb 2010 10:32:00 +0000</pubDate><atom:updated>2010-02-10T04:14:53.846-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">groovy splitEachLine mock mocking file</category><title>Mocking File splitEachLine</title><description>I thought I'd share this tip. I was trying to mock the behaviour of a file read, each line being read in and processed by a closure in the normal way:&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;class MyFileReader{&lt;br /&gt;    def myFileRead(){&lt;br /&gt;        def file = new File(myFile)&lt;br /&gt;        file.splitEachLine(","){ tokens -&gt;&lt;br /&gt;            println token[0]&lt;br /&gt;            println token[1]&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;splitEachLine is a closure call attached to the file, which actually invokes the  DefaultGroovyMethods static method splitEachLine(File self, String regex, Closure closure) . I &lt;span style="font-style:italic;"&gt;could&lt;/span&gt; just mock the call to splitEachLine on the File object, but I also really want to be able to test my closure functionality as well without extracting the closure contents to another method.&lt;br /&gt;&lt;br /&gt;Here's how I managed to mock it:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;def fileText = """\&lt;br /&gt;col1, col2&lt;br /&gt;col1a, col2a&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;def mockFile = new MockFor(File)&lt;br /&gt;mockFile.demand.splitEachLine { sep, Closure c -&gt;&lt;br /&gt;    Reader stringReader = new StringReader(fileText)&lt;br /&gt;    DefaultGroovyMethods.splitEachLine(stringReader as Reader, sep, c)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;mockFile.use{&lt;br /&gt;    new MyFileReader.myFileRead()&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now on the surface this may not look that useful, I'm not actually testing anything in that example. But looking deeper what it has done is given me the control to pass in my own set of mock text to the splitEachLine closure, rather than having groovy read a real file. Methods called by that closure can now be tested against that data, which is a huge benefit.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-4703412686245603376?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/EukwWYEiipE/mocking-file-spliteachline.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/02/mocking-file-spliteachline.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-4579036232107283600</guid><pubDate>Fri, 05 Feb 2010 19:45:00 +0000</pubDate><atom:updated>2010-02-05T11:52:16.869-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">groovy svn merge</category><title>groovy workplace</title><description>Finally, I am using groovy at work ;)&lt;br /&gt;&lt;br /&gt;I am writing a merge script to perform custom svn merges from branch to branch, and the plan is to run it from hudson :)&lt;br /&gt;&lt;br /&gt;I found someone had thought of doing this before and even produced &lt;a href="http://code.google.com/p/svn-merge-tools/"&gt;some google code hosted code for it&lt;/a&gt;, but it's a bit too bloated for me and only merges code into trunk..  also the author seems to have got distracted building a cli argument parser, which &lt;a href="http://www.comitservices.com/wp/?p=19"&gt;groovy already has&lt;/a&gt; ...&lt;br /&gt;&lt;br /&gt;At last!!  Yay!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-4579036232107283600?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/2yS6lWYPPks/groovy-workplace.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/02/groovy-workplace.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-2482245990373611666</guid><pubDate>Thu, 04 Feb 2010 09:55:00 +0000</pubDate><atom:updated>2010-02-05T11:05:04.728-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">groovy sql fu gstrings</category><title>dynamic SQL statements</title><description>Now, I know it's not good practice to inject unchecked parameters into an sql with strings. Especially input from users.&lt;br /&gt;&lt;br /&gt;But if you are processing a list of unknown size and just Do Not Have Time(tm), you need to create a statement where you have a variable number of inputs.&lt;br /&gt;&lt;br /&gt;This can be tricky in java, building strings is a pain in the arse.&lt;br /&gt;&lt;br /&gt;However, with groovy it's a breeze. In our example, we are taking a csv file, reading it in and selecting data from a db with the values received:&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;import java.sql.Connection;&lt;br /&gt;&lt;br /&gt;import java.sql.DriverManager;&lt;br /&gt;import java.sql.SQLException;&lt;br /&gt;&lt;br /&gt;def list = []&lt;br /&gt;def stream = getClass().getResourceAsStream("failed.csv"); // or use a file&lt;br /&gt;(stream.getText()).splitEachLine(',') {fields -&gt;&lt;br /&gt; if(!fields[0].toString().trim().isEmpty()){&lt;br /&gt;  list.add fields[0]&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;Connection connection = DriverManager.getConnection("jdbc:Oracle:thin:username/password@xyz:1521:abc");&lt;br /&gt;Sql sql = new Sql(connection);&lt;br /&gt;&lt;br /&gt;def query = "select * from foo where id in (${'?, '*(list.size()-1)}?)"&lt;br /&gt;sql.query query, list, {ResultSet rs -&gt;&lt;br /&gt;    println rs.getLong("id"); // and other stuff from foo&lt;br /&gt;}&lt;br /&gt;sql.close()&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The magic groovy fu here is generating a list of question marks inside the select statment: &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;${('? ,' * (list.size()-1)}?&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Grokking this may seem tricky, but actually it's fairly simple. The GString parameter ${} is being told to create '?, ' as many times (*) as list has elements less one (list.size() - 1) and append a ? at the end to make up for the last parameter. Easy eh?&lt;br /&gt;&lt;br /&gt;NOTE: I do not condone this way as general use, just as a quick n dirty hack. Generally, this sort of query will execute slowly and annoy dba's. Often a query will run a lot faster if you create a temporary table and insert all the values into it first.&lt;br /&gt;&lt;br /&gt;Also note, this will not work on some databases (for example, Oracle) if the list size exceeds a certain number. For any more than around 1000 values you really should use a temporary table...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-2482245990373611666?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/xrS3rucfPf4/dynamic-sql-statements.html</link><author>noreply@blogger.com (matt)</author><thr:total>4</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/02/dynamic-sql-statements.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-5774461199031233205</guid><pubDate>Wed, 03 Feb 2010 21:48:00 +0000</pubDate><atom:updated>2010-02-04T03:09:58.663-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>Groovy 2</title><description>I love the open source community ..No sooner had I entered my request for a &lt;a href="http://jira.codehaus.org/browse/GROOVY-4032"&gt;new Groovy feature&lt;/a&gt;, Guillaume Laforge adds it to the new &lt;a href="http://jira.codehaus.org/browse/GROOVY-2503"&gt;MOP requirements for Groovy 2&lt;/a&gt; :)&lt;br /&gt;&lt;br /&gt;The main problem is that you cannot persist metaclass closures. For example:&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;def object = new MyObjectBase()&lt;br /&gt;object.metaClass.doSomething = { println "hello groovy world!" }&lt;br /&gt;object.doSomething() // prints hello etc&lt;br /&gt;def xstream = new XStream()&lt;br /&gt;xstream.classLoader = getClass().classLoader&lt;br /&gt;new File("object.xml").withOutputStream { out -&gt;&lt;br /&gt;    xstream.toXML(object, out)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;new File("object.xml").withInputStream { ins -&gt;&lt;br /&gt;    object = xstream.fromXML(ins)&lt;br /&gt;}&lt;br /&gt;object.doSomething() // throws an exception :(&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;... the closure has not been restored. Which sort of sucks. Shame I have to wait for Groovy 2 tho :(&lt;br /&gt;&lt;br /&gt;Anyhew, I've been away for a while due to personal circumstances, but I hope to regain the enthusiasm for Groovy I had just before my last post. &lt;br /&gt;&lt;br /&gt;Onward, to greater groovier things!!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-5774461199031233205?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/bZEwAYxiO0c/groovy-2.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2010/02/groovy-2.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-3373489547427708142</guid><pubDate>Fri, 04 Sep 2009 09:24:00 +0000</pubDate><atom:updated>2009-09-04T06:34:19.677-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Grape</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>Grapes of Wrath</title><description>&lt;a href="http://groovy.codehaus.org/Grape"&gt;Groovy Grape&lt;/a&gt; comes standard now with Groovy 1.6.x. I am not going to go in to what Grape is for in this article, but suffice to say think of a dynamic, runtime version of Maven.&lt;br /&gt;&lt;br /&gt;I was trying to set up a Groovy run script that would download and run my application using Grapes, but hit on a problem that some of you might find useful to know about: &lt;span style="font-style: italic;"&gt;When I tried to instantiate one of my classes from the run script, it could not find the class' dependencies&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;This is a bit of a doozy. When I searched Jira about a bug, I came across &lt;a href="http://jira.codehaus.org/browse/GROOVY-3583"&gt;this issue&lt;/a&gt;. In my own script it was a bit more complex than this, but suffice to say the issues were the same. I will use the example from Jira to explain what is happening. Consider this code:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;import groovy.sql.Sql;&lt;br /&gt;import groovy.grape.Grape;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Grape.grab(group:'mysql', module:'mysql-connector-java', version:'5.1.6' )&lt;br /&gt;&lt;br /&gt;def sql=Sql.newInstance("jdbc:mysql://localhost/test","root","",&lt;br /&gt;"com.mysql.jdbc.Driver");&lt;br /&gt;&lt;br /&gt;println sql.firstRow("SELECT now( )");&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This will fail with a ClassNotFoundException. But why?&lt;br /&gt;&lt;br /&gt;Let me try to explain about what's going on here. Grape resolves and adds the dependencies to the current classes classloader, and classloaders work in tree formations. Classloaders further up the tree cannot see dependencies further down (or on different "branches").It turns out the SQL static newInstance method uses a different classloader higher up the tree from the run script.&lt;br /&gt;&lt;br /&gt;You can check this by printing the dependencies on the current and system classloaders by passing them to the listDependencies method of Grape:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;println Grape.listDependencies(ClassLoader.systemClassLoader)&lt;br /&gt;println Grape.listDependencies(this.class.classLoader)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The first is empty, the second has all your dependencies.&lt;br /&gt;&lt;br /&gt;So how do we work round this? The Grab method allows you to specify the classLoader to use for adding the dependencies on:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;import groovy.sql.Sql;&lt;br /&gt;import groovy.grape.Grape;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Grape.grab(group:'mysql', module:'mysql-connector-java', version:'5.1.6', classLoader:ClassLoader.systemClassLoader)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def sql=Sql.newInstance("jdbc:mysql://localhost/test","root","", "com.mysql.jdbc.Driver");&lt;br /&gt;&lt;br /&gt;println sql.firstRow("SELECT now( )");&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Thanks to Mr Haki (see the comments below) for the correct solution!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-3373489547427708142?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/-rcVhnIzq8w/grapes-of-wrath_04.html</link><author>noreply@blogger.com (matt)</author><thr:total>2</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/09/grapes-of-wrath_04.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-5484513437707113760</guid><pubDate>Wed, 19 Aug 2009 11:26:00 +0000</pubDate><atom:updated>2009-08-19T00:08:22.792-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">vi</category><category domain="http://www.blogger.com/atom/ns#">telnet</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>Building a VI clone with Groovy pt 2</title><description>Ok so, here's the beef. My main issue at the moment with my vi clone is that I think my assumptions about the way I was using a StringBuilder* were initially incorrect. I actually think I now need to store &lt;i&gt;each line&lt;/i&gt; separately in a list. This way, I can keep track of the caret, and know exactly which line I am on as well:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def buffers = new File(argstr).getText().tokenize('\n').collect{ new StringBuilder(it) }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;With that sorted, I find myself with a number of requirements:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Moving the cursor should be done with the arrow keys.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Deleting stuff (x) should remove the character at the right x, y position. &lt;/li&gt;&lt;li&gt;Do not pass the screen boundary, scroll the file down.&lt;/li&gt;&lt;li&gt;When at the end of the file, do not move the cursor further.&lt;/li&gt;&lt;li&gt;When I am in append mode, text should be added to the end of the line no matter where in the line I am. The cursor should be moved as well.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;  When I hit escape, a number of things can happen: If I am in edit mode, I drop back to movement mode; If I am in movement mode, I leave the editor (for now, saving the file will be automatic, rather than explicit for simplicity).&lt;/li&gt;&lt;li&gt;If I am in Append Mode or in Edit Mode I should be able to type text in to the correct buffer, and have it appear on my screen. Also, pressing enter should move on to a new line inbetween the current line and the next.&lt;/li&gt;&lt;li&gt;Do not wrap text on the screen for the time being.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;Requirement eight I am a little reticent about. I am not sure if it would be harder to work out whether we have wrapped the text on a line (could be stored as a boolean on an object wrapping the StringBuilder) or whether it is better to scroll the whole file with the cursor at the screen boundary. I guess both are valid solutions, and in the future the user could be given an option to do either.&lt;br /&gt;&lt;br /&gt;Encapsulating the StringBuilder in a decorator class of it's own does make sense though, because I might be able to add extra information to the line (like, last know caret position) as well as whether it has wrapped or not. I realise that the string length could be calculated every time to work this out, but encapsulating this functionality would be better I feel.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;* I have switched to StringBuilder because I forgot I was using Java 5 :O&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;*&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-5484513437707113760?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/ZsN6_diDnhU/building-vi-clone-with-groovy-pt-2.html</link><author>noreply@blogger.com (matt)</author><thr:total>1</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/08/building-vi-clone-with-groovy-pt-2.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-5938263458697150795</guid><pubDate>Sun, 16 Aug 2009 07:40:00 +0000</pubDate><atom:updated>2009-08-16T01:00:26.837-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">mop</category><category domain="http://www.blogger.com/atom/ns#">persistence</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><category domain="http://www.blogger.com/atom/ns#">metaclass</category><title>Persisting class with metaclass</title><description>The metaclass object on a Groovy object is marked transient, and with good reasons: I don't event want to think about actually persisting the entire thing.&lt;br /&gt;&lt;br /&gt;However, I'd like to be able to persist closures that belong to the class, since I spent the energy actually scripting the additional methods I would like them to be loaded when I need them?&lt;br /&gt;&lt;br /&gt;Has anyone got any clues?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-5938263458697150795?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/ONyrH3J0mRY/persisting-class-with-metaclass.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/08/persisting-class-with-metaclass.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-1817733765810776805</guid><pubDate>Thu, 13 Aug 2009 14:40:00 +0000</pubDate><atom:updated>2009-08-13T07:46:11.391-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">plugins</category><category domain="http://www.blogger.com/atom/ns#">GREclipse</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>GREclipse Plugin V2</title><description>Before I forget, I really aught to plug version 2 of the GREclipse plugin. It is far far superior to the old one, and I entirely recommend updating to it.&lt;br /&gt;&lt;br /&gt;Gone are the silly builders and having to have the output on your classpath woes, V2 does some very good things to make up for all the awfulness of the old one. JUnit tests run like a breeze, and although buggy, code completion is there.&lt;br /&gt;&lt;br /&gt;If you are using the old one, uninstall it first and get rid of any fluff on the classpath. Something else to watch out for is that you might need to uncheck the Groovy Libraries entry on the "order and export" tab on the project's preferences.&lt;br /&gt;&lt;a href="http://groovy.codehaus.org/Eclipse+Plugin"&gt;&lt;br /&gt;Check it out, I highly recommend it as a replacement&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-1817733765810776805?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/HbzQIXuzgYw/greclipse-plugin-v2.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/08/greclipse-plugin-v2.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-5757258229033815122</guid><pubDate>Mon, 10 Aug 2009 20:20:00 +0000</pubDate><atom:updated>2009-09-04T02:06:09.567-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">vi</category><category domain="http://www.blogger.com/atom/ns#">telnet</category><category domain="http://www.blogger.com/atom/ns#">text editor</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>Building a VI clone with Groovy</title><description>The great thing about online spaces is they tend to be able to build themselves. Give enough decent tools for the users of a space, and they can make some kickass things. And bizarre things too. And very very garish things :(&lt;br /&gt;&lt;br /&gt;Anyway, MUDS also allow this sort of thing, but in a more controlled fashion. MUDS generally have some sort of hierarchy to prevent the idiots from changing bits of the game that are really cool and ruining it for others. Called "creators", these hand picked super users can change parts of the game to make it more exciting, add depth and new content as often as required.&lt;br /&gt;&lt;br /&gt;So I need some tools for the creators in my MUD to go about editing the groovy scripts and other files. Which brings me to the problem: there are no telnet based text editors written in either Java or Groovy that can do this.  Guess I'll have to build  my own? GroovyMud already has a command loop type shell implementation, but adding an entire shell for this sort of thing is a little overkill. With GroovyMud I am able to run scripts as commands (&lt;a href="http://mbrainspace.blogspot.com/2009/06/creating-mob-dsl.html"&gt;remember last time&lt;/a&gt;?) in the MUD by just typing the name, and the CommandInterpreter invokes the GroovyScriptEngine to run it. I can leverage this behaviour nicely :D&lt;br /&gt;&lt;br /&gt;I will be logging my progress in creating this editor here when I can, so keep tuned to find out how I get on.&lt;br /&gt;&lt;br /&gt;So to start, I struck on having a vi type editor for the interface. For those of you not familiar with vi, (get out now!! :D just kidding), it is a very simple *nix text editor with a lot of very cool functions. There are no menus, just a number of commands that can put you into different states in order to do stuff with the text. &lt;br /&gt;&lt;br /&gt;For example, start up vi and push "i", and you enter "input" mode. Enter characters to add text to the file, and then push escape. You return back to movement mode, where you can move around the text file using the arrow keys. In movement mode, you can not only move the caret around, but delete characters with 'x' and lines by pressing 'd' and 'd' again. The default mode is movement, so you can move to where ever you need to add stuff in your file.&lt;br /&gt;&lt;br /&gt;So an enum for these states would be useful, with our default: &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;   enum Mode {&lt;br /&gt; INSERT, APPEND, MOVE&lt;br /&gt;   }&lt;br /&gt;   Mode currentMode = Mode.MOVE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Obviously we would also need to store the position of our caret in the text file, so Groovy's StringBuffer and file manipulation api extensions should help me here:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;   int xPos = 0&lt;br /&gt;   int yPos = 0&lt;br /&gt;&lt;br /&gt;   StringBuffer fileContents = new StringBuffer(new File(argstr).getText())&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In GroovyMud land, the player that is performing the edit is passed into the script as a paramter called "source". They have a very nice handy telnet ExtendedTerminalIO object to play with, which for these purposes acts just like any other kind of stream (except I can read lines with it with readln). So I can get a handle on this to manipulate their IOStream to their telnet prompt like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;ExtendedTerminalIO stream = source.terminalOutput&lt;br /&gt;stream.eraseToBeginOfScreen() // nifty function to clear the screen&lt;br /&gt;stream.write(fileContents) // write out the file contents&lt;br /&gt;stream.moveCursor(xPos, yPos)  // move the cursor to the beginning of the file.&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is good, I now have a screen full of file with my cursor at the start. But how would I work within the framework of the script to provide the command interface? Then I hit on the idea of using a map to hold the actions for each key press:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;def commandMap = ["i": {currentMode = INSERT}, &lt;br /&gt;                  "a" : {currentMode = APPEND},&lt;br /&gt;                  "x" : { ... perform some delete function ...},&lt;br /&gt;                  &lt;br /&gt;                 ]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Ok so far so good. We also need some kind of input loop, to trap the users input until we exit. So setting up a while loop here would probably be a good thing:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;boolean exit = false&lt;br /&gt;&lt;br /&gt;while(!exit){&lt;br /&gt; char ch = stream.read()&lt;br /&gt; //perform the command in the map first&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Ok this is as far as I have got. In theory I should be able to call the command in the map with the character that I read in. The closures there will handle the movement of the caret, the deletion of the chars in the string and any other functions, depending on the MODE I am in. I also want to add more funky stuff too, like code completion, colourization and other stuff like that.&lt;br /&gt;&lt;br /&gt;More next time.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-5757258229033815122?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/m6CbWaDRivs/building-vi-clone-in-java.html</link><author>noreply@blogger.com (matt)</author><thr:total>1</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/08/building-vi-clone-in-java.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-5380358699866229270</guid><pubDate>Wed, 22 Jul 2009 18:21:00 +0000</pubDate><atom:updated>2009-09-04T02:06:54.087-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">groovy GroovyScriptEngine</category><title>another bug bites the dust</title><description>Another beauty of a bug bites the dust in Groovy 1.7-beta-1: &lt;a href="http://jira.codehaus.org/browse/GROOVY-3357?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel"&gt;GroovyScriptEngine fails to load mutually dependant classes&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;This had been a big pain for me in the past, because I would have to watch out how I wrote my code. In the beginning, I hadn't got rid of the habit of statically typing my data, so doing something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;IBar.groovy:&lt;br /&gt;&lt;br /&gt;package test&lt;br /&gt;&lt;br /&gt;import test.Foo&lt;br /&gt;&lt;br /&gt;public interface IBar{&lt;br /&gt;    public void doStuff(Foo foo);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Foo.groovy:&lt;br /&gt;&lt;br /&gt;package test&lt;br /&gt;&lt;br /&gt;import test.IBar;&lt;br /&gt;&lt;br /&gt;public class Foo{&lt;br /&gt;    public void doSomeFoo(IBar obj){&lt;br /&gt;        out.print("foo!");&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;... and use the GSE to load one of the objects, things would fail with an infinite lookup loop.&lt;br /&gt;&lt;br /&gt;Now I hardly use interfaces its not such a problem, but it's still good to get it fixed. My thanks to Jochen (again ;))&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-5380358699866229270?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/GcxprCQuUmw/another-bug-bites-dust.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/07/another-bug-bites-dust.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-1143202315776010388</guid><pubDate>Wed, 08 Jul 2009 09:43:00 +0000</pubDate><atom:updated>2009-07-08T02:49:12.175-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>Bottled it.. why?</title><description>Darn...&lt;br /&gt;&lt;br /&gt;I had the perfect opportunity to use Groovy today on a work project. And I bottled it.&lt;br /&gt;&lt;br /&gt;Why? I love Groovy. It's useful, concise and powerful. Yet here I am, slogging away at the solution in Java, and cursing every time I have to put a semicolon in.&lt;br /&gt;&lt;br /&gt;I've been wanting to use Groovy for a long time now in my day job. I have had my reservations. These are mainly to do with:&lt;br /&gt;&lt;br /&gt;1. No one else in my department understands Groovy&lt;br /&gt;2. The architect has expressed reservations about it (well, not so much about Groovy as implementing new things without training)&lt;br /&gt;3. Even though I was using the maven plugin to generate my project, I had reservations about how I would go about deploying it.&lt;br /&gt;4. Mainly, I was confused about whether it really needed to be Groovy or not.&lt;br /&gt;&lt;br /&gt;These things panicked me, and I lost my bottle. Maybe next time... :(&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-1143202315776010388?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/FY4ModWq-Qo/bottled-it-why.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/07/bottled-it-why.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-1666360744183755716</guid><pubDate>Wed, 01 Jul 2009 07:22:00 +0000</pubDate><atom:updated>2009-09-04T02:07:22.861-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Lists</category><category domain="http://www.blogger.com/atom/ns#">GStrings</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>Stringy Lists and Maps</title><description>We all like to keep lists and maps of our objects. From shopping lists to translation maps, these useful little utilities are the staple diet of any Java programmer.&lt;br /&gt;&lt;br /&gt;You need to be careful with lists and maps when using GStrings. Consider the following test:&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;public class GroovyTest extends GroovyTestCase{&lt;br /&gt; &lt;br /&gt; void testAddName(){  &lt;br /&gt;  def name = "tom"&lt;br /&gt;  def someNames = []&lt;br /&gt;  &lt;br /&gt;  someNames.add("${name} 1")&lt;br /&gt;  &lt;br /&gt;  assertTrue someNames.contains("tom 1")&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This test will fail. But why? Well, the GString "${name}" and the GString "tom 1" are different object types. "tom 1" is a String, and "${name} 1" is a GString.&lt;br /&gt;&lt;br /&gt;Something similar happens with maps, when using a GString as a key. This time it is the hashcode of the GString which is different each time.&lt;br /&gt;&lt;br /&gt;As Jochen puts it on JIRA &lt;a href="http://jira.codehaus.org/browse/GROOVY-2660"&gt;&lt;/a&gt;:&lt;br /&gt;&lt;br /&gt;"there where several discussion on the mailing list for the usage of GStrings as map keys. Map keys things that should keep their hashcode the same and their euqals(sic) method should also return always the same if feed with the same object. This implies that hash key objects should either not be changed or even better, they should not be mutable. GStrings are mutable. Making a map immutable, does not change that fact. And while the GString "${p}" or "$p" uses the value of p at the time the GString was created and thus could be seen as something that does not change, the GString "${&gt;p}" uses a closure and evaluates the value of p every time anew. Not only that, but the hashcode of "${&gt;p}" differs from "$p", because the hashcode of the closure is used, instead of the hashcode of p to create the GString's hashcode.&lt;br /&gt;&lt;br /&gt;So I suggest you to just follow the rule to nether to use a GString as key and there is no issue at all. Even the GString "$p" and "33" do not have the same hashcode for p=33. That is no bug, that is a design decision often discussed on the list. But there are good reasons for it. "&lt;br /&gt;&lt;br /&gt;So, how do we work around these problems? Well, there is no elegant solution to this but calling toString on the GString should at least solve some of it:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;public class GroovyTest extends GroovyTestCase{&lt;br /&gt; &lt;br /&gt; void testAddName(){  &lt;br /&gt;  def name = "tom"&lt;br /&gt;  def someNames = []&lt;br /&gt;  &lt;br /&gt;  someNames.add("${name} 1".toString())&lt;br /&gt;  &lt;br /&gt;  assertTrue someNames.contains('tom 1') // note we can also switch to single quotes?&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;... at least our test now passes. The same solution would work for keys on maps.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Has anyone got a more elegant solution to this?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-1666360744183755716?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/B9SXN35HUvQ/stringy-lists-and-maps.html</link><author>noreply@blogger.com (matt)</author><thr:total>2</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/07/stringy-lists-and-maps.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-8747141295293821033</guid><pubDate>Mon, 08 Jun 2009 07:01:00 +0000</pubDate><atom:updated>2009-09-04T02:12:16.657-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Groovy Interfaces</category><title>Lets Interface</title><description>Java and Groovy work seemlessly together. Or at least thats the idea. However there are some tricky concepts as a Java programmer you might need to know about interfaces and Groovy. By interface, I do not always mean the interface declaration (as in "interface foo { void bar();} - although this does include that). I mean method declarations, constructors and getters and setters.&lt;br /&gt;&lt;br /&gt;Groovy can be softly typed, whilst Java likes things strongly typed. As a Java programmer I found it quite tricky to get my head around. I wanted to make everything softly typed in groovy (because I wanted to be, you know, Groovier man), and when it came to interfaces I couldn't reconcile the two ideas. Without the compiler to tell me I was bodging things up, I would try to program around the issues.&lt;br /&gt;&lt;br /&gt;Here are some gotchas and insights to remember when dealing with interfaces. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt;1. When implementing an interface, the keyword def might not work how you think&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;The keyword "def" does not mean "any object type". Groovy does not take the def type to mean literally any type, it means "any Object type or (groovy) void type". The compiler will moan if you try to implement interface methods defined with the def keyword instead of the String keyword for example. &lt;br /&gt;&lt;br /&gt;Conversely if an interface defines "Object"  as its type, you CAN define the method with def in Groovy (but not other types like String). &lt;br /&gt;&lt;br /&gt;GOTCHA: Although you cannot use def to declare concrete methods where the interface method is declared void, you can use void to declare concrete groovy object methods that are typed as "def" in your interface. E.g:&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;// this is ok...&lt;br /&gt;interface Wombat{&lt;br /&gt; def foo();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class InterfaceTest implements Wombat{&lt;br /&gt;&lt;br /&gt; void foo(){&lt;br /&gt;  println("hey")&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;however... &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt; &lt;br /&gt;// this is NOT ok&lt;br /&gt;interface Wombat{&lt;br /&gt; void foo();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public class InterfaceTest implements Wombat{&lt;br /&gt;&lt;br /&gt; def foo(){&lt;br /&gt;  println("hey")&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;2. Automatic getters and setters only work with interfaces if they are declared with the same type&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;If you have a required getter and setter pairing, for say Spring or Javabeans declaration, automatic getters and setters will only work if the property has exactly the same type.&lt;br /&gt;&lt;br /&gt;This is related to number 1, because believing "def" can define a String type is incorrect (although you can HOLD a String type in a def type object, it is not the same as expecting a return of type String).&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;3. Groovy automated constructors call your setter methods.&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;In groovy, a.name = "brian" is the same as a.setName("brian"), so you would think this one would be rather obvious. But because I'm used to setting properties directly in a constructor rather than calling setters, I have been gotcha'd by this one several times. I originally thought that an automatic constructor would do a.@name = "brian" but it does not, and if you put any logic into your setProperty or setName method it will always get called when the object is constructed and could be the cause of many NullPointerExceptions!&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;4. Constructor argument order matters!&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;This is related to 3. The order of your automatic constructor arguments actually matters. &lt;br /&gt;&lt;br /&gt;Say you have constructor a with arguments x y and z. If a setter of z uses x to perform a check and x depends on y to exist, then you must construct the object with arguments to reflect this.&lt;br /&gt;&lt;br /&gt;For the object to be constructed properly you must put them in dependency order from none to most, left to right, like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;def groovyObject = new GroovyObject(x, y, z) // x depends on y and z depends on both&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;5.GStrings are NOT Strings&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;This one doesn't seem interface related, but as I was explaining before in &lt;a href="http://mbrainspace.blogspot.com/2009/05/stringy-gstrings.html"&gt;Stringy G-Strings&lt;/a&gt; when a GString hits an interface boundary, you can expect it to be evaluated if the boundary type is String and not def or GString.&lt;br /&gt;&lt;br /&gt;Don't go around thinking you can pass GStrings around easily. At some point, someone somewhere may be expecting a String, and so as soon as the "toString" method is called on the GString, it will be evaluated &lt;i&gt;within the scope of the calling method&lt;/i&gt; and could cause errors. Even lazy GStrings can be problematic.&lt;br /&gt;&lt;br /&gt;[edit to correct my definition of def - see, its very confusing!!]&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-8747141295293821033?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/uC3QBY-xFqE/lets-interface.html</link><author>noreply@blogger.com (matt)</author><thr:total>2</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/06/lets-interface.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-6493286930695370278</guid><pubDate>Thu, 04 Jun 2009 08:33:00 +0000</pubDate><atom:updated>2009-09-04T02:09:40.234-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">groovy DSL groovymud</category><title>Creating a MOB DSL</title><description>Muds have something called MOBs. No one really knows what MOB stands for but my guess is MObile Object or some such.&lt;br /&gt;&lt;br /&gt;MOBs inhabit a MUD and can interact with the user, move about, talk and perform every action that a player can.&lt;br /&gt;&lt;br /&gt;Since the beginning of muds, programmers have created languages that make non-player characters behave the way they want them to. One of these languages is called MOBProg which you can specify actions for a mob in a simple sequence:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;... mob prog stuff to define the mob ..&lt;br /&gt;&gt;greet_prog 100~&lt;br /&gt;  if ispc($n)&lt;br /&gt;    mpadd mpecho $I says, ‘Get out of my way!! GRRR!!!’&lt;br /&gt;    mpadd kill $n&lt;br /&gt;  else&lt;br /&gt;    endif&lt;br /&gt;  endif&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;~&lt;br /&gt;&lt;br /&gt;This is part behavioural and part MOB instruction - if the player is a Player Character (pc), add the echo command for the mob to say "get out of my way" and then kill the pc.&lt;br /&gt;&lt;br /&gt;Because Groovy has the ability to create DSLs, this is a natural way to go. GroovyMud uses the GroovyScriptEngine to execute scripts that are in the script space. These scripts perform actions for the player, just like in an OS where the command "grep" or "exec" can be run by someone on the command line.&lt;br /&gt;&lt;br /&gt;This is the command interpreter (stripped down). Its written in Java:&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;&lt;br /&gt;public class CommandInterpreter { &lt;br /&gt;    private GroovyScriptEngine groovyScriptEngine;&lt;br /&gt;&lt;br /&gt;    ... &lt;br /&gt;public Object doCommand(final String command,&lt;br /&gt;    String argsAsString, MudObject performingObject) throws ResourceException,   &lt;br /&gt;    ScriptException {&lt;br /&gt;&lt;br /&gt;  if (getGroovyScriptEngine() != null) {&lt;br /&gt;   List&lt;String&gt; argsAsList = null;&lt;br /&gt;&lt;br /&gt;   if (argsAsString != null) {&lt;br /&gt;    argsAsList = Arrays.asList&lt;br /&gt;(argsAsString.split(" "));&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   Map&lt;String, Object&gt; bindingMap = new HashMap&lt;String, Object&gt;();&lt;br /&gt;   &lt;br /&gt;   bindingMap.put("argstr", argsAsString);&lt;br /&gt;                        // ... etc &lt;br /&gt;   bindingMap.put("interpreter", this);&lt;br /&gt;   Binding binding = new Binding(bindingMap);&lt;br /&gt;&lt;br /&gt;   return getGroovyScriptEngine().run(command + ".groovy", binding);&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  return null;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;    &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;All you really need to know about this is that it runs a script that is defined in a directory somewhere. This script could be something like "look" or "say" or "jump" etc etc. and is passed a string of arguments (like say hello there) &lt;br /&gt;&lt;br /&gt;However every time we want to run a command, we have to invoke "doCommand" which is a little clunky. What would be nice is if we could do something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;    MOBImpl ogre = new MOBImpl(name: "ogre")&lt;br /&gt;    ... register it with the mud etc ...&lt;br /&gt;&lt;br /&gt;    mob.say "I'm going to eat you!"&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;nice ... but we need it wrapped in a behaviour, because otherwise how would we know when to execute the commands? GroovyMud's triggeredBehaviour comes to the help. This behaviour is executed on the object whenever it receives an event from the MUD (ie, when someone leaves, enters, or whatever), and is called from the doEvent method, which is called by the mud whenever an event is received: &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;MOBImpl ogre = new MOBImpl(name: "ogre")&lt;br /&gt;... register it with the mud etc ...&lt;br /&gt;&lt;br /&gt;def triggered = new TriggeredBehaviour(eventClazz: ArrivalEvent)&lt;br /&gt;triggered.triggerLogic = { event -&gt; event.source instanceof Player }&lt;br /&gt;triggered.behaviour = [doBehaviour: {mob, event -&gt; &lt;br /&gt;&lt;br /&gt;      mob.say "I'm going to eat you!"&lt;br /&gt;      mob.kill event.source&lt;br /&gt;&lt;br /&gt;] as Behaviour&lt;br /&gt;ogre.triggeredBehaviours &lt;&lt; triggeredBehaviour&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Ok so adding the new commands to the mob is easily done with groovy:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;// stripped down Mud Object&lt;br /&gt;class MOBImpl extends IObservable{&lt;br /&gt; def name&lt;br /&gt;        def triggeredBehaviours&lt;br /&gt;//.. other methods etc &lt;br /&gt;&lt;br /&gt;        def methodMissing(String name, args){&lt;br /&gt;  def retObject = null;&lt;br /&gt;  def argsAsString = args[0]&lt;br /&gt;&lt;br /&gt;   if (argsAsString instanceof String) {&lt;br /&gt;    retObject = interpreter.doCommand(name,&lt;br /&gt; argsAsString, this); &lt;br /&gt;   }else{&lt;br /&gt;    throw new MissingMethodException(name, &lt;br /&gt;this, args)&lt;br /&gt;   }&lt;br /&gt; &lt;br /&gt;  &lt;br /&gt;  return retObject;&lt;br /&gt; }&lt;br /&gt;    void doEvent(IScopedEvent arg) {&lt;br /&gt;  triggeredBehaviours?.each{it-&gt;&lt;br /&gt;   it.doBehaviour(this, arg)&lt;br /&gt;  }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Using "methodMissing", we can pass the method on to the CommandInterpreter for processing. This way, when we add new scripts to the mud, any object can now perform any scripted action that the GroovyScriptEngine can find, and doEvent will call this behaviour when ever an event is received.&lt;br /&gt;&lt;br /&gt;I have actually implemented this on the base MUD object, so that any object at all can perform commands!&lt;br /&gt;&lt;br /&gt;Grooovy :D&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-6493286930695370278?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/h6TJqHx7YvQ/creating-mob-dsl.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/06/creating-mob-dsl.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-8152035029709531623</guid><pubDate>Tue, 19 May 2009 09:29:00 +0000</pubDate><atom:updated>2009-05-19T02:32:22.483-07:00</atom:updated><title>MOPs not a problem</title><description>Turns out I was being an Id10t with the interface problem :(&lt;br /&gt;&lt;br /&gt;I had missed out initialising the closure with the newly created bean in my examples.&lt;br /&gt;&lt;br /&gt;Silly me :(&lt;br /&gt;&lt;br /&gt;the fixed code is:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import b.*&lt;br /&gt;def pogo = new GroovyA(name:"John", lastName:"Wombat") as Foo&lt;br /&gt;&lt;br /&gt;pogo.fullName = {f, l, s -&gt; "Hello $f $l, how much $s in your tea?"} // set the closure&lt;br /&gt;&lt;br /&gt;def method = pogo.metaClass.getMetaMethod('getFullNameWithSugar', Object)&lt;br /&gt;&lt;br /&gt;// Given the instance now, it works&lt;br /&gt;println method.invoke(pogo, 'sugar')&lt;br /&gt;&lt;br /&gt;// This was commented out in your JIRA code. This also works.&lt;br /&gt;println pogo.fullNameWithSugar("f","sugar", "y")&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-8152035029709531623?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/9-oL1D9t3Bs/mops-not-problem.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/05/mops-not-problem.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-8679317525498003909</guid><pubDate>Fri, 15 May 2009 21:09:00 +0000</pubDate><atom:updated>2009-05-16T09:18:28.673-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">GORM</category><category domain="http://www.blogger.com/atom/ns#">Grails</category><title>standalone BeanBuilder broken in 1.1.1</title><description>&lt;span style="font-weight: bold;"&gt;&lt;a href="http://jira.codehaus.org/browse/GRAILS-4558"&gt;Standalone BeanBuilder support is broken&lt;/a&gt; in GRAILS 1.1.1 :(&lt;br /&gt;&lt;br /&gt;Best stay with 1.1 if you need BeanBuilder without GRAILS for a bit.&lt;br /&gt;&lt;br /&gt;Alternatively (thanks to Graeme Rocher for the tip) you could add the grails core as a dependency.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-8679317525498003909?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/0lQ1bu0dR-4/standalone-gorm-broken-in-111.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/05/standalone-gorm-broken-in-111.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-5344596157328486545</guid><pubDate>Thu, 14 May 2009 22:05:00 +0000</pubDate><atom:updated>2009-05-14T15:10:37.303-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Groovy</category><category domain="http://www.blogger.com/atom/ns#">Grails</category><title>Groovy 1.6.3 and Grails 1.1.1</title><description>Yay!&lt;br /&gt;&lt;br /&gt;&lt;a href="http://groovyblogs.org/entries/jump/11904"&gt;Groovy 1.6.3 is out, and so is Grails 1.1.1&lt;/a&gt; :D&lt;br /&gt;&lt;br /&gt;Goodbye &lt;a href="http://groovyblogs.org/entries/jump/11904"&gt;bug 4537&lt;/a&gt; (among others) :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-5344596157328486545?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/gjPrDRBSbYM/groovy-163-and-grails-111.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/05/groovy-163-and-grails-111.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-7932900467322626090</guid><pubDate>Wed, 13 May 2009 11:55:00 +0000</pubDate><atom:updated>2009-09-04T02:10:55.305-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">GStrings</category><category domain="http://www.blogger.com/atom/ns#">interfaces</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>Stringy GStrings</title><description>Groovy introduces the concept of GStrings into your code. GStrings are cool, and very, very groovy.&lt;br /&gt;&lt;br /&gt;However be warned that using GStrings and Java together (especially using interfaces) can be confusing.&lt;br /&gt;&lt;br /&gt;Consider this:&lt;br /&gt;//java&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;public interface StringyInterface{&lt;br /&gt;    public String getFullName();&lt;br /&gt;    public void setFullName(String name);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;//groovy class&lt;br /&gt;&lt;pre class="brush:groovy"&gt;class MyClass implements StringyInterface{&lt;br /&gt;    def name;&lt;br /&gt;    def lastName;&lt;br /&gt;    def fullName&lt;br /&gt;&lt;br /&gt;    String getFullName(){&lt;br /&gt;       return fullName&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    void setFullName(String fullName){&lt;br /&gt;       this.fullName = fullName&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In a normal Groovy class, you would not define the getter or setter for lastName, Groovy would deal with it for you. But if you do not, then the compiler complains about it.&lt;br /&gt;&lt;br /&gt;All goes wonderfully well until you try to assign a GString to lastName. The lastName variable is protected by the getters and setters defined by the interface so you cannot put ANY kind of GString (lazy or otherwise) into it without converting it to string first (toString()), which then evaluates the GString in the context of the calling code.&lt;br /&gt;&lt;br /&gt;e.g.&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;def myBean = new MyClass()&lt;br /&gt;myBean.name = "tom"&lt;br /&gt;myBean.lastName = "thumb"&lt;br /&gt;myBean.fullName = "${writer -&gt; writer &lt;&lt; \"$name $lastName\"}" &lt;br /&gt;// ^^^ complains about lastName and name&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;"But why dont you put the logic inside the getter to return the full name?" I hear you cry. Well, I could, but I should be able to do this kind of templating with a GString. Especially if I'm creating different kind of objects on the fly, that may have different rules for the position of name and lastname (for example) that are too simple or multifarious to bother putting in the class.&lt;br /&gt;&lt;br /&gt;"But I could change the definition of the setter to take an Object parameter!!" I also hear you cry. Correct, you /could/ do this, but this would break Javabean conventions and if you are using a framework like Spring then Spring will complain about it :( A Javabean must have the same getter return type as the setter argument type or some such nonsense. This makes sense when you're in a strongly typed language like Java, but is very annoying when using Groovy.&lt;br /&gt;&lt;br /&gt;However there is a way out!!!1! You can use the @ sign in front of the definition to directly access the lastName variable:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;def myBean = new MyClass()&lt;br /&gt;&lt;br /&gt;// yay this should work&lt;br /&gt;myBean.@fullName = "${writer -&gt; writer &lt;&lt; \"$name $lastName\"}"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I feel better now. Phew.&lt;br /&gt;&lt;br /&gt;GOTCHA:&lt;br /&gt;&lt;br /&gt;If you are using a Grails beanbuilder, you cannot do this as it does not support it: no matter what, the beanbuilder tries to evaluate the GString in the context of the beanbuilder because of the interface setter!&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:groovy"&gt;&lt;br /&gt;   beanbuilder.beans {&lt;br /&gt;      myClass(MyClass){&lt;br /&gt;          fullName = "${writer -&gt; writer &lt;&lt; \"$name $lastName\"}" // boo, name not found&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is because there is currently no way for beanbuilder to do the @ magic above boo :(&lt;br /&gt;&lt;br /&gt;Hopefully they will sort this out soon.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-7932900467322626090?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/diU9TcMDRXI/stringy-gstrings.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/05/stringy-gstrings.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-2739805967360732592</guid><pubDate>Wed, 13 May 2009 11:21:00 +0000</pubDate><atom:updated>2009-05-13T04:39:48.593-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">GroovyMud</category><category domain="http://www.blogger.com/atom/ns#">Groovy</category><title>GroovyMud - the Java / Groovy Mud Engine</title><description>I'm quite a seasoned Java programmer now. Or I like to think I am anyways. So I wanted to put myself to the test a little, and begin a really ambitious open source project.&lt;br /&gt;&lt;br /&gt;So I started writing a &lt;a href="http://en.wikipedia.org/wiki/Multi-User_Dungeon"&gt;MUD&lt;/a&gt; code base.&lt;br /&gt;&lt;br /&gt;Groovy!&lt;br /&gt;&lt;br /&gt;Yes. It is. Written in Groovy (and Java). For the past year and a bit I have been consumed by my obsessive nature and produced something that kinda works OK.&lt;br /&gt;&lt;br /&gt;It is still in heavy development, being redesigned to be more, er, Groovy - because Java *isn't* Groovy at all and I'm just not used to writing it.&lt;br /&gt;&lt;br /&gt;I have had many, many issues. Mainly fighting with Java and Groovy to play nicely with each other. Java wants nicely typed interfaces. Groovy doesn't. Groovy being in heavy development too hasn't helped either: there are a number of &lt;a href="http://jira.codehaus.org/secure/IssueNavigator.jspa?reset=true&amp;amp;&amp;amp;reporterSelect=specificuser&amp;amp;reporter=matt.corby&amp;amp;sorter/field=issuekey&amp;amp;sorter/order=DESC"&gt;bugs&lt;/a&gt; that I've had to raise just because I couldn't make Groovy do nice things.&lt;br /&gt;&lt;br /&gt;Anyway, take a look at the source code. You can download version 2 off the googlecode website (&lt;a href="http://code.google.com/p/groovymud"&gt;http://code.google.com/p/groovymud&lt;/a&gt;), it doesn't support areas yet but the version in the trunk is fairly stable now, which does.&lt;br /&gt;&lt;br /&gt;I will be writing some stuff about unit testing in Groovy on here in the next few months. And how to get things done with Java and Groovy (and Grails), which I think is missing a little from any of the documentation or tutorials you can find. I guess mainly because you either use Groovy, or you use Java.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-2739805967360732592?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/_lGpQTGw804/groovymud-java-groovy-mud-engine.html</link><author>noreply@blogger.com (matt)</author><thr:total>2</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/05/groovymud-java-groovy-mud-engine.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-8488399678069086976.post-3948890699828332973</guid><pubDate>Wed, 13 May 2009 11:20:00 +0000</pubDate><atom:updated>2009-05-13T04:21:05.399-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">welcome</category><title>Welcome</title><description>Hey&lt;br /&gt;&lt;br /&gt;This is my blog. I'm going to put programming stuff on here so I can refer back to it in the future. I used to have a blog over at JRoller, but for the life of me I can't get back in to edit it.&lt;br /&gt;&lt;br /&gt;So here I am.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8488399678069086976-3948890699828332973?l=mbrainspace.blogspot.com' alt='' /&gt;&lt;/div&gt;</description><link>http://feedproxy.google.com/~r/Mbrainspace/~3/N2lP0qoFrBY/welcome.html</link><author>noreply@blogger.com (matt)</author><thr:total>0</thr:total><feedburner:origLink>http://mbrainspace.blogspot.com/2009/05/welcome.html</feedburner:origLink></item></channel></rss>

