Groovy Introduction - JAX Germany - 2008

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Favorites, Groups & Events

    Groovy Introduction - JAX Germany - 2008 - Presentation Transcript

    1. Groovy a Successful Dynamic Language for the JVM Guillaume Laforge Vice-President, Technology G2One, Inc. http://www.g2one.com
    2. Goal of This Talk
        • Learn more about the Groovy dynamic language for the JVM, what’s new in the latest version, and how you can use it in your projects!
    3. Guillaume Laforge
      • Groovy Project Manager
      • JSR-241 Spec Lead
      • Initiator of the Grails framework
      • Co-author of Groovy in Action
        • By Dierk König, et al.
      • Vice-President Technology
    4. Agenda
      • What’s Groovy?
      • Syntax basics
      • Groovy APIs
      • What’s new in Groovy 1.5?
      • Domain-Specific Languages
      • Integrating Groovy in your applications
      • Summary
      • Q&A
    5. What’s Groovy?
      • An award-winning alternative dynamic language for the JVM
      • State of the Groovy Nation
    6. Sugar in your Java
      • Groovy is Java-like
        • Easy to learn for a Java developer
          •  flat learning curve
        • Simpler than Java for beginners and subject matter experts
      • Seamless integration with Java
        • You can mix Groovy and Java objects together
          • Groovy class extending Java class implementing Groovy interface, and vice versa…
        • Same strings, regex, APIs, OO, threads, security
          • Same paradigm and platform!
          • No impedance mismatch!
    7. Features at a Glance
      • Fully object-oriented
      • Closures : reusable & assignable code blocks
      • Properties support: don’t wait for Java 7 or 8!
      • Operator overloading
      • Native syntax for list, maps and regex
      • Multimethods: call the right method!
      • GPath: XPath-like navigation in object graphs
      • BigDecimal arithmetics by default
      • Optional semi-colons and parenthesis
      • SQL, Ant, XML, templates, Swing, XML-RPC, JMX
      • Perfect for Domain-Specific Languages
    8. Already Integrated Everywhere
      • AntHill Grails eXo Platform JBoss Seam NanoContainer Eclipse XWiki ServiceMix Tapestry Wicket TestNG SoapUI Turbine Oracle OC4J Blojsom NetBeans OpenEJB JBoss Drools 1060NetKernel RIFE GroovyRules Mule FreeMind LuxorXUL Spring Ant Maven IntelliJ IDEA Simple JSPWiki eXist Canoo WebTest Biscuit ThinG Oracle Data Integrator Struts2 Eclipse JMeter JFreeChart, Hyperic HQU
    9. Used in Mission-Critical apps
      • Mutual of Omaha – Fortune 500 US Comp.
        • 45,000 lines of Groovy (half business code / half test code)
        • Integrated in an EJB as a risk calculation engine for insurance policies
        • Involved Java beginners, developers, and subject matter experts
        • Exact arithmetic support, perfect Java integration, closures  ideal for business rules expression
    10. Many books
    11. JAX 2007 Innovation Award
      • 40 proposals / 10 nominees
      • Groovy won the first prize
        • Most innovative and creative project
        • 10,000 euros donation
      • Past winner was Spring
    12. Syntax Basics
      • Groovy as a Java-superset
      • Syntax examples:
        • Properties, lists, maps,
        • ranges, regex, strings,
        • closures
    13. Valid Java Program
      • import java.util.List;
      • import java.util.ArrayList;
      • class Erase {
      • private List filterLongerThan(List strings, int length) {
      • List result = new ArrayList();
      • for (int i = 0; i < strings.size(); i++) {
      • String s = (String) strings.get(i);
      • if (s.length() <= length) {
      • result.add(s);
      • }
      • }
      • return result;
      • }
      • public static void main(String[] args) {
      • List names = new ArrayList();
      • names.add(&quot;Ted&quot;);
      • names.add(&quot;Fred&quot;);
      • names.add(&quot;Jed&quot;);
      • names.add(&quot;Ned&quot;);
      • System.out.println(names);
      • Erase e = new Erase();
      • List shortNames= e.filterLongerThan(names, 3);
      • System.out.println(shortNames.size());
      • for (inti= 0; i< shortNames.size(); i++) {
      • String s = (String) shortNames.get(i);
      • System.out.println(s);
      • }
      • }
      • }
    14. Valid Groovy Program
      • import java.util.List;
      • import java.util.ArrayList;
      • class Erase {
      • private List filterLongerThan(List strings, int length) {
      • List result = new ArrayList();
      • for (int i = 0; i < strings.size(); i++) {
      • String s = (String) strings.get(i);
      • if (s.length() <= length) {
      • result.add(s);
      • }
      • }
      • return result;
      • }
      • public static void main(String[] args) {
      • List names = new ArrayList();
      • names.add(&quot;Ted&quot;);
      • names.add(&quot;Fred&quot;);
      • names.add(&quot;Jed&quot;);
      • names.add(&quot;Ned&quot;);
      • System.out.println(names);
      • Erase e = new Erase();
      • List shortNames= e.filterLongerThan(names, 3);
      • System.out.println(shortNames.size());
      • for (inti= 0; i< shortNames.size(); i++) {
      • String s = (String) shortNames.get(i);
      • System.out.println(s);
      • }
      • }
      • }
    15. Groovier solution 
      • def names = [&quot;Ted&quot;, &quot;Fred&quot;, &quot;Jed&quot;, &quot;Ned&quot;]
      • println names
      • def shortNames = names.findAll{
      • it.size() <= 3
      • }
      • println shortNames.size()
      • shortNames.each{ println it }
    16. Properties Support
      • Don’t wait for Java 7/8/9 
      • Getters / setters are boring boiler-plate code
      • Groovy adds support for properties
        • Declared fields get automagic accessors
      • Example
        • class Person { String name String firstName }
    17. Litterals for lists, maps, ranges, regex, strings
      • List: def list = [&quot;Groovy&quot;, &quot;Grails&quot;]
      • Map: def map = [CA: &quot;Calif.&quot;, TX: &quot;Texas&quot;]
      • Ranges: def uptoten = 1..10
      • Regex: assert &quot;fooooo&quot; ==~ /fo*/
      • Multiline strings:
        • def s = &quot;&quot;&quot; multi line string&quot;&quot;&quot;  
      • Gstring
        • println &quot;My name is ${name}&quot;
    18. Closures
      • Don’t wait for Java 7/8/9, get closures now!
      • Reusable / assignable code blocks
        • Combine, store, share data and logic
      • Examples
        • new File('x.txt').eachLine{ println it }
        • [0, 1, 2].each { println it }
        • def numbers = 1..100 def odd = { it % 2 == 1 } numbers.findAll { it > 90 } numbers.findAll( odd )
    19. Groovy APIs
      • Groovy Development Kit
      • Examples: XML, SQL, Swing and Office automation
    20. Groovy Development Kit
      • Simplified APIs for common tasks
        • Mocking / stubbing support
        • XML parsing and GPath navigation
        • SQL support with exception & resource handling
        • Script Ant with the AntBuilder
        • Create Swing UIs easily with SwingBuilder
        • Templating support à la Velocity
        • Script COM / ActiveX components on Windows
        • Consume / expose XML-RPC / SOAP services
        • Handle JMX beans as local objects
    21. XML Parsing and GPath Navigation
      • Given this XML snippet
        • def xml = &quot;&quot;&quot; <languages> <language name=&quot;Groovy&quot;> <feature coolness=&quot;low&quot;>SQL</feature> <feature coolness=&quot;high&quot;>Template</feature> </language> <language name=&quot;Perl&quot;/> </languages>&quot;&quot;“
      • Navigate the object graph
        • def root = new XmlParser().parseText(xml) println root.language.feature[1].text() root.language.feature . findAll { it['@coolness'] == &quot;low&quot; } .each{ println it.text() }
    22. SQL support
      • Easy to use JDBC thanks to closures
        • def sql = Sql.newInstance(url, usr, pwd, driver) sql.execute(&quot;insert into table values ($foo, $bar)&quot;) sql.execute(&quot;insert into table values(?,?)&quot;, [a, b]) sql.eachRow(&quot;select * from USER&quot;) { print it.name } def list = sql.rows(&quot;select * from USER&quot;)
      • DataSet notion: « poor-man » ORM
        • def set = sql.dataSet(&quot;USER&quot;) set.add(name: &quot;Johnny&quot;, age: 33) set.each { user -> println user.name } set.findAll { it.age > 22 && it.age < 42 }
    23. SwingBuilder
      • def theMap = [color: &quot;green&quot;, object: &quot;pencil&quot;] def swing = new SwingBuilder() def frame = swing.frame( title: 'A Groovy Swing', location: [240,240], defaultCloseOperation:WC.EXIT_ON_CLOSE) { panel { for (entry in theMap) { label(text: entry.key) textField(text: entry.value) } button(text: 'About', actionPerformed: { def pane = swing.optionPane(message: 'SwingBuilder') def dialog = pane.createDialog(null, 'About') dialog.show() }) button(text:'Quit', actionPerformed:{ System.exit(0) }) } } frame.pack() frame.show()
    24. Automating Office Applications
      • An additional module provide VB-like scripting capabilities with a VB-like syntax
      • Example
        • def outlook = new ActiveXProxy(&quot;Outlook.Application&quot;) def message = outlook.CreateItem(0) def emails = [email_address] . com   def rec= message.Recipients.add(emails) rec.Type = 1 message.Display(true)
    25. Domain-Specific Languages
      • Why create DSL?
      • How to create DSLs?
    26. Why Create a DSL?
      • Use a more expressive language than a general programming language
      • Share a common metaphore between developers and subject matter experts
      • Have domain experts help design the business logic of an application
      • Avoid cluttering business code with too much boilerplate technical code
      • Cleanly seperate business logic from application code
    27. Putting it all together
      • Optional parens, map syntax, props on ints
        • move left
        • compare indicator: ‘NIKEI’, withFund: ‘XYZ’
        • account.debit amount: 30.euros, in: 3.days
      • Custom control structures with closures
        • unless ( account.balance < 0 ) { account.debit 10.dollars }
        • execute( withTimeoutOf: 50.seconds ) { … }
      • Operator overloading
        • a + b  a.plus(b)
        • taskA | taskB  taskA.or(taskB)
    28. Builder pattern at the syntax level
      • Tree structures are everywhere
        • XML, GUI components, Ant tasks, conf files…
      • Through closure & chained method calls
        • new MarkupBuider().invoices { invoice(id: &quot;4&quot;) { line &quot;product 1&quot; line &quot;product 2&quot; } }
      • Create your own « builder »
        • Extend BuilderSupport, or FactoryBuilderSupport
    29. What’s new in 1.5?
      • Java 5 features
      • New dynamic capabilities
      • Performance improvements
      • IDE support
    30. What’s New?
      • Java 5 features
        • Annotations, generics, enums, static imports
      • New powerful dynamic capabilities
        • ExpandoMetaClass contributed by Grails
      • Performance improvements
        • Regular gains of perf. between the last releases
      • IDE support : IntelliJ IDEA, Eclipse, NetBeans
    31. Java 5 Features
      • Why adding Java 5 features to Groovy?
        • To leverage Enterprise frameworks making use of annorations and generics
          • Spring, JPA, Hibernate , Guice, TestNG, JUnit 4…
        • Groovy is the sole alternative dynamic language for the JVM supporting annotations
        • Groovy is Java-like, but is closer to being a pure Java-superset
      • If you need annotations / generics and want to benefit from a dynamic language
        • Look no further, Groovy is the sole option
    32. Annotations Example
      • Taken from JBoss Seam ’s documentation
      • @Entity @Name(&quot;hotel&quot;) class Hotel implements Serializable { @Id @GeneratedValue Long id @Length(max=50) @NotNull String name @Override String toString() { &quot;Hotel ${name}&quot;  } }
    33. Enums example with a Groovy switch
      • enum Day { SUNDAY,  MONDAY, TUESDAY, WEDNESDAY, 
      • THURSDAY, FRIDAY, SATURDAY }
      • def today = Day.SATURDAY
      • switch (today) {
      •      case [Day.SATURDAY, Day.SUNDAY]: 
      •          println &quot;Weekends are cool&quot;
      •          break
      •      case Day.MONDAY..Day.FRIDAY: 
      •          println &quot;Boring work day&quot;
      •          break
      •      default: 
      •          println &quot;Are you sure this is a valid day?&quot;
      • }
    34. New dynamic features
      • Grails contributed the ExpandoMetaClass
        • Easily add new behavior to existing classes
        • Symbiotic relationship between both projects
      • Ex: Adding a meters property to numbers
        • Integer.metaClass.getMeters = { -> new Distance(delegate, Distance.METER) } println 3.meters
    35. IntelliJ IDEA plugin
    36. Eclipse plugin
    37. Integrating Groovy in your Applications
      • Why integrating Groovy in your applications?
      • The different integration mechanisms
    38. Why Integrating Groovy?
      • Groovy’s great support for testing
        • Mocks & stubs, GroovyTestCase
        • More concise & readable tests
      • Handy tool int the developer toolbox
      • Externalize business rules
        • Business rules be written by domain experts
        • Rules follow their own lifecycle
      • Providing extension points in your apps
        • For third-party plugins
        • Customizing the app to clients’ needs
    39. Several Integration Mechanisms
      • Java 6’s scripting APIs (JSR-223)
      • Spring dynamic language support
      • Groovy’s own mechanisms
    40. JSR-223: javax.script.* in JDK 6
      • One API to rule them all!
      • Dedicated Groovy engine on scripting.dev.java.net
        • Drop it in your classpath!
      • Example
        • ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine gEngine = manager.getEngineByName(&quot;groovy&quot;); String result = (String)gEngine.eval(&quot;’Foo’ * 2&quot;);
    41. GroovyShell
      • Easily evaluate expressions
        • Pass variables in and out
        • Can provide global reusable functions
      • Example
        • def binding = new Binding() binding.mass = 22.3 binding.velocity = 10.6 def shell = new GroovyShell( binding ) def expression = &quot;mass * velocity ** 2 / 2&quot; assert shell.evaluate(expression) == 1252.814
    42. GroovyClassLoader
      • Most powerful integration mechanism
      • With GCL, you can
        • Parse and compile classes
        • Provide a resource loader defining the location of sources
          • Database, flat files, XML files, distant URLs…
        • Define Java security rules
          • To avoid System.exit(0) in an Embedded DSL!
        • Even transform the Abstract Syntax Tree !
    43. Spring 2 Groovy integration
      • Spring 2 provides support for alternative language bean definitions and configuration
        • A POGO can be wired the like a POJO and be proxied
        • You can mix languages in your Spring application
        • POGO and POJO can be injected within each other
      • Configuration of a POGO bean with the specific lang namespace , and a custom MetaClass
        • <lang:groovy id=&quot;events&quot; script-source=&quot;classpath:dsl/eventsChart.groovy&quot; customizer-ref=&quot;eventsMetaClass&quot; />
    44. Conclusion
      • Summary
      • Resources
      • Q&A
    45. Summary
      • The Groovy dynamic language for the JVM simplifies the life of developers through powerful APIs
      • Groovy opens some interesting perspectives towards extending your application
      • Groovy provides the most seamless Java integration experience
      • Groovy lets you create DSL s
      • Groovy protects your investment in skills, tools, libraries and application servers
    46. Resources
      • Groovy: http: //groovy . codehaus . org
      • Grails: http: //grails . org
      • Groovy blogs: http: //groovyblogs . org
      • AboutGroovy: http: //aboutgroovy . com
      • G2One: http://www.g2one. com
    47. G2One, Inc.
      • Groovy & Grails at the source!
        • Graeme Rocher, Grails lead
        • Guillaume Laforge, Groovy lead
        • Plus key committers
      • Professional Services
        • Training, support, consulting
        • Custom developments
          • Connectors, plugins, etc…
    48. Questions & Answers

    + Guillaume LaforgeGuillaume Laforge, 2 years ago

    custom

    968 views, 0 favs, 1 embeds more stats

    Groovy introduction at JAX Germany 2008

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 968
      • 966 on SlideShare
      • 2 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 0
    Most viewed embeds
    • 2 views on http://lyrics.filestube.com

    more

    All embeds
    • 2 views on http://lyrics.filestube.com

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories

    Tags