Versions Compared

Key

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

...

Code Block
titleBGColor#D0D9BD
borderStylesolid
titleDOMTest.groovy
borderStylesolid
borderColor#D0D9BD
borderWidth1
import groovy.xml.*

def html = DOMBuilder.newInstance().html {
  head {
    title (class:'mytitle', 'Test')
  }
  body {
    p (class:'mystyle', 'This is a test.')
  }
}

use (groovy.xml.dom.DOMCategory) {
  assert html.head.title.text() == 'Test'
  assert html.body.p.text() == 'This is a test.'
  assert html.find{ it.tagName == 'body' }.tagName == 'body'
  assert html.getElementsByTagName('*').grep{ it.'@class' }.size() == 2
}

try {
  html.head
} catch(MissingPropertyException mpe) {
  println "Categories wear off"
}

...

Code Block
titleBGColor#D0D9BD
borderStylesolid
titleGroovyServlet.java
borderStylesolid
borderColor#D0D9BD
borderWidth1
Closure closure = new Closure(gse) {
   public Object call() {
       try {
           return ((GroovyScriptEngine) getDelegate()).run(scriptUri, binding);
       } catch (ResourceException e) {
           throw new RuntimeException(e);
       } catch (ScriptException e) {
           throw new RuntimeException(e);
       }
   }
};
GroovyCategorySupport.use(ServletCategory.class, closure);

...

Code Block
titleBGColor#D0D9BD
borderStylesolid
titleCategoryTest.groovy
borderStylesolid
borderColor#D0D9BD
borderWidth1
class StringCategory {
    static String lower(String string) {
        return string.toLowerCase()
    }
}

use (StringCategory) {
    assert "test" == "TeSt".lower()
}

...

Code Block
titleBGColor#D0D9BD
borderStylesolid
titlebookmarks.groovy
borderStylesolid
borderColor#D0D9BD
borderWidth1
#!/Users/sam/bin/groovy
// Put /System/Library/Java in your CLASSPATH
import groovy.xml.*;
import groovy.xml.dom.*;
import java.io.*;
import com.apple.cocoa.foundation.*;

class PropertyListCategory {
        static Object get(NSDictionary dictionary, String key) {
                return dictionary.objectForKey(key);
        }
        static Object getAt(NSArray array, int i) {
                return array.objectAtIndex(i);
        }
        static void each(NSArray array, Closure closure) {
                for (i in 0..array.count()-1) {
                        closure.call(array[i]);
                }
        }
}

filename = "${System.getProperty("user.home")}/Library/Safari/Bookmarks.plist";
data = new NSData(new File(filename));
errorString = new String[1];
format = new int[1];
plist = NSPropertyListSerialization.propertyListFromData(data,
            NSPropertyListSerialization.PropertyListImmutable, format, errorString);

if (errorString[0]) {
        println "Error: ${errorString[0]}";
        System.exit(1);
}

def getURLs(NSArray array, list) {
        array.each {
                getURLs(it, list);
        }
}

def getURLs(NSDictionary dict, list) {
        if (dict.Children != null) getURLs(dict.Children, list);
        if (dict.URIDictionary != null) {
                list.add([title:dict.URIDictionary.title, url:dict.URLString]);
        }
}

def getURLs(NSDictionary dict) {
        use (PropertyListCategory) {
                def list = [];
                getURLs(dict, list);
                return list;
       }
}

println getURLs(plist);

...

Code Block
titleBGColor#D0D9BD
borderStylesolid
titleClosure, Category and JPA example
borderStylesolid
borderColor#D0D9BD
borderWidth1
class JPACategory{
  // Let's enhance JPA EntityManager without getting into the JSR committee
  static void persistAll(EntityManager em , Object[] entities) { //add an interface to save all
    entities?.each { em.persist(it) }
  }
}

def transactionContext = { 
  EntityManager em, Closure c ->
  def tx = em.transaction
  try {
    tx.begin()
    use(JPACategory) {
      c()
    }
    tx.commit()
  } catch (e) {
    tx.rollback()
  } finally {
    //cleanup your resource here
  }
}

// user code, they always forget to close resource in exception, some even forget to commit, let's not rely on them.
EntityManager em; //probably injected
transactionContext (em) {
 em.persistAll(obj1, obj2, obj3)
 // let's do some logics here to make the example sensible
 em.persistAll(obj2, obj4, obj6)
}