Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
titleBGColor#D0D9BD
borderStylesolid
titlebookmarks.groovy
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
borderColor#D0D9BD
borderWidth1
class JPACategory{
  // Let's enhance JPA EntityManager without getting into the JSR committee
  static void persistAll( EntityManager em , ListObject[] 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] );
}