Вы находитесь на странице: 1из 21

Groovy & Grails Tutorial

Developer Tutorials
ver 1.0
rubengerad@gmail.com

Groovy & Grails Tutorial

Topics

Groovy Language

GroovyBeans

Closures

GString

Collections

Ranges

Categories

Builders

MetaProgramming
Grails Framework

MVC Define Model

MVC Define Controller

MVC Define View

Grails Services

Brainboost Application Model

Groovy & Grails Tutorial

GROOVY Language

Pure Object Oriented language built on top of Java


Framework supporting all existing constructs, such as
modularity, classes & interfaces, inheritance,
polymorphism.
Unlike Java, all primitives (byte, int, short, float..) are
autoboxed into classes by the compiler thereby
promoting additional features
int x = 10
String y = 10.toString()
y == x (compares object values)

Liberalizes constructs, need not provide semicolon at the


end of each line, but need to add only if additional
statements are clubbed into the single line.
Imports java.lang, java.util, java.io, java.net,
java.math.BigDecimal, java.math.BigInteger, groovy.lang,
groovy.util, by default
Native support for lists, maps, regular expressions

Groovy & Grails Tutorial

GROOVY Language
Switch statement supports all types.

Strings can embed expressions which are dynamically


rendered.

Safe navigation improved by checking null values using


car?.engine?.start()
?

Checks if car is null before invoking engine object.


Checks if engine object is null before calling start method

Dynamic typing allows omission of types in methods,


variables and fields

Last
def
x evaluated expression is the return values, does not
require
return statement
def
doSomething(param1){
x = param1}

def orDosomethingelse = { param1, param2


x = param1 + param2;
}//returns x by default

Groovy & Grails Tutorial

Groovy Language

Added new helper classes to augment Java coding styles.

def x = [a, c, b, d]
x.sort()
x.reverse()
def num = 2
num.toString();
stringDate = "2015-01-01"
dateArray = stringDate.tokenize("-")
year = dateArray[0].toInteger()
year = year + 1
newDate = year + "-" + dateArray[1] + "-" + dateArray[2]

Groovy & Grails Tutorial

GStrings

GStrings are essentially map objects and not Strings.


Groovy supports both and for strings.
Groovy supports multi-line strings with three quotes
It is possible to avoid additional backslash for escape
characters by providing the string within /
Use the $ symbol for variables and ${} when addressing
methods

def mystring = hello my world

def mystrings = hello this is


a multi line comment
def stringPath = /c:\mydrive\mypath\myfile.txt/
def stringworld = Just for the record $mystring
def int xint = 10
def complexString = printing integer : ${xint.toString()}
3.times{ print $mystring }
xint.times{ print $mystring }

Groovy & Grails Tutorial

Groovy Beans

Groovy beans implicitly

Declare all fields/member variables private

Adds public getter/setter methods for each member


variable

If private fields are declared then no setters are


created
Class MyBean{
Integer Id
String Name
Float Salary
static void main(args) {
def customer = new Customer(id:1, name:"Gromit", dob:new Date())
println("Hello ${customer.name}")
}
}

Groovy & Grails Tutorial

Closures

Closures are code blocks or method pointers.


Groovy does not support inner classes but closures help
to create first class functions that can be passed around
as variables.
Closures use it similar to represent iterative object as
this is used to refer enclosing class.

def addictive = { it + it } //implicitly takes first argument as it


def x = addictive(10) // = 20
//can declare as visible param which is same as #1
def addictive = { argx ->
argx + argx
}
//defining 2 or more params
def addictive = { argx, argy ->
argx + argy
}
def y = addictive(argx, argy)

Groovy & Grails Tutorial

Collection
Groovy provides native support for List, Set, Map and
array.

Lists
can= be
def
mylist
[ 1,evaluated
2, 3, 4 ] as Boolean to check if it is empty

mylist.size (or) mylist.size() // = 4


mylist instanceof ArrayList // true
def xval = mylist[2] (or) mylist.get(2) (or) mylist.getAt(2) //= 3m
mylist[2] = 8 (or) mylist.set(2, 8)
newlist = [1,2,8,4] (or) newlist = mylist.clone()
mylist == [1,2,8,4] (or) mylist.contains(newlist)
mylist[-2] // == 8 counts backwards
newlist << 9 newlist.plus(10).plust([11,12]) //= 1,2,8,4,9,10,11,12
newlist.each{println Values $it} //=1,2,8,4,9,10,11,12
mylist.find{it >10} /*=11*/ mylist.findAll{it >10} // =11,12
mylist.join(-) // 1-2-8-4-9-10-11-12
mylist.contains(2) (or) mylist.containsAll([2,10]) // =true
Mylist.sort() //= [1,2,3,4,8,9,10,11,12]
Set x = mylist + newlist //1,2,8,4,9,10,11,12 (non repeating set)

Groovy & Grails Tutorial

Collection

Maps can be used to store key value pairs. The key


element can be accessed as from an array.

def maps = [:] //declaration


maps = [1:a, 2:b, 3:c]
Map.get(1) (or) map[1] //=a
Map.put(1, x) (or) map[1]=x

Groovy & Grails Tutorial

Categories
Categories are more like friend functions which can be
used inside the context of other classes with loose
coupling.

To create a category class you need to declare all


