Ziya Askerov
JAVA WEB TECHNOLOGIES
WHAT IS FRAMEWORK ?
DYNAMIC AND STATIC LANGUAGES
-Difference between dynamic and static programming languages
checking types before operations to prevent errors
-Static Type Checking & Dinamic Type Checking
-Runtime checking and Compile time checking
-Static Languages Java, C, C++ ,C#
-Dynamic Languages Groovy, Javascript, Python, Ruby
WHAT IS GROOVY
Is an agile and dynamic language for the Java Virtual Machine
Makes modern programming features available to Java developers
with almost-zero learning curve
Increases developer productivity
Compiles straight to Java bytecode so you can use it anywhere you can
use Java
Seamlessly integrates with all existing Java classes and libraries
WHAT IS GRAILS
-Full stack MVC framework for web apps
-Exploits the awesome power of Groovy
-Leverages proven staples
Hibernate
Spring
Sitemesh
-Works on JVM
GRAILS ARCHITECTURE
WHY GRAILS
Java web development as it stands today is dramatically more complicated than it
needs to be
Most modern web frameworks in the Java space are over complicated and don't
embrace the Don't Repeat Yourself (DRY) principles
- 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 transactional service layer built on Spring's transaction abstraction
WHY GRAILS
Based on battle tested and proven Java frameworks (Spring, Hibernate,
SiteMesh, Quartz, etc)
Based on Groovy language
GORM(Grails Object Relational Mapping)
Doesn’t stop you from using the power of underlying frameworks
Easy to set-up and get started
Minimal server restart required while development
Convention over Configuration / No painful XML configuration & XML Management
Tag Lib Authoring mechanism
Tons of available plugins
CONVENTION OVER CONFIGURATION
-Some frameworks need multiple configuration files, each with many settings
-A large number of configuration files with lots of parameters is often difficult to maintain
-Convention over Configuration (Coding by convention) is a software design paradigm
which seeks to decrease the number of decisions that developers need to make
-Gaining simplicity, but not necessarily losing flexibility
-Like a software consulting 
GRAILS AND SECURITY
Web security problems typically occur due to developer naivety or mistakes, and there is a
little Grails can do to avoid common mistakes and make writing secure applications easier
to write.
-All standard database access via GORM domain objects is automatically SQL escaped to
prevent SQL injection attacks
-Grails link creating tags (link, form, createLink, createLinkTo and others) all use appropriate
escaping mechanisms to prevent code injection
-Grails provides codecs to let you trivially escape data when rendered as HTML, JavaScript
and URLs to prevent injection attacks here.
-XSRF attacks prevention
-Cross Site Scripting (XSS) Prevention
GRAILS AND MVC
GRAILS Object Relational Mapping (GORM)
GORM is Grails' object relational mapping (ORM) implementation.
Under the hood it uses Hibernate
BASIC CRUD
class Person {
String name
Integer age
Date lastVisit
}
def p = new Person(name: "Fred", age: 40, lastVisit: new Date())
p.save()
def p = Person.get(1)
p.name = "Bob“
p.save()
def p = Person.get(1)
p.delete()
constructor
def results = Person.findAll()
One-to-many
Many-to-many
Association in GORM
One-to-one
One-to-one
class Face {
Nose nose
}
class Nose {
}
class Face {
Nose nose
}
class Nose {
static belongsTo = [face:Face]
}
class Author {
static hasMany = [books: Book]
String name
}
class Book {
static belongsTo = [author: Author]
String title
}
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
String title
}
class Author {
static hasMany = [books:Book]
String name
}
Eager and Lazy Fetching
Associations in GORM are by default lazy
class Airport {
String name
static hasMany = [flights: Flight]
}
class Flight {
String number Location destination
static belongsTo = [airport: Airport]
}
class Location {
String city
String country
}
Given the above domain classes and the following code:
def airport = Airport.findByName("Gatwick")
for (flight in airport.flights) {
println flight.destination.city
}
Pessimistic and Optimistic Locking
-By default gorm classes are configured for optimistic locking.
-Optimistic locking is a feature of hibernate which involves storing a version value in a special version
Column in the database that is incremented after each update.
-Pessimistic locking is equivalent to doing a sql "select * for update" statement and locking a row in the database
Pessimistic Locking
Optimistic Locking
def airport = Airport.get(10)
try {
airport.name = "Heathrow" airport.save(flush: true)
} catch (org.springframework.dao.OptimisticLockingFailureException e)
{
// deal with exception
}
def airport = Airport.get(10)
airport.lock()
// lock for update airport.name = "Heathrow"
airport.save()
def airport = Airport.lock(10) // lock for update
airport.name = "Heathrow"
airport.save()
def airport = Airport.findByName("Heathrow", [lock: true])
Querying with GORM
GORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query
language HQL. Depending on the complexity of the query you have the following options in order of flexibility and power:
-Dynamic Finders
-Where Queries
-Criteria Queries
-Hibernate Query Language (HQL)
Dynamic Finders
Pagination and Sorting
class Book {
String title
Date releaseDate
Author author
}
class Author {
String name
}
def book = Book.findByTitle("The Stand")
book = Book.findByTitleLike("Harry Pot%")
book = Book.findByReleaseDateBetween(firstDate, secondDate)
book = Book.findByReleaseDateGreaterThan(someDate)
book = Book.findByTitleLikeOrReleaseDateLessThan("%Something%", someDa
def books = Book.findAllByTitleLike("Harry Pot%", [max: 3, offset: 2, sort:
"title", order: "desc"])
Boolean logic (AND/OR)
def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan( "%Java%", new Date() - 3
def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan( "%Java%", new Date() -
The possible comparators include:
•InList - In the list of given values
•LessThan - less than a given value
•LessThanEquals - less than or equal a give value
•GreaterThan - greater than a given value
•GreaterThanEquals - greater than or equal a given value
•Like - Equivalent to a SQL like expression
•Ilike - Similar to a Like, except case insensitive
•NotEqual - Negates equality
•InRange - Between the from and to values of a Groovy Range
•Rlike - Performs a Regexp LIKE in MySQL or Oracle otherwise falls back to Like
•Between - Between two values (requires two arguments)
•IsNotNull - Not a null value (doesn't take an argument)
•IsNull - Is a null value (doesn't take an argument)
Dynamic Finders
Where Queries
Criteria
def query = Person.where {
firstName == "Bart"
}
Person bart = query.find()
def query = Person.where {
(lastName != "Simpson" && firstName != "Fred")|| (firstName == "Bart" && age > 9)
}
def results = query.list(sort:"firstName")
def c = Account.createCriteria()
def results = c {
between("balance", 500, 1000)
eq("branch", "London") or {
like("holderFirstName", "Fred%")
like("holderFirstName", "Barney%")
}
maxResults(10)
order("holderLastName", "desc")
}
Querying with GORM
Validation on the GRAILS
Validation on the Client attributes
bindable
blank
creditCard
email
inList
matches
max
maxSize
min
minSize
notEqual
nullable
range
scale
size
unique
url
validator
widget
def user = new User(params)
if (user.hasErrors()) {
if (user.errors.hasFieldErrors("login")) {
println user.errors.getFieldError("login").rejectedValue
}
}
class User {
String login
String password
String email
Integer age
static constraints = {
}
}
class User { ...
static constraints = {
login size: 5..15, blank: false, unique: true
password size: 5..15, blank: false
email email: true, blank: false
age min: 18
}
} All Constraints
<g:hasErrors bean="${user}">
<ul>
<g:eachError var="err" bean="${user}">
<li>${err}</li>
</g:eachError>
</ul>
</g:hasErrors>
Constraints
Validation of Domain Class
GRAILS TAGS
<g:form name="myForm" action="myaction" id="1">...</g:form>
<g:select name="user.company.id" from="${Company.list()}"
value="${user?.company.id}" optionKey="id" />
<g:include action="list" params="[sort: 'title', order: 'asc', author:
currentBook.author]" />
<g:paginate next="Forward" prev="Back" maxsteps="0"
controller="book" action="list" total="${bookCount}" />
<g:each in="${books}">
<p>Title: ${it.title}</p>
<p>Author: ${it.author}</p>
</g:each>
<g:if test="${name == 'fred'}">
Hello Fred!
</g:if>
<g:elseif test="${name == 'bob'}">
Hello bob!
</g:elseif>
actionSubmit
actionSubmitImage
applyLayout
checkBox
collect
cookie
country
countrySelect
createLink
createLinkTo
currencySelect
datePicker
each
eachError
else
elseif
external
field
fieldValue
findAll
form
formatBoolean
formatDate
formatNumber
grep
hasErrors
header
hiddenField
uploadForm
while
if
img
include
isAvailable
isNotAvailable
javascript
join
layoutBody
layoutHead
layoutTitle
link
localeSelect
message
meta
pageProperty
paginate
passwordField
radio
radioGroup
render
renderErrors
resource
select
set
sortableColumn
submitButton
textArea
textField
timeZoneSelect
unless
GRAILS TAGS
PROJECT STRUCTURE & CONFIGURATION
BootStrap.groovy
BuildConfig.groovy
Config.groovy
DataSource.groovy
UrlMappings.groovy
class BootStrap {
def init = { servletContext ->
}
def destroy = {
}
}
DataSource.groovy
Plugins
Grails is first and foremost a web application framework, but it is also a platform
-Spring Security Core Plugin
-Spring Security UI Plugin
-Quartz Plugin
-Quartz Monitor Plugin
-Mail Plugin
-XSS sanitizer Plugin
class User {
transient springSecurityService
String username
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static transients = ['springSecurityService']
static constraints = {
username blank: false, unique: true password blank: false
}
static mapping = {
password column: '`password`‘
}
Set<Role> getAuthorities() {
UserRole.findAllByUser(this).collect { it.role }
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword() }
}
protected void encodePassword() {
password = springSecurityService?.passwordEncoder ?
springSecurityService.encodePassword(password) : password
}
}
Authentication & Authorization with Spring Security
Defining Secured Annotations with Spring Security
package com.mycompany.myapp
import grails.plugin.springsecurity.annotation.Secured
class SecureAnnotatedController {
@Secured(['ROLE_ADMIN'])
def index() {
render 'you have ROLE_ADMIN'
}
@Secured(['ROLE_ADMIN', 'ROLE_SUPERUSER'])
def adminEither() {
render 'you have ROLE_ADMIN or SUPERUSER'
}
def anybody() {
render 'anyone can see this' }
}
package com.mycompany.myapp
import grails.plugin.springsecurity.annotation.Secur
@Secured(['ROLE_ADMIN'])
class SecureClassAnnotatedController {
def index() {
render 'index: you have ROLE_ADMIN' }
def otherAction() {
render 'otherAction: you have ROLE_ADMIN‘
}
@Secured(['ROLE_SUPERUSER'])
def super() {
render 'super: you have ROLE_SUPERUSER' }
}
<sec:ifLoggedIn> Welcome Back! </sec:ifLoggedIn>
<sec:ifNotLoggedIn>
<g:link controller='login' action='auth'>Login</g:link>
</sec:ifNotLoggedIn>
<sec:ifAllGranted roles="ROLE_ADMIN,ROLE_SUPERVISOR">secure stuff here</sec:ifAllGrante
<sec:ifAnyGranted roles="ROLE_ADMIN,ROLE_SUPERVISOR">secure stuff here</sec:ifAnyGrante
<sec:ifNotGranted roles="ROLE_USER">non-user stuff here</sec:ifNotGranted>
Spring Security Tag Lib
authoritiesToRoles()
getPrincipalAuthorities()
parseAuthoritiesString()
ifAllGranted()
ifNotGranted()
ifAnyGranted()
getSecurityConfig()
loadSecondaryConfig()
reloadSecurityConfig()
isAjax()
Spring Security Utils
-Based on battle tested and proven Java frameworks (Spring, Hibernate, SiteMesh, Quartz, etc)
-Based on Groovy language
-A very responsive and supporting community and mailing list
-GORM
-Doesn’t stop you from using the power of underlying frameworks
-Easy to set-up and get started
-Minimal server restart required while development
-Standard Project template and artifacts
-DRY / Convention over Configuration / No painful XML configuration & XML Management
-REST support built-in
-Tag Lib Authoring mechanism
-Integrates easily with already written Java code
-Tons of available plugins
-Hundreds of small things that make development fun with Groovy and Grails
II Launch Your Startup With Groovy & Grails

Grails

  • 1.
  • 2.
  • 3.
  • 4.
    DYNAMIC AND STATICLANGUAGES -Difference between dynamic and static programming languages checking types before operations to prevent errors -Static Type Checking & Dinamic Type Checking -Runtime checking and Compile time checking -Static Languages Java, C, C++ ,C# -Dynamic Languages Groovy, Javascript, Python, Ruby
  • 5.
    WHAT IS GROOVY Isan agile and dynamic language for the Java Virtual Machine Makes modern programming features available to Java developers with almost-zero learning curve Increases developer productivity Compiles straight to Java bytecode so you can use it anywhere you can use Java Seamlessly integrates with all existing Java classes and libraries
  • 7.
    WHAT IS GRAILS -Fullstack MVC framework for web apps -Exploits the awesome power of Groovy -Leverages proven staples Hibernate Spring Sitemesh -Works on JVM
  • 8.
  • 9.
    WHY GRAILS Java webdevelopment as it stands today is dramatically more complicated than it needs to be Most modern web frameworks in the Java space are over complicated and don't embrace the Don't Repeat Yourself (DRY) principles - 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 transactional service layer built on Spring's transaction abstraction
  • 10.
    WHY GRAILS Based onbattle tested and proven Java frameworks (Spring, Hibernate, SiteMesh, Quartz, etc) Based on Groovy language GORM(Grails Object Relational Mapping) Doesn’t stop you from using the power of underlying frameworks Easy to set-up and get started Minimal server restart required while development Convention over Configuration / No painful XML configuration & XML Management Tag Lib Authoring mechanism Tons of available plugins
  • 11.
    CONVENTION OVER CONFIGURATION -Someframeworks need multiple configuration files, each with many settings -A large number of configuration files with lots of parameters is often difficult to maintain -Convention over Configuration (Coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make -Gaining simplicity, but not necessarily losing flexibility -Like a software consulting 
  • 12.
    GRAILS AND SECURITY Websecurity problems typically occur due to developer naivety or mistakes, and there is a little Grails can do to avoid common mistakes and make writing secure applications easier to write. -All standard database access via GORM domain objects is automatically SQL escaped to prevent SQL injection attacks -Grails link creating tags (link, form, createLink, createLinkTo and others) all use appropriate escaping mechanisms to prevent code injection -Grails provides codecs to let you trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here. -XSRF attacks prevention -Cross Site Scripting (XSS) Prevention
  • 13.
  • 14.
    GRAILS Object RelationalMapping (GORM) GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate BASIC CRUD class Person { String name Integer age Date lastVisit } def p = new Person(name: "Fred", age: 40, lastVisit: new Date()) p.save() def p = Person.get(1) p.name = "Bob“ p.save() def p = Person.get(1) p.delete() constructor def results = Person.findAll()
  • 15.
    One-to-many Many-to-many Association in GORM One-to-one One-to-one classFace { Nose nose } class Nose { } class Face { Nose nose } class Nose { static belongsTo = [face:Face] } class Author { static hasMany = [books: Book] String name } class Book { static belongsTo = [author: Author] String title } class Book { static belongsTo = Author static hasMany = [authors:Author] String title } class Author { static hasMany = [books:Book] String name }
  • 16.
    Eager and LazyFetching Associations in GORM are by default lazy class Airport { String name static hasMany = [flights: Flight] } class Flight { String number Location destination static belongsTo = [airport: Airport] } class Location { String city String country } Given the above domain classes and the following code: def airport = Airport.findByName("Gatwick") for (flight in airport.flights) { println flight.destination.city }
  • 17.
    Pessimistic and OptimisticLocking -By default gorm classes are configured for optimistic locking. -Optimistic locking is a feature of hibernate which involves storing a version value in a special version Column in the database that is incremented after each update. -Pessimistic locking is equivalent to doing a sql "select * for update" statement and locking a row in the database Pessimistic Locking Optimistic Locking def airport = Airport.get(10) try { airport.name = "Heathrow" airport.save(flush: true) } catch (org.springframework.dao.OptimisticLockingFailureException e) { // deal with exception } def airport = Airport.get(10) airport.lock() // lock for update airport.name = "Heathrow" airport.save() def airport = Airport.lock(10) // lock for update airport.name = "Heathrow" airport.save() def airport = Airport.findByName("Heathrow", [lock: true])
  • 18.
    Querying with GORM GORMsupports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query language HQL. Depending on the complexity of the query you have the following options in order of flexibility and power: -Dynamic Finders -Where Queries -Criteria Queries -Hibernate Query Language (HQL) Dynamic Finders Pagination and Sorting class Book { String title Date releaseDate Author author } class Author { String name } def book = Book.findByTitle("The Stand") book = Book.findByTitleLike("Harry Pot%") book = Book.findByReleaseDateBetween(firstDate, secondDate) book = Book.findByReleaseDateGreaterThan(someDate) book = Book.findByTitleLikeOrReleaseDateLessThan("%Something%", someDa def books = Book.findAllByTitleLike("Harry Pot%", [max: 3, offset: 2, sort: "title", order: "desc"]) Boolean logic (AND/OR) def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan( "%Java%", new Date() - 3 def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan( "%Java%", new Date() -
  • 19.
    The possible comparatorsinclude: •InList - In the list of given values •LessThan - less than a given value •LessThanEquals - less than or equal a give value •GreaterThan - greater than a given value •GreaterThanEquals - greater than or equal a given value •Like - Equivalent to a SQL like expression •Ilike - Similar to a Like, except case insensitive •NotEqual - Negates equality •InRange - Between the from and to values of a Groovy Range •Rlike - Performs a Regexp LIKE in MySQL or Oracle otherwise falls back to Like •Between - Between two values (requires two arguments) •IsNotNull - Not a null value (doesn't take an argument) •IsNull - Is a null value (doesn't take an argument) Dynamic Finders
  • 20.
    Where Queries Criteria def query= Person.where { firstName == "Bart" } Person bart = query.find() def query = Person.where { (lastName != "Simpson" && firstName != "Fred")|| (firstName == "Bart" && age > 9) } def results = query.list(sort:"firstName") def c = Account.createCriteria() def results = c { between("balance", 500, 1000) eq("branch", "London") or { like("holderFirstName", "Fred%") like("holderFirstName", "Barney%") } maxResults(10) order("holderLastName", "desc") } Querying with GORM
  • 21.
    Validation on theGRAILS Validation on the Client attributes bindable blank creditCard email inList matches max maxSize min minSize notEqual nullable range scale size unique url validator widget def user = new User(params) if (user.hasErrors()) { if (user.errors.hasFieldErrors("login")) { println user.errors.getFieldError("login").rejectedValue } } class User { String login String password String email Integer age static constraints = { } } class User { ... static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } } All Constraints <g:hasErrors bean="${user}"> <ul> <g:eachError var="err" bean="${user}"> <li>${err}</li> </g:eachError> </ul> </g:hasErrors> Constraints Validation of Domain Class
  • 22.
    GRAILS TAGS <g:form name="myForm"action="myaction" id="1">...</g:form> <g:select name="user.company.id" from="${Company.list()}" value="${user?.company.id}" optionKey="id" /> <g:include action="list" params="[sort: 'title', order: 'asc', author: currentBook.author]" /> <g:paginate next="Forward" prev="Back" maxsteps="0" controller="book" action="list" total="${bookCount}" /> <g:each in="${books}"> <p>Title: ${it.title}</p> <p>Author: ${it.author}</p> </g:each> <g:if test="${name == 'fred'}"> Hello Fred! </g:if> <g:elseif test="${name == 'bob'}"> Hello bob! </g:elseif>
  • 23.
  • 24.
    PROJECT STRUCTURE &CONFIGURATION BootStrap.groovy BuildConfig.groovy Config.groovy DataSource.groovy UrlMappings.groovy class BootStrap { def init = { servletContext -> } def destroy = { } }
  • 25.
  • 26.
    Plugins Grails is firstand foremost a web application framework, but it is also a platform -Spring Security Core Plugin -Spring Security UI Plugin -Quartz Plugin -Quartz Monitor Plugin -Mail Plugin -XSS sanitizer Plugin
  • 27.
    class User { transientspringSecurityService String username String password boolean enabled = true boolean accountExpired boolean accountLocked boolean passwordExpired static transients = ['springSecurityService'] static constraints = { username blank: false, unique: true password blank: false } static mapping = { password column: '`password`‘ } Set<Role> getAuthorities() { UserRole.findAllByUser(this).collect { it.role } } def beforeInsert() { encodePassword() } def beforeUpdate() { if (isDirty('password')) { encodePassword() } } protected void encodePassword() { password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password } } Authentication & Authorization with Spring Security
  • 28.
    Defining Secured Annotationswith Spring Security package com.mycompany.myapp import grails.plugin.springsecurity.annotation.Secured class SecureAnnotatedController { @Secured(['ROLE_ADMIN']) def index() { render 'you have ROLE_ADMIN' } @Secured(['ROLE_ADMIN', 'ROLE_SUPERUSER']) def adminEither() { render 'you have ROLE_ADMIN or SUPERUSER' } def anybody() { render 'anyone can see this' } } package com.mycompany.myapp import grails.plugin.springsecurity.annotation.Secur @Secured(['ROLE_ADMIN']) class SecureClassAnnotatedController { def index() { render 'index: you have ROLE_ADMIN' } def otherAction() { render 'otherAction: you have ROLE_ADMIN‘ } @Secured(['ROLE_SUPERUSER']) def super() { render 'super: you have ROLE_SUPERUSER' } }
  • 29.
    <sec:ifLoggedIn> Welcome Back!</sec:ifLoggedIn> <sec:ifNotLoggedIn> <g:link controller='login' action='auth'>Login</g:link> </sec:ifNotLoggedIn> <sec:ifAllGranted roles="ROLE_ADMIN,ROLE_SUPERVISOR">secure stuff here</sec:ifAllGrante <sec:ifAnyGranted roles="ROLE_ADMIN,ROLE_SUPERVISOR">secure stuff here</sec:ifAnyGrante <sec:ifNotGranted roles="ROLE_USER">non-user stuff here</sec:ifNotGranted> Spring Security Tag Lib authoritiesToRoles() getPrincipalAuthorities() parseAuthoritiesString() ifAllGranted() ifNotGranted() ifAnyGranted() getSecurityConfig() loadSecondaryConfig() reloadSecurityConfig() isAjax() Spring Security Utils
  • 31.
    -Based on battletested and proven Java frameworks (Spring, Hibernate, SiteMesh, Quartz, etc) -Based on Groovy language -A very responsive and supporting community and mailing list -GORM -Doesn’t stop you from using the power of underlying frameworks -Easy to set-up and get started -Minimal server restart required while development -Standard Project template and artifacts -DRY / Convention over Configuration / No painful XML configuration & XML Management -REST support built-in -Tag Lib Authoring mechanism -Integrates easily with already written Java code -Tons of available plugins -Hundreds of small things that make development fun with Groovy and Grails II Launch Your Startup With Groovy & Grails