Groovy 来自Grails的Atom feed

def atom = {
    	params.max = 10
     	params.sort = 'datePosted'
     	params.order = 'desc'
       	def tmpList = Item.list( params )	
		
		def feedHeader = """<feed xmlns="http://www.w3.org/2005/Atom">
		  <title type="text">aboutGroovy.com</title>
		  <link rel="alternate" type="text/html" href="http://aboutGroovy.com"/>
		  <link rel="self" type="application/atom+xml" href="http://aboutGroovy.com/item/atom"/>
		  <updated>2006-12-17T18:30:02Z</updated>
		  <author><name>Scott Davis</name></author>
		  <id>tag:aboutgroovy.com,2006-12-18:thisIsUnique</id>
		  <generator uri="http://aboutGroovy.com" version="0.0.1">Hand-rolled Grails code</generator>
		"""
		
		def feedFooter = "</feed>"

		StringBuffer feed = new StringBuffer()
		def df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'-07:00'")
		tmpList.each{item ->
			Writer sw = new StringWriter()
			def x = new groovy.xml.MarkupBuilder(sw)
			x.entry(xmlns:"http://www.w3.org/2005/Atom"){
				author{name("Scott Davis")}
				published(df.format(item.datePosted))
				updated(df.format(item.datePosted))
				link(href:"http://aboutGroovy.com/item/show/${item.id}", 
					rel:"alternate", title:item.title, type:"text/html")
				id("tag:aboutgroovy.com,2006:/item/show/${item.id}")
				title(type:"text", item.title)
				content(type:"xhtml"){
					div(xmlns:"http://www.w3.org/1999/xhtml"){
						p("Category: ${item.type}")
						p{a(href:item.url, "Original Source")}
						p(item.shortDescription)
						p(item.description)
					}
				}	
			}
			feed.append(sw.toString() + "\n")
		}
	
		response.setContentType("application/atom+xml")				
		render "${feedHeader}${feed}${feedFooter}"
	}

Groovy Groovy系列:数字

//the two most common number classes
def intObj = 5
assert intObj.class.name == 'java.lang.Integer'

def bigDecimalObj = 5.12345
assert bigDecimalObj.class.name == 'java.math.BigDecimal'

//you can explicitly create Long, Float and Double with L / F / D
def longObj = 20L
assert longObj.class.name == 'java.lang.Long'
def floatObj = 40.45F
assert floatObj.class.name == 'java.lang.Float'
def doubleObj = 34.45D
assert doubleObj.class.name == 'java.lang.Double'

//if G is used, it checks if the number has a decimal point, then creates a BigInteger or BigDecimal
def bigIntegerObj = 50G
assert bigIntegerObj.class.name == 'java.math.BigInteger'

//some coercion stuff
//multiplication, addition and substraction between two floats results in a double
def z = 2F * 2F
assert z.class.name == 'java.lang.Double'

//multiplication, addition and substraction with BigInteger or BigDecimal results in BigInteger or BigDecimal
def product = 1.1G * 2 //BigDecimal and Integer
assert product.class.name == 'java.math.BigDecimal'

(3G*4).class.name == 'java.math.BigInteger' //BigInteger and Integer

//multiplication of two integers
assert (5*4).class.name == 'java.lang.Integer'

//multiplication with Long
assert (1L*4).class.name == 'java.lang.Long'

//dividing some numbers
(5/5).class.name == 'java.math.BigDecimal'
//if you want an integer, use the intdiv() method
(5.intdiv(5)).class.name == 'java.lang.Integer'
(1.intdiv(5)).class.name == 'java.lang.Integer' //result is 0
assert 1/2 == 0.5


//some GDK methods for numbers
//think about a java for loop... you don't need it!
def numbers = []
10.times { numbers << it } //it will contain values from 0 to 9
assert numbers.join(",") == '0,1,2,3,4,5,6,7,8,9'
10.upto(12) { numbers << it}
assert numbers.join(",") == '0,1,2,3,4,5,6,7,8,9,10,11,12'
11.downto(10) { numbers << it}
assert numbers.join(",") == '0,1,2,3,4,5,6,7,8,9,10,11,12,11,10'

numbers = []
1.step(2, 0.1) { numbers << it; assert it.class.name == 'java.math.BigDecimal' }
assert numbers.join(",") == '1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9' //notice 2 is not included

numbers = []
1.0.step(2, 0.1) { numbers << it; assert it.class.name == 'java.math.BigDecimal' }
assert numbers.join(",") == '1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9' //notice how the first value changed to 1.0