methods static, however in the later version you may use
@Category annotation and such classes are not required
@Category
class
BubbleSort{
to declare
their methods static.

sortIt(mylist){//implementation}

}
@Category
class LinearSort{
sortIt(mylist){//implementation}
}
class Sorter{
def sortIt(type,list){
switch(type){
case BUBBLE:
use(BubbleSort){ list.sortIt();} break
case LINEAR: use(LinearSort){ list.sortIt();} break
default: use(BubbleSort){ list.sortIt();}
}

Groovy & Grails Tutorial

Builders

Groovy has JsonBuilder or MarkupBuilder to create data


or text structures.
Nodes in builder are methods which we can access from
closures to simplify the creation of complex and nested
types.
@Builder(builderMethodName = start, buildMethodName = 'create')
class Message {
String from, to, subject, body
}
def message = Message.start()
.from(abc@attinadsoftware.com)
.to(xyz@attinadsoftware.com
.body(Attinad rocks !')
.create()

Groovy & Grails Tutorial

Meta programming

Meta programming is the writing of computer programs


with the ability to treat programs as their data. It means
that a program could be designed to read, generate,
analyse and/or transform other programs, and even
modify
itself for
while
running
println
"Package
String
class + String.package
println "All methods of Object class:"
Object.methods.each { println " " + it }
println "All fields of Integer class:"
Integer.fields.each { println " " + it }
class Car{
def drive ={ log.info driving }
}
class Reflect{
def invoke( vehicle, method){
vehicle.$method()
}
public static main(args){
def ref = new Reflect();
ref.invoke(new Car, drive);
}
}

Groovy & Grails Tutorial

Grails Framework
Grails is a full stack framework and attempts to solve as
many pieces of the web development puzzle through the
core technology and it's associated plug-ins. Included out
the box are things like:

An easy to use Object Relational Mapping (ORM) layer


built on Hibernate
An expressive view technology called Groovy Server Pages
(GSP)
A controller layer built on Spring MVC
A command line scripting environment built on the
Groovy-powered Gant
An embedded Tomcat container which is configured for on
the fly reloading
Dependency injection with the inbuilt Spring container
Support for internationalization (i18n) built on Spring's
core MessageSource concept
A transactional service layer built on Spring's transaction

Groovy & Grails Tutorial

Grails Application

grails create-app Brainboost


cd Brainboost

A Grails application is
generated not created.
The basic structure is
generated on providing
the create-app command.
It provides a ready to use
application development
environment
configured
for the developers.
Use a modern IDE like
netbeans and create a
groovy
project
which
executes
the
same
command internally to
build the empty project
structure.

Groovy & Grails Tutorial

Grails Application

grails create-app Brainboost


cd Brainboost

A Grails application is
generated not created.
The basic structure is
generated on providing
the create-app command.
It provides a ready to use
application development
environment
configured
for the developers.
Use a modern IDE like
netbeans and create a
groovy
project
which
executes
the
same
command internally to
build the empty project
structure.

Groovy & Grails Tutorial

Grails MVC Application Define model


//Command line method
grails create-domain-class
com.attinad.tutorials.model.Employee
//define the model fields & constraints
package com.attinad.tutorials.model
class Employee {
String firstName
String lastName
Integer age
String userName
static hasMany [skills:SkillSet]
static constraints = {
firstName blank: false
lastName blank: false
age min:18, max:60
userName size:515
}
}
class SkillSet{
String framework
Integer experience
}

The first step in creating a


good project is to begin
with the proper domain
model.
The domain model can be
created by issuing the
command create-domainclass or by using an IDE
to create a new Groovy
Domain Class object.
All fields are implicitly
private with public getters
and setters
We add constraints which
help define the various
limits.
Finally we add hasMany,
hasOne and belongsTo

Groovy & Grails Tutorial

Grails MVC Application Define controller


//Command line method
grails create-controller
com.attinad.tutorials.controller.Employee
//define the model fields & constraints
package com.attinad.tutorials.controller
import com.attinad.tutorials.model
class EmployeeController {
static scaffold = true
}
Class EmployeeController{
def employeeService //dependency inject
def index() {
render Employee Controller
}
def show ={
Employee emp = new
Employee( firsName:John,
lastName:Doe, age:21, username:john.d)
[emp:emp]
}
}

The controller is the main


part of the application
responsible for rendering
the content.
Grails provide a feature
called scaffolding, which
generates a basic CRUD
application framework.
Dynamic scaffolding is
created at runtime by
setting a blank controller
with
parameter
scaffolding=true
Static
scaffolding
is
generating
the
CRUD
application
using
generate-controller
command.

Groovy & Grails Tutorial

Grails Services
//Command line method
grails create-service
com.attinad.tutorials.service.Employee
package com.attinad.tutorials.service

import grails.transaction.Transactional
@Transactional
class EmployeeService {
static scope = session

def serviceMethod() {
}

The service classes are


created using the createservice command
The services must be
used to hold session
related information and
business logic.
The services layer can be
singleton have only one
instance across all users.
To
manage
session
scoped
services
all
controllers accessing the
service must be declared
prototype.
Further logic and patterns
can be defined as groovy
classes,
but
do
not
support
dependency

Sample Architecture Model

Educational App Model

Happy Grailing !

Вам также может понравиться