0
Groovy<br />Zdenek Urban<br />20. ledna 2010<br />
Groovykindof love<br /> excellent, fashionable, or amazing<br />
Groovy<br /><ul><li>Strings
Lists and Maps
Regex and Ranges
Operators
Closures
Groovy Beans
Operator overloading
DSL – Domain Specific Language
Metaprogramming
Builders
Files
Database</li></li></ul><li>Historie<br />Groovy<br />James Strachan<br />Guillaume Laforge<br />Java<br />James GosliNg   ...
Scripting dynamic langs (JVM)<br />
Hello, world<br />Legální java code, ale co vše je nadbytečné<br />class Foo {<br />	public static void main(String[] args...
Hello, world<br />Nadbytečné declarace obecných objektů<br />Závorky, ukončení věty…<br />System.out.println("Hello, world...
Hello, world<br />println'Hello, world'<br />
CLI Command Line Interface<br />def cli = new CliBuilder(usage: 'showdate.groovy -[chflms] [date] [prefix]')<br />cli.with...
PročGroovy?<br />Dynamický skriptovací jazyk plus …<br />JSR 241: Java standard<br />Two-way contract: <br />Groovy class ...
Some Groovy language features<br />Dynamically typed<br />Closures<br />Everything is an object. No primitives.<br />== me...
Strings<br />greeting = 'Hello “my darling”'<br />println "$greeting, world is ‘easy’“<br />println """<br />Today's “date...
Lists and maps<br />mylist = [1, 2, 3, 4, 5]    // an ArrayList<br />assert mylist[0] == 1<br />mylist[2..3] = []         ...
Ranges and regex<br />Ranges<br />(1..10).each { it -> println it }<br />switch (age) { case 15..30: … }<br />for (i in 1....
Regex <br />str = 'groovy.codehaus.org  and www.aboutgroovy.com ‘<br />reNoWhiteSpace = /((?:(?![-_][w-])+.)+[A-Za-z][w-]+...
Closures	<br />Metoda jako objekt<br />Default argument “it” je volitelný. <br />def squareIt = { return it * it }<br />as...
ClosuresStrategy pattern<br />def multiplicationStrategies = [<br />    { n, m -> n * m },<br />    { n, m -> def result =...
Operator overloading<br />Override operators by overriding methods:<br />a + b 				a.plus(b)<br />a[b] 				a.getAt(b)<br /...
Smart switch<br />switch (x) {case 'James':	println "yes it is me"	breakcase 18..65:	println "ok you are old"	breakcase ~/...
Groovy convenience operators<br />=~		regex find brandMatch = (line =~ /<b>([a-zA-Zs]*):<br>/)        if(brandMatch)  bran...
GroovyBeans and JavaBeans<br />// Groovy<br />class MyBean {<br />	String item<br />}<br />MyBean b = <br />    new MyBean...
Why brevity matters: Quicksort<br />function sort(array) // pseudocode from Wikipedia<br />    var list less, greater<br /...
Quicksort in Java<br />    public static void qsort(Comparable[] c,int start,int end){<br />        if(end <= start) retur...
Object graph navigation: GPaths<br />class Invoice { List items; … }<br />class Item { Product product; int total() {…} … ...
Dynamic Groovy: multimethods<br />class Equalizer {<br />	boolean equals(Equalizer e) {...}<br />	boolean equals(Object o)...
Upcoming SlideShare
Loading in...5
×

Groovy

2,292

Published on

Groovy and its place in Java world and scripting

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,292
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
29
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • The Strategy Pattern allows you to abstract away particular algorithms from their usage. This allows you to easily swap the algorithm being used without having to change the calling code.
  • Transcript of "Groovy"

    1. 1. Groovy<br />Zdenek Urban<br />20. ledna 2010<br />
    2. 2. Groovykindof love<br /> excellent, fashionable, or amazing<br />
    3. 3. Groovy<br /><ul><li>Strings
    4. 4. Lists and Maps
    5. 5. Regex and Ranges
    6. 6. Operators
    7. 7. Closures
    8. 8. Groovy Beans
    9. 9. Operator overloading
    10. 10. DSL – Domain Specific Language
    11. 11. Metaprogramming
    12. 12. Builders
    13. 13. Files
    14. 14. Database</li></li></ul><li>Historie<br />Groovy<br />James Strachan<br />Guillaume Laforge<br />Java<br />James GosliNg  Sun Microsystems<br />JSR 241 Process 2004<br />Ver 1.0 2.l.2007<br />Oak 1991<br />Ver 1.0 1995<br />Java 2 11, 1998<br />WORAwrite once, run anywhere<br />Open Source 11, 2007<br /> JCP 2.7 standard<br />Industry standard<br />JCP Java Community Process<br />JSR Java Specification Request<br />Java EE(enterprise edition), SE, ME<br />
    15. 15. Scripting dynamic langs (JVM)<br />
    16. 16. Hello, world<br />Legální java code, ale co vše je nadbytečné<br />class Foo {<br /> public static void main(String[] args) {<br /> System.out.println("Hello, world");<br /> }<br />}<br />
    17. 17. Hello, world<br />Nadbytečné declarace obecných objektů<br />Závorky, ukončení věty…<br />System.out.println("Hello, world");<br />
    18. 18. Hello, world<br />println'Hello, world'<br />
    19. 19. CLI Command Line Interface<br />def cli = new CliBuilder(usage: 'showdate.groovy -[chflms] [date] [prefix]')<br />cli.with {// Create the list of options.<br /> h longOpt: 'help', 'Show usage information'<br /> c longOpt: 'format-custom', args: 1, argName: 'format', 'Format date with custom format defined by "format"'<br /> f longOpt: 'format-full', 'Use DateFormat#FULL format'<br /> l longOpt: 'format-long', 'Use DateFormat#LONG format'<br /> m longOpt: 'format-medium', 'Use DateFormat#MEDIUM format (default)'<br /> s longOpt: 'format-short', 'Use DateFormat#SHORT format'<br />}<br />cli.p(argName:'heslo', longOpt:'password', args:1, required:true, type:GString, 'fill up the hic')<br />def options = cli.parse(args)<br />if (!options) return<br />if ( options.h) {<br /> cli.usage()<br />// usage: showdate.groovy -[chflms] [date] [prefix]<br /> // -c,--format-custom <format> Format date with custom format defined by "format"<br /> // -f,--format-full Use DateFormat#FULL format <br /> // -h,--help Show usage information <br /> // -l,--format-long Use DateFormat#LONG format <br /> // -m,--format-medium Use DateFormat#MEDIUM format <br /> // -s,--format-short Use DateFormat#SHORT format <br /> return<br />}<br />GOP Groovy Option Parser Alternativa<br />
    20. 20. PročGroovy?<br />Dynamický skriptovací jazyk plus …<br />JSR 241: Java standard<br />Two-way contract: <br />Groovy class je Java class: bytecode identita. Groovy and Java dědičnost tříd.<br />Integrace s Java: annotations, generics, enums, familiar syntax.<br />Groovy platforma je Java platforma: <br />JSE library, debugging, ...<br />Spring, Hibernate, web services, TestNG<br />
    21. 21. Some Groovy language features<br />Dynamically typed<br />Closures<br />Everything is an object. No primitives.<br />== means equals. Really.<br />Native syntax for lists, maps, regex<br />Operator overriding <br />Compact, expressive, readable<br />
    22. 22. Strings<br />greeting = 'Hello “my darling”'<br />println "$greeting, world is ‘easy’“<br />println """<br />Today's “date” is ‘${new Date().toGMTString()’}<br />Multiline string, isn't it?<br />"""<br />greeting = "Hello, world“;greeting[7] == 'w‘;greeting[2..4] == 'llo‘<br />"{'}${"}/“ == '{'}${"}/‘ == /#{'}${'$'}{"}//<br />def capitalize(s) { s[0].toUpperCase() + s[1..-1].toLowerCase() }<br />caps = "man OF stEEL".replaceAll(/w+/) { w -> capitalize(w) }<br />println "cmd /c dir|grep cli".execute().text.split(' ')<br />
    23. 23. Lists and maps<br />mylist = [1, 2, 3, 4, 5] // an ArrayList<br />assert mylist[0] == 1<br />mylist[2..3] = [] // deleted 3, 4<br />[2,3,4].collect { it * 2 } == [4, 6, 8]<br />[1,2,3].find { it > 1 } == 2<br />[1,2,3,[1,[2,3]]].flatten().unique() == [1, 2, 3]<br />mylist.each { doSomethingWith(it) }<br />mymap = [a:1, b:2, c:3] // a HashMap<br />mymap['a'] == mymap.a // == mymap.get("a")<br />mymap['c'] = 5 // mymap.put("c", 5)<br />
    24. 24. Ranges and regex<br />Ranges<br />(1..10).each { it -> println it }<br />switch (age) { case 15..30: … }<br />for (i in 1..10) { … }<br />'Hello, world'[2..4] == 'llo'<br />Regex<br />if ('rain' =~ /w*ain/)<br /> println '"rain" does rhyme with "Spain"!'<br />
    25. 25. Regex <br />str = 'groovy.codehaus.org and www.aboutgroovy.com ‘<br />reNoWhiteSpace = /((?:(?![-_][w-])+.)+[A-Za-z][w-]+)/<br />reWhiteSpace = /(?x)( (?: (?! [-_]) [w-]+ . )+ [A-Za-z] [w-]+ ) /<br />re = '''(?x) # to enable whitespace and comments<br /> ( # capture the hostname in $1<br /> (?: # these parens for grouping only<br /> (?! [-_] ) # lookahead for neither underscore nor dash<br /> [-] + # hostname component<br /> # and the domain dot<br /> ) + # now repeat that whole thing a bunch of times<br /> [A-Za-z] # next must be a letter<br /> [-] + # now trailing domain part<br /> ) # end of $1 capture<br />'''<br />finder = str =~ re<br />out = str<br />(0..<finder.count).each{<br /> adr = finder[it][0]<br /> out = out.replaceAll(adr, "$adr [${InetAddress.getByName(adr).hostAddress}]")<br />}<br />println out<br />// => groovy.codehaus.org [63.246.7.187] and www.aboutgroovy.com [63.246.7.76]<br />
    26. 26. Closures <br />Metoda jako objekt<br />Default argument “it” je volitelný. <br />def squareIt = { return it * it }<br />assert squareIt(5) == 25<br />10.times { println “I will not talk in class” }<br />Variables visibility<br />int x = 10<br />Closure addToX = { addThis -> x += addThis }<br />addToX(2)<br />assert x == 12<br />
    27. 27. ClosuresStrategy pattern<br />def multiplicationStrategies = [<br /> { n, m -> n * m },<br /> { n, m -> def result = 0; n.times{ result += m }; result }<br />]<br />def sampleData = [<br /> [3, 4, 12],<br /> [5, -5, -25]<br />]<br />sampleData.each{ data -><br /> multiplicationStrategies.each{ calc -><br /> assert data[2] == calc(data[0], data[1])<br /> }<br />}<br />
    28. 28. Operator overloading<br />Override operators by overriding methods:<br />a + b a.plus(b)<br />a[b] a.getAt(b)<br />a << b a.leftShift(b)<br />switch (a) { case b: ... } b.isCase(a)<br />a == b a.equals(b)<br />a < b a.compareTo(b) < 0<br />
    29. 29. Smart switch<br />switch (x) {case 'James': println "yes it is me" breakcase 18..65: println "ok you are old" breakcase ~/Gw?+e/: println "your name starts with G and ends in e!" breakcase Date: println 'got a Date instance' breakcase ['John', 'Ringo', 'Paul', 'George']: println "Got one of the Beatles"breakdefault: println "Don't know $x“<br />}<br />
    30. 30. Groovy convenience operators<br />=~ regex find brandMatch = (line =~ /<b>([a-zA-Zs]*):<br>/) if(brandMatch) brandName = brandMatch[0][1]<br />==~ regex match <br /><=> spaceship, compareTo method of the Comparable interface<br />?:elvis ternary operator<br />Java: name = name != null ? name : "default"<br /> Groovy: name = name ?: "default"<br />?. safe dereference. No worry about nulls.<br /> street = user?.address?.street<br />* (spread) – “explode” the contents of a list or arraydef  list = ['Groovy', 'Java‘]; assert ['Groovy', 'Java', 'Scala'] == [*list, 'Scala']<br />*. spread dot. Invoke on all items, return list.<br /> List result = invoice.lineItems*.total()<br /> parent*.action //equivalent to: parent.collect{ child -> child?.action }assert ['cat', 'elephant']*.size() == [3, 8]<br />
    31. 31. GroovyBeans and JavaBeans<br />// Groovy<br />class MyBean {<br /> String item<br />}<br />MyBean b = <br /> new MyBean(item:‘foo’)<br />String val = b.item<br />b.item = ‘bar’<br />b[‘item’] = ‘bar’<br />// Java<br />class MyBean {<br /> private String item;<br /> public String getItem() {…}<br /> public void setItem(…) {…}<br />}<br />MyBean b = new MyBean();<br />b.setItem(“foo”);<br />String val = b.getItem();<br />b.setItem(“bar”)<br />
    32. 32. Why brevity matters: Quicksort<br />function sort(array) // pseudocode from Wikipedia<br /> var list less, greater<br /> if length(array) ≤ 1 return array <br /> select a pivot value pivot from array<br /> for each x in array<br /> if x < pivot then append x to less<br /> if x > pivot then append x to greater<br /> return concatenate(sort(less), pivot, sort(greater))<br />--------------------------------------------------------<br />def sort(list) { // Groovy implementation<br /> if (list.size() <= 1) return list<br /> def pivot = list[0]<br /> def less = list.findAll {it < pivot}<br /> def same = list.findAll {it == pivot}<br /> def greater = list.findAll {it > pivot}<br /> sort(less) + same + sort(greater)<br />}<br />
    33. 33. Quicksort in Java<br /> public static void qsort(Comparable[] c,int start,int end){<br /> if(end <= start) return;<br /> Comparable comp = c[start];<br /> int i = start,j = end + 1;<br /> for(;;){<br /> do i++; while(i<end && c[i].compareTo(comp)<0);<br /> do j--; while(j>start && c[j].compareTo(comp)>0);<br /> if(j <= i) break;<br /> Comparable tmp = c[i];<br /> c[i] = c[j];<br /> c[j] = tmp;<br /> }<br /> c[start] = c[j];<br /> c[j] = comp;<br /> qsort(c,start,j-1);<br /> qsort(c,j+1,end);<br /> }<br /> public static void qsort(Comparable[] c){<br /> qsort(c,0,c.length-1);<br /> }<br />
    34. 34. Object graph navigation: GPaths<br />class Invoice { List items; … }<br />class Item { Product product; int total() {…} … }<br />class Product { String name; … }<br />List<Invoice> invoices = …;<br />// get all product names where item total > 7000<br />List result = invoices.items.grep{it.total() > 7000}.product.name<br />// Java version:<br />List result = new ArrayList();<br />for (Iterator<Invoice> i = invoices.iterator(); i.hasNext(); ) {<br /> List items = i.next().getItems();<br /> for (Iterator j = items.iterator(); j.hasNext(); ) {<br /> Item item = (Item) j.next();<br /> if (item.total() > 7000)<br /> result.add(item.getProduct().getName());<br /> }<br />}<br />
    35. 35. Dynamic Groovy: multimethods<br />class Equalizer {<br /> boolean equals(Equalizer e) {...}<br /> boolean equals(Object o) {...}<br />}<br />Object obj = new Equalizer()<br />obj.equals(new Equalizer())<br />
    36. 36. Dynamic Groovy: categories<br />// Dynamically add methods to any class<br />class PersistenceCategory {<br /> static void save(Object o) { <br />// save object<br /> }<br />}<br />use (PersistenceCategory) {<br /> // all objects now have save() method<br /> new MyBean().save()<br />}<br />
    37. 37. Dynamic Groovy: meta programming<br />Change class/object behavior at runtime<br />Meta-Object Protocol (MOP)<br />You can intercept method calls and property accesses<br />invokeMethod(...)<br />getProperty(...)<br />setProperty(...)<br />etc<br />String.metaClass.groovy << { Integer number -><br />delegate * number<br />} << { String s -><br />delegate + s<br />} << { -><br />delegate + ' Groovy rocks.'<br />}<br />assert 'GroovyGroovy' == 'Groovy'.groovy(2)<br />assert 'Hello world from Groovy' == 'Hello world'.groovy(' from Groovy')<br />assert 'It is true. Groovy rocks.' == 'It is true.'.groovy()<br />
    38. 38. MarkupBuilder<br />builder = new groovy.xml.MarkupBuilder()<br />builder.numbersAndSquares {<br />description 'Numbers and squares'<br /> (3..6).each {<br />number (value: it, square: it*it)<br /> }<br />}<br /><numbersAndSquares><br /> <description>Numbers and squares</description><br /> <number value='3' square='9' /><br /> <number value='4' square='16' /><br /> <number value='5' square='25' /><br /> <number value='6' square='36' /><br /></numbersAndSquares><br />
    39. 39. SwingBuilder<br />swing = new SwingBuilder()<br />frame = swing.frame(title: 'Hello, world') {<br />panel(layout: new BorderLayout()) {<br />label(text: 'Hello, world', <br /> constraints: BorderLayout.CENTER)<br />button(text: 'Exit', <br /> constraints: BorderLayout.SOUTH,<br /> actionPerformed: {<br /> System.exit(0)<br /> })<br /> }<br />}<br />frame.pack()<br />frame.show()<br /><ul><li>SwingBuilder is a declarative hierarchal DSL for building Swing applications
    40. 40. Terse notation for JavaBeans architecture properties and events
    41. 41. Promotes native platform fidelity
    42. 42. Promotes good threading interaction
    43. 43. Promotes good MVC design
    44. 44. External Swing components are easily added</li></li></ul><li>Domain-specific languages (DSL)<br />A DSL “is a mini-language aiming at representing constructs for a given domain”<br />Groovy features for DSLs: add new methods/properties to classes, override operators.<br />Integer.metaClass.getDaysFromNow = { -><br /> Calendar today = Calendar.instance<br /> today.add(Calendar.DAY_OF_MONTH, delegate)<br /> today.time<br />}<br />println(5.daysFromNow)<br />
    45. 45. Grails ORM (GORM)<br />class Book {<br /> String title<br /> String author<br /> Date releaseDate<br />}<br />book = Book.get(id) // let's change the title<br />book.title = 'War and Peace'<br />book.save()<br />Book.listOrderByTitle()<br />Book.findByReleaseDateBetween(startDate, endDate)<br />
    46. 46. Files<br />def file1 = new File('groovy1.txt')<br />file1 << 'See how easy it is to add text to a file. ‚<br />file1.withWriter('UTF-8') { writer -><br /> writer.write('We can also use writers to add contents.‘)}<br />sw = new StringWriter()<br />file1.filterLine(sw) { it =~ /Groovy/ }<br />assert 'Working with files the Groovy way is easy. ' == sw.toString()<br />files = []<br />new File('.').eachFileMatch(~/^groovy.*.txt$/) { files << it.name }<br />assert ['groovy1.txt', 'groovy2.txt', 'groovy3.txt'] == files<br />files.each { new File(it).delete() }<br />
    47. 47. Database<br />def c = new ConfigSlurper().parse(new File('config.groovy').toURL())<br />def sql = groovy.sql.Sql.newInstance(c.db.schema, c.db.user, c.db.pwd, c.db.driver)<br />sql.execute("CREATE TABLE tbl(oid integer,nam char(5))")<br />def ds = sql.dataSet("tbl")<br />new File(‘file.csv').splitEachLine(';') {ds.add(oid: it[0], name: it[1])}<br />ds.each { println it}<br /> sql.eachRow("""select oid, name from tbl”””) {println “${it.name}}<br />db{ config.groovy<br />driver=denormalize("com.mysql.jdbc.Driver“)<br />schema="jdbc:mysql://localhost/test"<br />user="zen"<br />pwd=“p"<br /> date = new Date()<br /> active = true<br />}<br />app{<br /> //assert new Integer(20).equals(app.get("servers.setting2"));<br /> [1, 2, 3].each {this."setting${it}" = it * 10}<br />}<br />def normalize(s){return s.toUpperCase()}<br />
    48. 48. Proč Groovy?<br />Java is Groovy, Groovy is Java<br />Standardizace<br />Společný jazyk<br />Architektura – Pseudocode<br />Testování<br />Automatizace<br />Instalační a konfigurační skripty<br />Builders, DSL<br />Java Domain<br />Grails, Spring, Seam <br />
    49. 49. Otázky, diskuze<br />Ain’t-cha got no rhymes for me? Doot’n doo-doo feelin’ groovy.<br />
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×