Groovy & Grails: Scripting for Modern Web Applications

Post on 09-May-2015

3.791 views 2 download

description

Dynamic scripting languages are a powerful addition to a software designer’s toolbox. Rails/Ruby and Python have not gained much acceptance in the enterprise. Grails and Groovy are an attempt to bridge the gap between the modern scripting world and the Enterprise Java world. This talk is an introduction towards building web applications in Grails. First we will go about creating a REST based webservice. We will also show how to replace the default database backend of Grails with MySQL. We will then build a web application that consumes this webservice. The emphasis will be on the design patterns and idioms in Grails that address the web application development lifecycle.

Transcript of Groovy & Grails: Scripting for Modern Web Applications

Groovy & GrailsScripting for Modern Web

Applications

Rohit Nayak

Talentica Software

Agenda Demo: Quick intro to Grails Scripting, Web Applications and

Grails/Groovy REST service in Grails

Demo Internals

Web Client in Grails Demo Internals

Perspective

Demo

Quick Intro to Grails

Maggi

grails create-app Maggi Domain class: Noodle, Packaging grails generate-all Noodle, Packaging grails run-app

Web Frameworks with Scripting

Ruby on Rails (2004)

CakePHP (2005)

Django / Python (2005)

Groovy on Grails (2006)

Power of these frameworks

Baked Experience

The Language

Agility / Productivity

Baked Experience

Model View Controller Object-Relational Mapping Templates Layout URL rewriting Ajax support XML / JSON support

The Language

Dynamic More expressive code Smaller code Native support for Lists, Hashmaps Lang. support for IO, Net, XML Idioms for common usage

Agile

Scaffolding Unit tests No build cycles Built-in webservers Fail faster!

http://www.zacker.org/ruby-on-rails (Nov 2nd)

http://www.zacker.org/ruby-on-rails (Nov 2nd)

HelloWorld.javapublic class HelloWorld {

String name;

public void setName(String name){ this.name = name; }

public String getName(){ return name; }

public String hello(){ return “Hello “+ name; }

public static void main(String args[]) {

HelloWorld helloWorld = new HelloWorld();

helloWorld.setName(“Java”);

System.out.println( helloWorld. hello() );

}

}

HelloWorld.groovyclass HelloWorld {

String name

def hello() { "Hello $name" }

}

def helloWorld = new HelloWorld(name:"Groovy")

println helloWorld.hello()

Key Groovy Features Java-like syntax Complements Java Object-oriented Targets Java VM (JSR-241)

Invoke Java class within Groovy Invoke Groovy class within Java

Dynamic Scripting (JSR-223) Brevity

Brevity

Optional semicolons, package prefixes

Automatic imports (java.util.*, java.net.*, java.io.*, groovy…)

GroovyBeans (generated accessors) Optional typing Optional return

Groovy Gravy GStrings: ”$book.title: $book.author ($

{book.reviewers.length})”

Regular expressions: assert ‘12345’ =~ /\d+/

Only objects: primitives converted to Reference Types

Lists: def list = [1, 2, 'hello', new java.util.Date()]

Maps: def map = ['name':‘Indic Threads', 'location':‘Pune']

Closures [1,2,3].collect {it*2} ===> [2, 4, 6]

String literals – single, double, triple quotes

Closures

Anonymous block of statements First class objects Parameters including default values Return value Binds variables in definition scope

Pluggable Behavior - Groovydef sum(num, closure)

{

def sum=0

1.upto(num) {

if (closure(it)) sum+=it

}

}

total=sum(10){it%2==0}

println "Total: ${total}"

Pluggable Behavior - Javapublic static int sum(int num, Algo algo){

int val=0;for (int i=1; i<=n, i++) {

if (algo.eval(i)) val+=i;}return val;

}public static void main (String[] args){

int total;total = sum(10, new Algo() {

public boolean eval(int i){

return i%2==0;}

}});System.out.println("Total: " + total);

}

Dynamic Programming Add methods, properties to classes/objects

at run-time Mixins to inject behaviour

class ListUtils {static foo(List list) { "foo called" }

}List.metaClass.mixin ListUtils

assert "foo called" == [1, 2, 3].foo() Can extend class field-access mechanism Dynamic method invocation

myObj.”$action”()

Poolster

Online “football pools” application Entities: Game, User Game Stake, Option, Ends To join User chooses an Option REST Webservice backend Clients: iPhone, Grails, Android,

Silverlight

Demo

The Poolster Webservice

Grails – Philosophy Convention over Configuration

Magic directories Implicit table names, column names

Don’t Repeat Yourself Database maps to model class hasMany defines relationship & declares variable Layout, form validations

Lightweight Modify and F5

Strong shoulders Spring (Grails MVC, DI, Transactions) Hibernate (GORM) Ant, JUnit, SiteMesh, log4j, OSCache

Grails – Key Features

Database mapping, relations MySQL integration URL Mapping Authentication / Filters Logging

Demo

Poolster Web Client

Grails Web Application

Rest Service Proxy Custom Tag libraries Sitemesh layout Templates

Unseen Gravy

JUnit test cases, Mocking/Stubbing Web testing with Canoo Webtest Bootstrapping Pagination

Cons

Learning curve Performance ?! Early adopter issues Dynamic/Functional programming

Scripted In Groovy

Canoo WebTest Tellurium Ant / Maven config files SoapUI script step Spring beans

Invoking Groovy Scriptsimport java.io.File;import groovy.lang.Binding;import groovy.util.GroovyScriptEngine;

public class ScriptEngineEmbedGroovy{public static void main(String args[]) throws Throwable{

String[] paths = {"C:\\groovy"};GroovyScriptEngine gse = new

GroovyScriptEngine(paths);Binding binding = new Binding();Object[] var1 = 123;binding.setVariable("args",var1);String ret = gse.run(“DoSomething.groovy", binding);

}}

Groovy Script Evalimport javax.script.ScriptEngine;import javax.script.ScriptEngineManager;

public class CalcMain { public static void main(String[] args) throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("groovy");

// basic example System.out.println(engine.eval("(1..10).sum()")); // 55

// example showing scripting variables engine.put("first", "HELLO"); engine.put("second", "world"); System.out.println(engine.eval("first.toLowerCase() +

second.toUpperCase()")); // helloWORLD }}

Using Grails

Web UI Flow Prototyping REST Service Prototyping Supporting Web Apps Internal Web Apps

Using Groovy

Glue together existing components Reengineering legacy components Externalizing business logic, rules Domain Specific Languages Smart Configuration Scripting language of choice

Getting Started

groovy.codehaus.org grails.org Free e-books

Beginning Groovy and Grails (Apress) Getting started with Grails (InfoQ)

refcardz.com cheat sheets

ibm.com Mastering Grails, Practically Groovy

Thanks