SlideShare a Scribd company logo
1 of 31
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

More Related Content

What's hot

Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
Raimonds Simanovskis
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 

What's hot (20)

Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
 
Old code doesn't stink
Old code doesn't stinkOld code doesn't stink
Old code doesn't stink
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
 
Crafting Quality PHP Applications (ConFoo YVR 2017)
Crafting Quality PHP Applications (ConFoo YVR 2017)Crafting Quality PHP Applications (ConFoo YVR 2017)
Crafting Quality PHP Applications (ConFoo YVR 2017)
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 
Enterprise JavaScript ... what the heck?
Enterprise JavaScript ... what the heck?Enterprise JavaScript ... what the heck?
Enterprise JavaScript ... what the heck?
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
InterConnect: Java, Node.js and Swift - Which, Why and When
InterConnect: Java, Node.js and Swift - Which, Why and WhenInterConnect: Java, Node.js and Swift - Which, Why and When
InterConnect: Java, Node.js and Swift - Which, Why and When
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swift
 
A Practitioner’s guide to Hardened JavaScript
A Practitioner’s guide to Hardened JavaScriptA Practitioner’s guide to Hardened JavaScript
A Practitioner’s guide to Hardened JavaScript
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.js
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypass
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part I
 
遇見 Ruby on Rails
遇見 Ruby on Rails遇見 Ruby on Rails
遇見 Ruby on Rails
 

Similar to Groovy on Grails by Ziya Askerov

JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 

Similar to Groovy on Grails by Ziya Askerov (20)

Jet presentation
Jet presentationJet presentation
Jet presentation
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Grails 101
Grails 101Grails 101
Grails 101
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2
 
Works with persistent graphs using OrientDB
Works with persistent graphs using OrientDB Works with persistent graphs using OrientDB
Works with persistent graphs using OrientDB
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
 
Groovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsGroovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applications
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 

Recently uploaded

Recently uploaded (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Groovy on Grails by Ziya Askerov

  • 4. 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
  • 5. 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
  • 6.
  • 7. 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
  • 9. 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
  • 10. 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
  • 11. 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 
  • 12. 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
  • 14. 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()
  • 15. 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 }
  • 16. 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 }
  • 17. 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])
  • 18. 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() -
  • 19. 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
  • 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 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
  • 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>
  • 24. PROJECT STRUCTURE & CONFIGURATION BootStrap.groovy BuildConfig.groovy Config.groovy DataSource.groovy UrlMappings.groovy class BootStrap { def init = { servletContext -> } def destroy = { } }
  • 26. 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
  • 27. 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
  • 28. 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' } }
  • 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
  • 30.
  • 31. -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