Upload
guillaume-laforge
View
2.231
Download
1
Embed Size (px)
Citation preview
Groovy in the Enterprise:Case Studies
Guillaume LaforgeVP TechnologyG2One, [email protected]
Guillaume Laforge
Groovy Project Manager
• Spec Lead of JSR-241
Initiator of the Grails framework
Co-author of Groovy in Action
VP Technology at G2One
• The Groovy / Grails company
• Training, support, consulting
Evangelizing Groovy, Grails and DSLs
• JavaOne, JavaPolis, QCon, JAX, Sun TechDays...
Goal of this talk
Discover real-world Groovy usage in the Enterprise to better understand:
•How you can leverage Groovy in your own environment
•How to integrate Groovy
in your applications
Agenda
About Groovy and Grails
Groovy usage patterns
Integrating Groovy in your applications
Case studies
About Groovy and Grails
Groovy, a dynamic language for the JVMGrails, an agile web application framework
Groovy is...
The fastest dynamic language for the JVM
• that integrates seamlessly with Java
without any impedance mismatch
An Apache-licensed Open Source project
• successful project hosted at Codehaus
Aiming at simplifying the life of developers
• by bringing expressiveness and productivity boosts
• by borrowing good ideas from other languages
An innovative and creative project
Java-like on steroids
Syntax derived from the Java 5 grammar
• Flat learning curve for Java developers
• Supports both static and dynamic typing
Support Java 5 features
• Annotations, generics, static imports, enums...
• Sole dynamic language to support this!
Real full Java / Groovy interop
• Joint compiler
• or can be evaluated on the fly
JInterface
<<implements>>
GClass
JClass
GInterface
JClass
GClass
<<implements>>
A Java programimport 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("Ted"); names.add("Fred"); names.add("Jed"); names.add("Ned"); 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); } }}
A Groovy programimport 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("Ted"); names.add("Fred"); names.add("Jed"); names.add("Ned"); 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); } }}
A more idiomatic Groovy solution
def names = [“Ted”, “Frend”, “Jed”, “Ned”]println namesdef shortNames = names.findAll { it.size() <= 3 }println shortNames.size()shortNames.each { println it }
Features at a glance...
Don’t wait for Java 7, 8, 9
• closures, properties, collection & regex literals
Operator overloading
• Just method calls: plus(), multiply(), etc.
• BigDecimal arithmetics by default
Metaprogramming — useful for DSLs
• Property / method calls interception
Optional semicolons and parentheses
SQL, Ant, XML, templates, Swing, JMX...
Groovy usage patterns
A tool in the developer toolboxA full stack web application frameworkAn extension point in your applicationDomain-Specific Languages
Pattern: Developer tool
Great support for unit testing and mock objects
• Nice way to introduce Groovy in a project
Shell scripting reusing all your JARs
• Easy to control Ant task for custom builds
Template engine for code generation needs
Excellent XML parsing and creation support
Easy JDBC for import/export database scripts
Pattern: CoC web app development
Convention over Configuration
• Productive in minutes with scaffolding
• No useless configuration, focus on what matters
• Dir. layout, naming conventions, transparent wiring...
Grails = Groovy + Spring + Hibernate + ...
• Groovy is the glue to write your views (Groovy Server Pages)
your controllers
your services
your domain classes
Pattern: Application extension point
Customize or extend your application at extension points through Groovy scripting
Create plugins adding new functionality
Add / Update business rules at runtime
• See also Domain-Specific Languages
Personalize your reporting screens
• With Groovy templates
Remote introspection of your app
• Embed a remote Groovy shell
Pattern: Domain-Specific Language
Use a more expressive language
• than a general purpose language
Share a common metaphore between developers and subject matter experts
Domain experts can help write the rules!
Avoid boilerplate technical code
Cleanly seperate business logic from application plumbing code
Integrating Groovy in your applications
JSR-223, one API to rule them allSpring dynamic beansGroovy’s own mechanisms
JSR-223: javax.script.*
One API to rule them all
Groovy engine JAR at scripting.dev.java.net
• drop it in your classpath
ScriptEngineManager mgr = new ScriptEngineManager();ScriptEngine eng = mgr.getEngineByName(“Groovy”);String result = (String)eng.eval(“‘foo’*2”);
Spring 2 dynamic language beans
Spring 2 provides support for alternative language bean definitions & implementations
• POGOs can be wired, proxied, injected in POJOs
Configuration with the <lang:*> namespace
• <lang:groovy id=’bean’ script-source=’classpath:com.foo.GBean’
customizer-ref=’specialMetaClass’/>
Groovy beans can be “refreshed”
Groovy’s own mechanisms
Several integration mechanisms
• Eval, GroovyShell, GroovyScriptEngine
• def binding = new Binding()binding.mass = 22.3binding.velocity = 10.6def shell = new GroovyShell()def expr = “mass * velocity ** 2 / 2”assert shell.evalute(expr) == 1252.814
GroovyClassLoader for more advanced integration scenario
Main site
• Java / Tomcat / Spring / Hibernate / custom MVC
But their corporate solutions are in Grails
• Private portals for recruiters, for premium customers with focused needs
Why Grails?
• Needed a more productive webapp framework with rapid prototyping capabilities
• Needed deep integration with their Java backend custom session, reuse business services, SSO
showbiz
Biggest UK satellitebroadcaster
• also known as BSkyB
• owned by News Corp.
Developed their showbiz website on Grails
• 186+ million page views per month
• “Grails just scales” ™
Currently rewriting their main portal in Grails
Groovy as a Developer Tool
Patterson Institute for Cancer ResearchFrench Ministry of JusticeCanoo WebTest
Patterson Institute for Cancer Research
Manchester University / Cancer Research UK
Groovy in two projects
• X:Map: a Genome browser using a 54GB tileset for Google Maps
• exonmap: microarrays analysis program
Groovy used to
• Fetch latest genome sequencing information (FTP)
• Homogenize data sources
• Scan databases, extrapolate and filter data
Code generation
Groovy was used as a developer tool
• but no line of Groovy in production code
GroovyTemplateEngine
UMLXMI
Groovy XMLParsers
Canoo WebTest
Open Source tool for automating testing of web applications
invoke “http://google.com”verifyTitle “Google”setInputField name: ‘q’, value: ‘WebTest’clickButton “I’m feeling lucky”verifyTitle “Canoo WebTest”
codestreet
Market Data Works simplifies
• capturing, auditing
• editing Reuters market data
Traders can use Groovy
• modify market data feeds
• record and replay feeds
• test evolutionary scenario
Hyperic HQ: open source web infrastructure monitoring and management suite
• used in Spring Application Management Suite
Big Groovy-based plugin infrastructure
• script deployments, server reboots, threshold alerts,
resources monitoring, etc...
• agent side: custom handling of monitored resources
• also embeds a Groovy console for interactive work
• plugins updatable / reloadable at runtime
Mutual of Omaha
US Fortune 500 insurance company
Risk calculation engine in Groovypart of a mission-critical application
50,000 lines of Groovy code
• half business rules, half test code
Module part of a large EJB-based application
Choice of Groovy
• Business rules readability, maintenance by IT and Subject Matter experts, seamless Java integration
Mutual of Omaha
On business rules readability...
• Groovy’s BigDecimal support
• Simple interpolation formula (d*(b-c)+e*(c-a))/(a-b)
BigDecimal uMinusv = upperBound.subtract(value); BigDecimal vMinusl = value.subtract(lowerBound); BigDecimal uMinusl = upperBound.subtract(lowerBound); return lowerValue.multiply(uMinusv). add(upperValue.multiply(vMinusl)). divide(uMinusl, 10, BigDecimal.ROUND_HALF_UP);
(lowerValue * (upperBound-value) + upperValue * (value-lowerBound) ) / (upperBound-lowerBound)
National Cancer Institute
Cancer registry management
• Organizes large amounts of medical records
• JBoss / Oracle / Hibernate / Struts application
Groovy used in several places
• As an architecture validation system — dev. tool ensure proper layer seperation, if not, fail the build
• Param validation for customizing reporting screens
• Business rules to edit and validation medical records validity of fields, of set of fields, of records
check / fix / improve the patient files
700k patient files * 1,300 edits
Nuclear safety organization
Scientific context, with intensiveand complex computation needs
Matlab/Mathematica-like DSL on top of super efficient Java custom math library
• Thin Groovy DSL layer
• Enjoyed a math-like syntax for matrices, seamless
integration with Java
• Groovy’s operator overloading mechanism
• Friendlier to scientists and mathematicians
• Application targets 200-300 engineers & researchers
Human Resources DSL
Architecture / Agile consultancy
• Needed a way to track consultant skills & knowledge pay raises, finding the right person for the gig, etc...
Developed a DSL to represent skills
• Textual DSL transformed into a treemap-like graphics
• Integrated in Confluence as a plugin the plugin parses and generates an in-memory model
a servlet renders graphics to embed in the wiki pages
a Confluence macro renders everything on the wiki page
• Leverages Confluence’s search capabilities
Human Resources DSL
etre { idees { capture 1 formule 1 produit 1 } organisation { controle 1 abandonne 1 aligne 1 } engagement { euros 1 gens 1 idees 1 enseigner 1 }}faire { ...}
Summary
Groovy is a successful, mature and performant dynamic language for the JVM
Provides several interesting usage patterns
• Developer tool, CoC webapp development,
application extension mechanism, DSLs & business rules externalization
Used in production for mission-critical
applications, and integrated in many frameworks