Groovy Groovy系列:GPath

//GPath can be used to easily query XML-based documents or even Object Graphs. 
//We start with looking at an XML GPath example.

//Let's load the Grails Pocast RSS Feed first.
println "new XmlSluper".center(75, '*')
def feed = new XmlSlurper().parse('http://hansamann.podhost.de/rss')
assert feed.getClass().name == 'groovy.util.slurpersupport.NodeChild'


//Like using XPath expressions, we can now navigate the tre
//This accesses the first iem element of the RSS channel:
println "Access to node content".center(75, '*')
println feed.channel.item[0].title
println feed.channel.item[0]['title']


//As in XPath, attributes are accessed with the @ syntax.
println "Access to attribute content".center(75, '*')
println feed.channel.item[0].enclosure.@url 
println feed.channel.item[0].enclosure['@url'] 

//Let's see how many podcasts whe have done so far. 
println "item element count".center(75, '*')
println feed.channel.item.size()

//We can iterate over all items with this
println "All titles below".center(75, '*')
feed.channel.item.each { item ->
    println item.title
}

//hier will ich die items nach Groovy Series filtern... 
//def groovySeries = feed.channel.item.findAll{ return (it.title.indexOf('Groovy Series')) ? true : false;} //wieso geht das nicht... println it.title geht
//println "Found ${groovySeries.size()}"

//playing with methods of GPathResult. NodeChild is an extension of GPathResult
assert feed.channel.item[0].enclosure[0].getClass().name == 'groovy.util.slurpersupport.NodeChild'

//to call the attributes method, we neet to macke sure that we are operating on a single Node, not a set
feed.channel.item[0].enclosure[0].attributes().each{println it} //works
try {
    feed.channel.item[0].enclosure.attributes().each{println it}
} catch (MissingMethodException e)
{
    assert feed.channel.item[0].enclosure.getClass().name == 'groovy.util.slurpersupport.NodeChildren'
    //above returns a NodeChildren object as it is a path expression for all enclosure tags of the first item tag!
}

//let's print all children of an item.
println "All children of item[0]".center(75, '*')
feed.channel.item[0].children().each { println it.name() } //will print tag names contained in item: title, description, author, pubDate, guid, link, enclosure
assert feed.channel.item[0].children().size() == 7

//Beispiel mit GPathResult->find / findAll


//evtl. xmlslurper dazu verwenden ein xml-doc zu veraendern??

Groovy 拷贝文件

//importjava.net commons
FileTools.copyFile("foo.txt", "bar.txt");

//antbuilder (no import needed!)
( new AntBuilder ( ) ).copy ( file : 'blah' , tofile : 'fobar' )

Groovy 使用Mysql db的GroovySQL

#!/usr/bin/env groovy
import groovy.sql.Sql

sql = Sql.newInstance('jdbc:mysql://localhost:3306/test', 'root', '', 'com.mysql.jdbc.Driver')

/*println 'Show all tables'
sql.eachRow('show tables'){ row ->
	println row[0]	
}
println ''*/

println 'Create user table'
sql.execute('''
create table if not exists user(
	id int auto_increment primary key,
	name varchar(63) not null,
	password varchar(35) not null
)
''')
println ''

println 'Create category table'
sql.execute('''
create table if not exists category(
	id int auto_increment primary key,
	name varchar(63) not null,
	parent_id int null
)
''')
println ''

println 'Create product table'
sql.execute('''
create table if not exists product(
	id int auto_increment primary key,
	category_id int not null,
	name varchar(63) not null,
	price decimal(10,2) not null,
	description text null
)
''')
println ''

//Generate some data.
insertUser = 'insert into user(name, password) values(?, ?)'	
for(idx in 1..3){
	println "Inserting user: tester$idx"
	//sql.executeInsert(insertUser, ["tester", "a"]) //Doesn't work???
	sql.execute(insertUser, ["tester" + idx, "a"]) 
}

insertCategory = 'insert into category(name, parent_id) values(?,?)'
for(idx in 1..3){
	println "Inserting category: cat$idx"
	sql.execute(insertCategory, ["cat$idx".toString(), null]) //toString is needed to persist.
}
lastCatId = sql.firstRow('select last_insert_id()')[0]

insertProduct = 'insert into product(category_id, name, price, description) values(?,?,?,?)'
for(idx in 1..50){
	println "Inserting product: product$idx"
	sql.execute(insertProduct, [lastCatId, "product"+idx, idx * Math.random(), "Just a test product item."])
}