Groovy And Grails

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 And Grails - Presentation Transcript

    1. Cool Web Apps with Grails, Groovy and Next-Gen Scripting Languages William Grosso Twofish
    2. Abstract
      • The rise of next-generation languages that run on top of the JVM is probably the most interesting thing to happen in the Java universe since the combination of the Spring framework and the EJB 2 specification signaled the complete implosion of the Enterprise Software Stack
      • In this talk, I'll cover, in sequence:
        • A brief overview of the state of the art of web application development
        • A brief overview of Groovy, one of the most interesting of the next-gen languages available on the JVM.
        • A brief overview of Grails, the best web-application framework currently available (where "best" is, of course, highly idiosyncratic)
        • The source code to an actual working web application written in Groovy/Grails.
    3. Actual Talk
      • The rise of next-generation languages that run on top of the JVM is probably the most interesting thing to happen in the Java universe since the combination of the Spring framework and the EJB 2 specification signaled the complete implosion of the Enterprise Software Stack
      • In this talk, I'll cover, in sequence:
        • A brief discussion of Java and the programming languages on the JVM.
        • A fairly lengthy overview of Groovy, one of the most interesting of the next-gen languages available on the JVM.
        • A brief overview of Grails, the best web-application framework currently available (where "best" is, of course, highly idiosyncratic)
        • The source code to an (admittedly small) actual working web application written in Groovy/Grails.
    4. Outline
      • Who Am I / Standard Caveats
      • Java as the Foundation
      • “ Improving” the Language: Groovy
      • Improving the Framework: Grails
      • Some Actual Code
    5. Outline
      • Who Am I / Standard Caveats
      • Java as the Foundation (2003 Recap)
      • “ Improving” the Language: Groovy
      • Improving the Framework: Grails
      • Some Actual Code
    6. Who Am I?
    7. Opinionated Talk
      • I’m not selling something
        • I’m talking about something that I think is going to be big in 2010
      • Goal is also to be somewhat provocative
          • “ I would rather be vaguely correct than precisely wrong” – John Maynard Keynes
          • “ The references are not without merit” – George Santayana
      And these are my opinions, not necessarily Twofish’s
    8. This all started in July
      • Left Engage in June
      • Decided to spend some time exploring new technologies
        • Was impressed enough by Grails to write my “Love Mashup”
      • Took the job at Twofish and left things percolating in my brain
    9. Up and running for >3 months without any attention from me
    10. Outline
      • Who Am I / Standard Caveats
      • Java as the Foundation (2003 Recap)
      • “ Improving” the Language: Groovy
      • Improving the Framework: Grails
      • Some Actual Code
    11. In 2003 …
      • I was invited to give a colloquium talk at CSU Sonoma
        • Dot-com bust was still in effect; valley was deep in recession
      • Java: It's better than you think, for reasons you haven't realized you already know.
        • http://www.slideshare.net/wgrosso/java-and-community-support-presentation/
    12. That Talk Began With ….
      • I want to convince you of two things
        • That Java, or some language like it, is inevitable from a technological point of view
        • That Java itself is inevitable from a social point of view.
      • I want to avoid using the traditional technology or “computer science” based arguments
    13. My 2003 Big Bold Claim
      • In the world of the future, programs will be increasingly be written by communities
      • The single best measure of whether a programming language is worth using is: how well does it support communities.
        • The social aspects of the language dominate the technological aspects of the language
    14. Supporting Communities
      • New programmers must be able to get up to speed in the language
      • Platforms to learn the language on must be cheap and plentiful
      • Programmers must be able to use the language on whatever machine they’re using
      • Programmers must be able to understand and reuse each other’s code
      • Old code must survive in a useful form
        • And evolve and improve
    15. I Was Right
      • Take a look at the libraries out there
      • Take a look at Java’s market share
      • It’s entrenched and dominant
    16. Outline
      • Who Am I / Standard Caveats
      • Java as the Foundation (2003 Recap)
      • “ Improving” the Language: Groovy
      • Improving the Framework: Grails
      • Some Actual Code
    17. But I Wasn’t Completely Right JVM Platform Libraries and Application Frameworks Your App / Your Web App Your Libraries Your Prototypes Down here, Java, super clear semantics, WORA etcetera win Hmm. Community properties probably only matter for largish things that you share or keep and reuse for a long time. Maybe we can do better than Java?
    18. Lots of people having similar thoughts. The JVM is robust enough, and the platform is robust enough, and … that people are starting to seriously layer languages on top.
    19. Short list of “interesting” languages: Jython JRuby Scala Groovy Kawa Clojure PHP NetRexx (??)
    20. Completely a sidenote: If you’re curious about programming language design, this is the single best site on the web
    21. Closures have been THE hot topic in commercial language design
    22. Odersky’s claim: closures + first class containers + super strong typing are the bees knees
    23. Complexity is bad. Java is near the edge of the cliff. 4.5M PDF and a Tiny Thumbnail? For Generics? Ruby has a similar problem (more later)
    24. Desiderata for the Tiers JVM Platform Libraries and Application Frameworks Your App Your Libraries Your Prototypes Strong typing Absolutely clear semantics Minimal evolution of language None of the other stuff is necessary Looks like Java Clear, readable code Non-verbose language Complete integration with Java First class containers Closures Great XML support Rapid Prototyping (REPL) Metaobject Protocol
    25. Only Groovy Makes the Short List
      • Start with: Jython, JRuby, Scala, Groovy, Kawa, Clojure, PHP, NetRexx
        • Only Scala and Groovy look even remotely like Java
      • Both Scala and Groovy have first class containers, complete integration with Java, closures, rapid prototyping, and great XML support
      • Groovy’s metaobject protocol, and Grails, make it the winner
        • Note that I’m completely avoiding the usual phrasing of the “dynamic typing” question, since I find it annoying
    26.  
    27. Looks Like Java Go read the code examples It’s easy
    28. Let’s Look at Concurrency Not Java def? 1 .. 8 sleep 30 But … it’s close
    29. Complete Integration with Java
      • Need to be able to use any library or jar
        • Seamlessly create and invoke java objects
      • Groovy adopts the Java model under the covers
      • Groovy compiles to Java classes so that Java applications can use the next-gen stuff
        • When necessary
        • But if you buy the stacking diagram, not all that often.
    30. import groovy.swing.*; import java.awt.*; import javax.swing.*; class Model extends Observable { static CURRENCY = ["USD", "EURO", "YEN"] private Map rates = new HashMap() private long value void initialize(initialRates) { (0..CURRENCY.size() - 1).each { setRate(CURRENCY[it], initialRates[it]) } } // setting rate for currency void setRate(currency, f) { rates.put(currency, f); setChanged(); notifyObservers(currency); } // setting new value for currency void setValue(currency, double newValue) { value = Math.round(newValue / rates[currency]); setChanged(); notifyObservers(null); } // getter for value for particular currency def getValue(currency) { value * rates[currency] } } class RateView extends JTextField implements Observer { private Model model; private currency; public void setModel(Model model) { this.model?.removeObserver(this) this.model = model model.addObserver(this) } public void update(Observable o, Object currency) { if (this.currency == currency) text = String.format("%15.2f", model.rates[currency]) } } class ValueView extends JTextField implements Observer { private Model model private currency public void setModel(Model model) { this.model?.removeObserver(this) this.model = model model.addObserver(this) } public void update(Observable o, Object currency) { if (currency == null || this.currency == currency) text = String.format("%15.2f", model.getValue(this.currency)); } }
    31. swing = new SwingBuilder() model = new Model() frame = swing.frame(title: "Groovy SwingBuilder MVC Demo", layout: new GridLayout(4, 3), size: [300, 150], defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE) { label("currency") label("rate") label("value") for (c in Model.CURRENCY) { label(c) widget(new RateView(), model: model, currency: c, action: swing.action(closure: { event -> event.source.model.setRate(event.source.currency, event.source.text.toDouble()); })) widget(new ValueView(), model: model, currency: c, action: swing.action(closure: {event -> event.source.model.setValue(event.source.currency, event.source.text.toDouble()); })) } } frame.show() model.initialize([1.0, 0.83, 0.56]);
    32.  
    33.  
    34. First Class Containers
      • Boils down to
        • Easy construction syntax
        • Methods that take closures and perform common operations.
          • find (returns first value it finds that matches)
          • findAll (returns collection of all matches)
          • every (boolean valued check on collection)
          • each (iterates through collection and hands elements to closure)
          • collect (changes collection)
    35. weekMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday", "We" : "Wednesday", "Th" : "Thursday", "Fr" : "Friday", "Sa" : "Saturday" ] weekMap.each() { key, value -> println "${key} == ${value}" }
    36. Gafter’s Def’n of Closure
      • A closure is a function that refers to free variables in its lexical context
      • A function is a block of code with parameters. It may produce a result value
      • A free variable is an identifier used but not defined by the closure
    37. In Practice
      • A closure is a function pointer that knows all the variables that were in scope when it was defined
      • Can be passed around as an argument
      • Can be called at any time.
      def foo = { a,b,c -> bunch of code} foo(“e”, “f”, “g”)
    38. Inner Classes are Close!
      • Java solution: Define an anonymous inner class that implements a well-known interface
      • But
        • Because they’re classes, they don’t quite behave the same way
        • Involve a lot more (physical) typing
    39. Don’t believe me? Neal likes Java a LOT more than I do
    40. XML Support
      • <interactive example with groovy console>
      def CAR_RECORDS = ''' <records> <car name='HSV Maloo' make='Holden' year='2006'> <country>Australia</country> <record type='speed'>Production Pickup Truck with speed of 271kph</record> </car> <car name='P50' make='Peel' year='1962'> <country>Isle of Man</country> <record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record> </car> <car name='Royale' make='Bugatti' year='1931'> <country>France</country> <record type='price'>Most Valuable Car at $15 million</record> </car> </records> ''' def records = new XmlSlurper().parseText(CAR_RECORDS) def allRecords = records.car println allRecords.size() println records.car[0].name() println records.car[0].@year println records.car[0].country
    41. XML Support II
      • XMLBuilder
      • Will be discussed in detail after MetaObject Protocol section
    42. Rapid Prototyping: Scripts, Shell and Console
      • Scripts – groovy doesn’t need to use classes.
        • SwingBuilder example a few slides ago didn’t use classes for the executable bits.
      • groovysh – command line shell (seen a few slides ago)
      • Groovyconsole – swing GUI for playing with scripts
        • Supports cut and paste better than command line
    43. Metaobject Protocol
      • A metaobject protocol (MOP) is an interpreter of the semantics of a program that is open and extensible. Therefore, a MOP determines what a program means and what its behavior is, and it is extensible in that a programmer (or metaprogrammer ) can alter program behavior by extending parts of the MOP. The MOP exposes some or all internal structure of the interpreter to the programmer. The MOP may manifest as a set of classes and methods that allow a program to inspect the state of the supporting system and alter its behaviour . MOPs are implemented as object-oriented programs where all objects are metaobjects.
      • Thanks Wikipedia !
    44. MetaObject Protocols: The Point
      • At runtime, can find out about, and alter, class definitions
        • Add or remove methods
        • Dynamically change implementations of methods
        • Handle “no such method” at the recipient, not the caller
      • Groovy
        • invokeMethod
        • ExpandoMetaclass
        • propertyMissing
        • methodMissing
      OPINIONS VARY AS TO WHETHER ALLOWING THIS SORT OF THING IS A GOOD IDEA!!!!
    45. Chris will talk more about GORM later on
    46. Builders
      • Lots and lots of things are tree-like data structures
        • User interfaces (structure of Swing components)
        • HMTL Documents (XML documents)
        • Invoices have line items …
      • Big-Ass Completely Unsupported Claim: Every DSL is a tree-like data structure + an interpretation.
              • Or Should Be!
    47. What’s Martin Fowler been doing since the refactoring book anyway?
    48.  
    49. How to Build a Builder
      • Implement a (Java!) subclass of BuilderSupport
      • Or just use methodMissing
        • It’s really what the Java’s doing anyway.
      protected abstract Object createNode(Object name) protected abstract Object createNode(Object name, Map attributes) protected abstract Object createNode(Object name, Map attributes, Object value) protected abstract Object createNode(Object name, Object value) protected abstract void setParent(Object parent, Object child) Groovy is designed to work with Java.
    50. MarkupBuilder import groovy.xml.MarkupBuilder def writer = new StringWriter() def xml = new MarkupBuilder(writer) xml.records() { car(name:'HSV Maloo', make:'Holden', year:2006) { country('Australia') record(type:'speed', 'Production Pickup Truck with speed of 271kph') } car(name:'P50', make:'Peel', year:1962) { country('Isle of Man') record(type:'size', 'Smallest Street-Legal Car at 99cm wide and 59 kg in weight') } car(name:'Royale', make:'Bugatti', year:1931) { country('France') record(type:'price', 'Most Valuable Car at $15 million') } } println writer.toString()
    51. Outline
      • Who Am I / Standard Caveats
      • Java as the Foundation (2003 Recap)
      • “ Improving” the Language: Groovy
      • Improving the Framework: Grails
      • Some Actual Code
    52. Rails as a Thunderbolt
      • Convention over configuration
        • Kind of like design patterns, except there’s only one pattern
      • ActiveRecord simplifies DB access
      • Migrations simplifies DB upgrades
      • Capistrano simplifies deployment
      • Plugin architecture (framework as platform)
      • Ruby as the base language
    53. The Rails guys invented the “movie to demo the framework” idea and their movies are still WOW OH WOW GOOD
      • PHP
      • PHP
      • Java (Coldfusion)
      • PHP
      • .NET
      • Perl
      • PHP
      • Java
      • .NET
      • PHP
      • Java
      • Java
      • PHP
      • Java
      • PHP
      • Ruby
      • Perl
      • Java
      • Java
      • PHP
      PHP: 8 Java: 7 .NET: 2 Perl: 2 Ruby: 1
    54. In 4 years, Rails has made very impressive strides. Market leader in the “early stage startup” category.
    55. Issues with Ruby
      • Powerful language, currently in flux
        • Transition from 1.8 to 1.9 is slow and painful
      • Not clear what the language definition is
      • Syntax is awful. Like a modified PERL with additional incomprehensibility
        • Okay, that was biased.
      • The standard implementation is low performance and fragile
    56. Backwards compatibility is not a huge priority
    57. Backwards compatibility is not a huge priority
    58. This is scary
    59. Of course, Java is mostly developed by Sun ….
    60. This is from a Ruby guy who doesn’t like JRuby very much …
    61. Issues with Rails
      • Focus on CRUD
        • Works very well for the standard web architecture
        • Good for building standalone applications
          • Integration scenarios not well supported
          • Legacy code not well supported
      • Far fewer man hours of development, qa, or deployment experience than many other frameworks
        • Compare to Spring, for example
    62. Grails is “Groovy on Rails”
      • Adopt many, if not all, of the key ideas of Rails
        • Swap out Ruby for Groovy
        • Swap out Rails for Spring, Hibernate, SiteMesh, and lots of glue
      • Application code is written in Groovy
        • With “drop into Java for performance” drop-dead easy
      • Leverage JVM + Java libraries for the infrastructure
    63. Pieces / Parts
      • GSP – “Groovy Server Pages”
        • A lot like JSP
      • GORM – “Groovy Object Relational Mapping”
        • Hibernate + Bionicness. Really impressive.
      • Core abstractions:
        • Domain classes
        • Controllers
        • Views
        • Services
      More on these later
    64. GORM
      • <<Chris– a world class expert in GORM>>
    65. Plugins and Extensability
      • Grails is a platform for extensions
      • Makes a lot of sense given the point is to build a Rails that leverages Java
    66. SWAG Estimate: About ¾ of plugins are mentioned here (BIRT, for example, is not)
    67. Outline
      • Who Am I / Standard Caveats
      • Java as the Foundation
      • “ Improving” the Language: Groovy
      • Improving the Framework: Grails
      • Some Actual Code
    68. Twofish Model TFEL TFEL DB TFEL DB
      • JBoss 4 on Java 6.
      • Everything clustered
      • Everything replicated
      • SOAP
      • Fat client SDK
      PS
      • Layered apps
      • In our data center
      • Customer specific
      • Lightweight frameworks rock
    69. <<IntelliJ>>
    70. Annoyances (Love Mashup)
      • Mainly from my incompetence with HTML.
      • Also: imperfect prototyping environment
        • Changes in controllers and views reflected immediately
        • Changes in domain models often require restarting dev server
        • Changes in services or supporting code almost always require a dev server restart
    71. Plugins (Love Mashup)
      • Cloud Foundry – easy deploy to Amazon
      • YUI – cleaner UI components
        • To be honest, I used OSWD for the layout
    72. Annoyances (Twofish)
      • Oddly enough, the Java stack
        • JDK has an XML Parser
        • Grails has a copy of Xerces
        • Twofish Client SDK has a copy of Xerces
        • Endorsed directories are painful
          • We can’t use the standard deployers
      • Intellij not yet supporting Grails 1.1 or Groovy 1.6
    73. Plugins (Twofish)
      • Quartz plugin – Background processing
      • BIRT plugin – Enterprise class reports
      • Xfire plugin – makes handling SOAP requests trivial
    74. Additional Reading
    75. This is a great series of articles. Whenever anyone tells you a technology is going to be big, ask yourself: WWTT?
    76.  
    77.  

    + William GrossoWilliam Grosso, 10 months ago

    custom

    1037 views, 0 favs, 1 embeds more stats

    Talk given at SDForum's Java SIG on Jan 6, 2009

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 1037
      • 1004 on SlideShare
      • 33 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 22
    Most viewed embeds
    • 33 views on http://sdforumjavasig.wordpress.com

    more

    All embeds
    • 33 views on http://sdforumjavasig.wordpress.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