1. How Groovy Helps Ken Kousen Kousen IT, Inc. http://www.kousenit.com [email_address] http://kousenit.wordpress.com
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14. google_chart.groovy package chart class Chart { def base = 'http://chart.apis.google.com/chart' def url = base + '?cht=p3&chs=500x150' def imageTag // … more code to come … } def chart = new Chart() chart.encodeMap() println chart.imageTag
15.
16.
17. More Fields def data = [ 'Spring and Hibernate', 'EJB', 'J2EE', 'J2EE', 'Spring', 'XML', 'Spring', 'Spring', 'XML', 'XML', 'J2EE', 'WS', 'Struts', 'Spring', 'JS', 'WS', 'Ajax', 'WS', 'Portlets', 'Hibernate and EJB3', 'J2EE', 'OOAD', 'Java', 'Ajax', 'Ajax', 'Spring', 'Struts 2', 'XML and Java', 'Ajax and Java', 'Securing WS', 'JSF', 'Ajax', 'Ajax and Java', 'Ajax', 'J2EE', 'WS'] def map = [:]
18.
19. Constructor Code Chart() { data. each { name -> if (name =~ (/Spring|Hibernate|Struts/)) { addToMap('Open Source') } if (name =~ (/Ajax|JS/)) { addToMap('Ajax') } // … other categories … } }
26. encodeMap() def encodeMap() { List list = (('A'..'Z')+('a'..'z')+(0..9)) as List String s = "&chd=s:" List keys = [] map. each { k,v -> keys << k s += list[v] } // … more to come …
27.
28. encodeMap() String labels = "&chl=" + keys. collect { URLEncoder.encode(it,"UTF-8") }. join ('|') url += s // the query string, defined in the code above url += labels println url // might as well see it String urle = url.replaceAll(/&/,'&') imageTag = "<img src='${urle}' alt='Course distribution'/>"
38. GetGameData.groovy class GetGameData { def day def month def year def base = 'http://gd2.mlb.com/components/game/mlb/' // all teams in actual file def abbrevs = [ ana:"Los Angeles (A)",ari:"Arizona",atl:"Atlanta", bal:"Baltimore",bos:"Boston",cha:"Chicago (A)", chn:"Chicago (N)",cin:"Cincinnati",cle:"Cleveland", col:"Colorado", was:"Washington"]
39. getGame() void getGame(away, home, num) { println "$away at $home on ${month}/${day}/${year}" def url = base + "year_${year}/month_${month}/day_${day}/" def game = "gid_${year}_${month}_${day}_" + "${away}mlb_${home}mlb_${num}/boxscore.xml" def boxscore = new XmlParser().parse(url + game)
41. getGame() def pitchers = boxscore.pitching.pitcher pitchers. each { p -> if (p.'@note' && p.'@note' =~ /W|L|S/) { println " ${p.'@name'} ${p.'@note'}" } }
42.
43. Result (so far) bos at col on 10/28/2007 Boston Red Sox 4, Colorado Rockies 3 (game 1) Lester (W, 1-0) Papelbon (S, 3) Cook (L, 0-1)
44. Process the Data def batters = boxscore.batting.batter for (b in batters) { println "${b.'@name'} went ${b.'@h'} for ${b.'@ab'}" } println batters. size () + " total batters" println 'Total hits: ' + batters.'@h'*. toInteger ().sum()
45.
46. More Processing println "Batters with at least one hit:" println batters. findAll { it.'@h'. toInteger () > 0 }. collect { it.'@name' + '(' + it.'@h' + ')' } }
47.
48.
49. Create HTML void writeHtml(node) { def away = node.'@away_sname‘ def home = node.'@home_sname' def name = "$away at $home" new File("${away}${home}.html"). withWriter { w -> def builder = new MarkupBuilder(w)
50.
51. Building HTML builder.html { head { title name } body { h1 name h2 node.'@date' node.batting. each { batters -> def team = batters.'@team_flag' + '_sname' h2 node."@${team}"
59. Find Games on Date void getGames() { println "Games for ${month}/${day}/${year}" def url = base + "year_${year}/month_${month}/day_${day}/" def gamePage = new URL(url).text def pattern = /amp;quot;gid_${year}_${month}_${day}_(*)mlb_(*)mlb_()/
60.
61. Process HTML Page def m = gamePage =~ pattern if (m) { (0..<m. count ).eachWithIndex { line, i -> def away = m[line][1] def home = m[line][2] def num = m[line][3] try { getGame(away,home,num) } catch (Exception e) { println abbrevs[away] + " at " + abbrevs[home] + " not started yet" } } }
62.
63. Results Games for 05/05/2007 Boston at Minnesota on 05/05/2007 Boston Red Sox 1, Minnesota Twins 2 (game 1) Tavarez (L, 1-3) Santana (W, 4-2) Nathan (S, 8) Chicago (A) at Los Angeles (A) on 05/05/2007 Chicago White Sox 6, Los Angeles Angels 3 (game 1) Garland (W, 1-2) Jenks (S, 9) Lackey (L, 4-3) …
64.
65.
66.
67.
68. Sample CSV Data 75,5/14/2007,5/18/2007,Java Web Services,Lancaster,PA 76,5/21/2007,5/25/2007,Ajax and Struts,Philadelphia,PA 77,6/4/2007,6/12/2007,Java Web Services,McLean,VA 78,6/25/2007,6/29/2007,Portal Dev. Using RAD6,Enola,PA 80,7/9/2007,7/14/2007,Hibernate EJB3,Atlanta,GA 81,8/23/2007,8/23/2007,J2EE for Managers,Marlborough,CT
69. Process CSV Data class Record { int num; String startDate; String endDate String title; String city; String state Record(String[] s) { num = s[0].startsWith("#") ? 0 : s[0]. toInteger () startDate = s[1]; endDate = s[2] title = s[3]; city = s[4]; state = s[6] } String toString() { "$title ($startDate -- $endDate) $city, $state" } }
70. Process CSV Data def records = [] try { def dataFile = new File('Course_locations.csv') def lines = dataFile. readLines () for (line in lines) { elements = line.trim().split(',') records << new Record(*elements) } } catch (FileNotFoundException e) { println e } records.each { println it }
71.
72.
73.
74. Using Google Geocoder def key = ‘long_ugly_key' def base = 'http://maps.google.com/maps/geo' def city = 'Marlborough' def state = 'CT' def query = "q=${city},+${state}&output=csv&key=${key}" def url_string = base + '?q=' + ',+' + URLEncoder.encode(city,"UTF-8") + ',+' + state + "&output=csv&key=${key}" def results = new URL(url_string).text.split(',') def latitude = results[-2].toDouble(); def longitude = results[-1].toDouble(); println "(${latitude},${longitude})" assert "(41.63256,-72.46315) == (${latitude},${longitude})"