SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Grails – The search is over
       Aécio Costa
      Felipe Coutinho
Grails – The search is over

Groovy
   Características
   Groovy x Java
   Regra dos 80/20


Grails
   Cenário Atual do Desenvolvimento Web
   Características
   Arquitetura
   Demo
Grails – The search is over

Groovy - Características
  Inspirada no Python, Ruby...;

  Linguagem Dinâmica;

  Plataforma Java;

  Especificação do JCP (JSR 241);

  Copy/Paste Compatibilty.
Grails – The search is over

O que Groovy tem de diferente de Java?
  Tipagem dinâmica;

  Recurso: attribute accessor;

  Closure;

  Métodos Dinâmicos;

  e mais...
Grails – The search is over

Tipagem dinâmica

def name = “João”


def names = [“João”, “José”, “Geraldo”]
Grails – The search is over

Atribute accessor
class User{

    String nome
    Integer idade

}

def user = new User(name:”João”, age: 23)

user.nome = “Pedro”
Grails – The search is over

Closure
def name = “Paulo”

def printName = {println “Hello, ${name}”}

printName()


def listNames = [“Gabriela”, “Maria”]

def sayHello = {println it}

listNames.each(sayHello)
Grails – The search is over

Métodos Dinâmicos

def methodName = “getYearBorn”

user.”${methodName}”()

new User().”getDayBorn”()
Grails – The search is over

Além de...
Sobre carga de operadores;

Ranges;

MetaPrograming;

e etc...
Grails – The search is over

Groovy veio acabar com a Regra dos 80/20
           (Princípio de Pareto)
Grails – The search is over
import java.util.ArrayList;
import java.util.List;

class Seletor {

   private List selectBooksNameLessThan(List bookNames, int length) {
      List resultado = new ArrayList();
      for (int i = 0; i < bookNames.size(); i++) {
            String candidate = (String) bookNames.get(i);
            if (candidate.length() < length) {
                  resultado.add(candidate);
            }
      }
      return resultado;
   }

   public static void main(String[] args) {
     List books = new ArrayList();
     books.add("Harry Potter");
     books.add("A Vila");
     books.add(“O Exorcista");

       Seletor s = new Seletor();
       List selected = s.selectBooksNameLessThan(books, 10);
       System.out.println("Total Selecionados: " + selecionados.size());

       for (int i = 0; i < selected.size(); i++) {
             String sel = (String) selecionados.get(i);
             System.out.println(sel);
       }

   }
Grails – The search is over

O que realmente interessa no código anterior?
Grails – The search is over
import java.util.ArrayList;
import java.util.List;

class Seletor {

   private List selectBooksNameLessThan(List bookNames, int length) {
      List resultado = new ArrayList();
      for (int i = 0; i < bookNames.size(); i++) {
            String candidate = (String) bookNames.get(i);
            if (candidate.length() < length) {
                  resultado.add(candidate);
            }
      }
      return resultado;
   }

   public static void main(String[] args) {
     List books = new ArrayList();
     books.add("Harry Potter");
     books.add("A Vila");
     books.add(“O Exorcista");

       Seletor s = new Seletor();
       List selected = s.selectBooksNameLessThan(books, 10);
       System.out.println("Total Selecionados: " + selecionados.size());

       for (int i = 0; i < selected.size(); i++) {
             String sel = (String) selecionados.get(i);
             System.out.println(sel);
       }

   }
Grails – The search is over
Grails – The search is over

Closure e import implícito
Grails – The search is over
import java.util.ArrayList;
import java.util.List;

class Seletor {

   private List selectBooksNameLessThan(List bookNames, int length) {
      List resultado = new ArrayList();
      for (int i = 0; i < bookNames.size(); i++) {
            String candidate = (String) bookNames.get(i);
            if (candidate.length() < length) {
                  resultado.add(candidate);
            }
      }
      return resultado;
   }

   public static void main(String[] args) {
     List books = new ArrayList();
     books.add("Harry Potter");
     books.add("A Vila");
     books.add(“O Exorcista");

       Seletor s = new Seletor();
       List selected = s.selectBooksNameLessThan(books, 10);
       System.out.println("Total Selecionados: " + selecionados.size());

       for (int i = 0; i < selected.size(); i++) {
             String sel = (String) selecionados.get(i);
             System.out.println(sel);
       }

   }
Grails – The search is over
class Seletor {

    private List selectBooksNameLessThan(List bookNames, int length) {
       List resultado = new ArrayList();
       bookNames.each { String candidate ->
            if (candidate.length() < length) {
                  resultado.add(candidate);
            }
       }
       return resultado;
    }

    public static void main(String[] args) {
      List books = new ArrayList();
      books.add("Harry Potter");
      books.add("A Vila");
      books.add(“O Exorcista");

        Seletor s = new Seletor();
        List selected = s.selectBooksNameLessThan(books, 10);
        System.out.println("Total Selecionados: " + selecionados.size());

        selected.each { String sel ->
            System.out.println(sel);
        }

    }
}
Grails – The search is over

Closure e import implícito
Declaração e Assinatura de Métodos
Grails – The search is over
class Seletor {

    private List selectBooksNameLessThan(List bookNames, int length) {
       List resultado = new ArrayList();
       bookNames.each { String candidate ->
            if (candidate.length() < length) {
                  resultado.add(candidate);
            }
       }
       return resultado;
    }

    public static void main(String[] args) {
      List books = new ArrayList();
      books.add("Harry Potter");
      books.add("A Vila");
      books.add(“O Exorcista");

        Seletor s = new Seletor();
        List selected = s.selectBooksNameLessThan(books, 10);
        System.out.println("Total Selecionados: " + selecionados.size());

        selected.each { String sel ->
            System.out.println(sel);
        }

    }
}
Grails – The search is over
List selectBooksNameLessThan(List bookNames, int length) {
    List resultado = new ArrayList();
    bookNames.each { String candidate ->
         if (candidate.length() < length) {
               resultado.add(candidate);
         }
    }
    return resultado;
}

List books = new ArrayList();
books.add("Harry Potter");
books.add("A Vila");
books.add(“O Exorcista");

Seletor s = new Seletor();
List selected = s.selectBooksNameLessThan(books, 10);
System.out.println("Total Selecionados: " + selecionados.size());

selected.each { String sel ->
    System.out.println(sel);
}
Grails – The search is over

Closure e import implícito
Declaração e Assinatura de Métodos
Tipagem Estática
Grails – The search is over
List selectBooksNameLessThan(List bookNames, int length) {
    List resultado = new ArrayList();
    bookNames.each { String candidate ->
         if (candidate.length() < length) {
               resultado.add(candidate);
         }
    }
    return resultado;
}

List books = new ArrayList();
books.add("Harry Potter");
books.add("A Vila");
books.add(“O Exorcista");

Seletor s = new Seletor();
List selected = s.selectBooksNameLessThan(books, 10);
System.out.println("Total Selecionados: " + selecionados.size());

selected.each { String sel ->
    System.out.println(sel);
}
Grails – The search is over
def selectBooksNameLessThan(bookNames, length) {
    def resultado = new ArrayList();
    bookNames.each { candidate ->
         if (candidate.size() < length) {
               resultado.add(candidate);
         }
    }
    return resultado;
}

def books = new ArrayList();
books.add("Harry Potter");
books.add("A Vila");
books.add(“O Exorcista");

def selected = s.selectBooksNameLessThan(books, 10);
System.out.println("Total Selecionados: " + selecionados.size());

selected.each { sel ->
    System.out.println(sel);
}
Grails – The search is over

Closure e import implícito
Declaração e Assinatura de Métodos
Tipagem Estática
Instância simplificada de Listas
Não necessidade de “return”
“;” não obrigatório
Impressão simples
Grails – The search is over
def selectBooksNameLessThan(bookNames, length) {
    def resultado = new ArrayList();
    bookNames.each { candidate ->
         if (candidate.size() < length) {
               resultado.add(candidate);
         }
    }
    return resultado;
}

def books = new ArrayList();
books.add("Harry Potter");
books.add("A Vila");
books.add(“O Exorcista");

def selected = s.selectBooksNameLessThan(books, 10);
System.out.println("Total Selecionados: " + selecionados.size());

selected.each { sel ->
    System.out.println(sel);
}
Grails – The search is over
def selectBooksNameLessThan(bookNames, length) {
    def resultado = [];
    bookNames.each { candidate ->
         if (candidate.size) < length) {
               resultado.add(candidate)
         }
    }
    resultado
}

def books = ["Harry Potter”, "A Vila”, “O Exorcista”]
def selected = s.selectBooksNameLessThan(books, 10)
println "Total ${selecionados.size()}”

selected.each { sel ->
    println sel
}
Grails – The search is over

Closure e import implícito
Declaração e Assinatura de Métodos
Tipagem Estática
Instância simplificada de Listas
Não necessidade de “return”
“;” não obrigatório
Impressão simples
Métódos Dinâmicos
Grails – The search is over
def selectBooksNameLessThan(bookNames, length) {
    def resultado = [];
    bookNames.each { candidate ->
         if (candidate.size) < length) {
               resultado.add(candidate)
         }
    }
    resultado
}

def books = ["Harry Potter”, "A Vila”, “O Exorcista”]
def selected = s.selectBooksNameLessThan(books, 10)
println "Total ${selecionados.size()}”

selected.each { sel ->
    println sel
}
Grails – The search is over
def selectBooksNameLessThan(bookNames, length) {
    bookNames.findAll { it.size() < length }
}

def books = ["Harry Potter”, "A Vila”, “O Exorcista”]
def selected = s.selectBooksNameLessThan(books, 10)
println "Total ${selecionados.size()}”

selected.each { sel ->
    println sel
}
Grails – The search is over
def selectBooksNameLessThan(bookNames, length) {
    bookNames.findAll { it.size() < length }
}

def books = ["Harry Potter”, "A Vila”, “O Exorcista”]
def selected = s.selectBooksNameLessThan(books, 10)
println "Total ${selecionados.size()}”

selected.each { sel ->
    println sel
}
Grails – The search is over
def books = ["Harry Potter”, "A Vila”, “O Exorcista”]
def selected = books. findAll { it.size() <= 5}
println "Total ${selecionados.size()}”

selected.each { sel ->
    println sel
}
Grails – The search is over
def books = ["Harry Potter”, "A Vila”, “O Exorcista”]
def selected = books. findAll { it.size() <= 5}
println "Total ${selecionados.size()}”

selected.each { sel ->
    println sel
}




Seletor.groovy
Grails – The search is over
def books = ["Harry Potter”, "A Vila”, “O Exorcista”]
def selected = books. findAll { it.size() <= 5}
println "Total ${selecionados.size()}”

selected.each { sel ->
    println sel
                                                        Groovy é Java
}




Seletor.groovy
Grails – The search is over
Cenário Atual Web

   Persistência
   Validações
   Logs
   Visualização
   Controladores
   Controle Transacional
   Injeção de Dependências
   Ajax
   Redirecionador de URL’s
   Configuração por ambiente
   Internacionalização
Grails – The search is over
Grails – The search is over




   Welcome to
Grails – The search is over



 Framework Web de Alta produtividade para plataforma Java;
 Programação por convenção;
 MVC nativo;
 Fácil bootstrap;
 GORM;
 Scaffolding;
 Plugins;
 e tudo que você viu lá atras...
Grails – The search is over
Arquitetura do Grails
Grails – The search is over

Passos para criar a Aplicação


   $ grails create-app booklibrary

   $ grails run-app
Grails – The search is over

Classes de domínio

   $ grails create-domain-class cesar.example.Book

class Book {
   String title
   Date releaseDate
   String ISBN
}
Grails – The search is over

Scaffolding

INSERT, UPDATE, DELETE, SEARCH

$ grails generate-all cesar.example.Book
Grails – The search is over

Validations (Constraints)

DSL interna baseada no recurso builder da linguagem Groovy;

Constraints: http://grails.org/doc/latest/ref/Constraints/Usage.html

static constraints = {
        title(blank: false)
        ISBN(blank: false, unique: true)
 }
Grails – The search is over
Relacionamento

$ grails create-domain-class cesar.example.Person

class Person {
   static hasMany = [books: Book]
   String name
   String email
   String password

    static constraints = {
      name(blank: false)
      email(blank: false, email: true)
      password(blank: false, password: true)
    }
}

Na classe Book:
static belongsTo = [person: Person]
Grails – The search is over
View

.gsp

i18n
# Book
book.label=Livro
book.title.label=Titulo
book.person.label=Pessoa
book.releaseDate.label=Data de lancamento

# Person
person.label=Pessoa
person.name.label=Nome
person.password.label=Senha
Grails – The search is over
GORM

def books = Book.list(max:10, order:”name”)

def books = Book.findByName(“The Developer”)

def books = Book.findAllByPriceLessThan(10.0)

def books = Book.findAllByTitleLikeAndPriceBetween(“Harry %”,
40.0, 70.0)
Grails – The search is over
GORM

class BookController {
  def find() {
     def books = Book.findAllByTitleLike("%"+params.like+"%")
     render(view: "list", model: [bookInstanceList: books,
bookInstanceTotal: books.size()])
   }
}

<div>
  <br/>
  <g:form name="myForm" url="[controller:'book',action:'find']">
    <g:actionSubmit value="Find" />
    <g:textField name="like" value="" />
  </g:form>
</div>
Grails – The search is over

WebService REST

import grails.converters.*

  def showRest() {
    def bookInstance = Book.get(params.id)
    if(!bookInstance){
        render new Book() as JSON
        return
    }
    render bookInstance as JSON
  }
Grails – The search is over
Configuração por ambiente

   BuildConfig.groovy
   DataSource.groovy

   development {
      dataSource {
        pooled = true
        driverClassName = "com.mysql.jdbc.Driver”
        username = "book"
        password = "book123"
        dbCreate = "create-drop"
        dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
        url =
   "jdbc:mysql://localhost:3306/book_dev?autoreconnect=true"
      }
   }

$ grails install-dependency mysql:mysql-connector-java:5.1.16
Grails – The search is over
Plugins

GWT
LDAP
Spring Security
Spring WS
Maill
Feeds
Quartz
Axis2
Wicket
Grails – The search is over

Deploy

$ grails war

http://ec2-184-73-69-212.compute-1.amazonaws.com:8080/manager

http://ec2-184-73-69-212.compute-1.amazonaws.com:8080/booklibrary-0.1/
bibliografia sugerida
http://groovy.codehaus.org/
http://grails.org/
perguntas ???
contato

Aécio Costa – aecio.costa@cesar.org.br – www.aeciocosta.com.br

Felipe Coutinho – flc@cesar.org.br – www.felipelc.com

Weitere ähnliche Inhalte

Was ist angesagt?

dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsRob Napier
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorFedor Lavrentyev
 
The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189Mahmoud Samir Fayed
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationJoni
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196Mahmoud Samir Fayed
 
Python tutorial
Python tutorialPython tutorial
Python tutorialRajiv Risi
 
The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210Mahmoud Samir Fayed
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - IntroDavid Copeland
 
Php code for online quiz
Php code for online quizPhp code for online quiz
Php code for online quizhnyb1002
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)Makoto Yamazaki
 
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, allCiklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, allCiklum Ukraine
 

Was ist angesagt? (20)

dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World Protocols
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189
 
Realm to Json & Royal
Realm to Json & RoyalRealm to Json & Royal
Realm to Json & Royal
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
 
Linq introduction
Linq introductionLinq introduction
Linq introduction
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
 
Swift tips and tricks
Swift tips and tricksSwift tips and tricks
Swift tips and tricks
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210The Ring programming language version 1.9 book - Part 44 of 210
The Ring programming language version 1.9 book - Part 44 of 210
 
Python Crawler
Python CrawlerPython Crawler
Python Crawler
 
Potential Friend Finder
Potential Friend FinderPotential Friend Finder
Potential Friend Finder
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
 
Php code for online quiz
Php code for online quizPhp code for online quiz
Php code for online quiz
 
webScrapingFunctions
webScrapingFunctionswebScrapingFunctions
webScrapingFunctions
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)
 
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, allCiklum net sat12112011-alexander fomin-expressions and all, all, all
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 

Ähnlich wie Groovy Simplifies Java Code

TDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypeTDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypetdc-globalcode
 
Linq - an overview
Linq - an overviewLinq - an overview
Linq - an overviewneontapir
 
import java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdfimport java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdfadhityalapcare
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
Productive Programming in Groovy
Productive Programming in GroovyProductive Programming in Groovy
Productive Programming in GroovyGanesh Samarthyam
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptxadityaraj7711
 
Creating a Facebook Clone - Part XXXIII.pdf
Creating a Facebook Clone - Part XXXIII.pdfCreating a Facebook Clone - Part XXXIII.pdf
Creating a Facebook Clone - Part XXXIII.pdfShaiAlmog1
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfarpaqindia
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8bryanbibat
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
This Is Not Your Father's Java
This Is Not Your Father's JavaThis Is Not Your Father's Java
This Is Not Your Father's JavaSven Efftinge
 
Why Scala is the better Java
Why Scala is the better JavaWhy Scala is the better Java
Why Scala is the better JavaThomas Kaiser
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day Oneretronym
 

Ähnlich wie Groovy Simplifies Java Code (20)

Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
TDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypeTDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hype
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Groovy
GroovyGroovy
Groovy
 
Linq - an overview
Linq - an overviewLinq - an overview
Linq - an overview
 
JDK 8
JDK 8JDK 8
JDK 8
 
Java Generics
Java GenericsJava Generics
Java Generics
 
import java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdfimport java-util-ArrayList- import java-util-Collections- import java-.pdf
import java-util-ArrayList- import java-util-Collections- import java-.pdf
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Productive Programming in Groovy
Productive Programming in GroovyProductive Programming in Groovy
Productive Programming in Groovy
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
Creating a Facebook Clone - Part XXXIII.pdf
Creating a Facebook Clone - Part XXXIII.pdfCreating a Facebook Clone - Part XXXIII.pdf
Creating a Facebook Clone - Part XXXIII.pdf
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
This Is Not Your Father's Java
This Is Not Your Father's JavaThis Is Not Your Father's Java
This Is Not Your Father's Java
 
Why Scala is the better Java
Why Scala is the better JavaWhy Scala is the better Java
Why Scala is the better Java
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
 

Mehr von Aécio Costa

Android - de usuários a desenvolvedores
Android - de usuários a desenvolvedoresAndroid - de usuários a desenvolvedores
Android - de usuários a desenvolvedoresAécio Costa
 
Desafios e perspectivas para TV Conectada
Desafios e perspectivas para TV ConectadaDesafios e perspectivas para TV Conectada
Desafios e perspectivas para TV ConectadaAécio Costa
 
Facebook api além de meros usuários
Facebook api além de meros usuáriosFacebook api além de meros usuários
Facebook api além de meros usuáriosAécio Costa
 
Google tv desafios e oportunidades na tv conectada
Google tv desafios e oportunidades na tv conectadaGoogle tv desafios e oportunidades na tv conectada
Google tv desafios e oportunidades na tv conectadaAécio Costa
 
Refinamento e boas práticas de programação
Refinamento e boas práticas de programaçãoRefinamento e boas práticas de programação
Refinamento e boas práticas de programaçãoAécio Costa
 
Introdução ao Google TV
Introdução ao Google TVIntrodução ao Google TV
Introdução ao Google TVAécio Costa
 
Java: Muito mais que uma linguagem!
Java: Muito mais que uma linguagem!Java: Muito mais que uma linguagem!
Java: Muito mais que uma linguagem!Aécio Costa
 

Mehr von Aécio Costa (7)

Android - de usuários a desenvolvedores
Android - de usuários a desenvolvedoresAndroid - de usuários a desenvolvedores
Android - de usuários a desenvolvedores
 
Desafios e perspectivas para TV Conectada
Desafios e perspectivas para TV ConectadaDesafios e perspectivas para TV Conectada
Desafios e perspectivas para TV Conectada
 
Facebook api além de meros usuários
Facebook api além de meros usuáriosFacebook api além de meros usuários
Facebook api além de meros usuários
 
Google tv desafios e oportunidades na tv conectada
Google tv desafios e oportunidades na tv conectadaGoogle tv desafios e oportunidades na tv conectada
Google tv desafios e oportunidades na tv conectada
 
Refinamento e boas práticas de programação
Refinamento e boas práticas de programaçãoRefinamento e boas práticas de programação
Refinamento e boas práticas de programação
 
Introdução ao Google TV
Introdução ao Google TVIntrodução ao Google TV
Introdução ao Google TV
 
Java: Muito mais que uma linguagem!
Java: Muito mais que uma linguagem!Java: Muito mais que uma linguagem!
Java: Muito mais que uma linguagem!
 

Groovy Simplifies Java Code

  • 1. Grails – The search is over Aécio Costa Felipe Coutinho
  • 2. Grails – The search is over Groovy  Características  Groovy x Java  Regra dos 80/20 Grails  Cenário Atual do Desenvolvimento Web  Características  Arquitetura  Demo
  • 3. Grails – The search is over Groovy - Características Inspirada no Python, Ruby...; Linguagem Dinâmica; Plataforma Java; Especificação do JCP (JSR 241); Copy/Paste Compatibilty.
  • 4. Grails – The search is over O que Groovy tem de diferente de Java? Tipagem dinâmica; Recurso: attribute accessor; Closure; Métodos Dinâmicos; e mais...
  • 5. Grails – The search is over Tipagem dinâmica def name = “João” def names = [“João”, “José”, “Geraldo”]
  • 6. Grails – The search is over Atribute accessor class User{ String nome Integer idade } def user = new User(name:”João”, age: 23) user.nome = “Pedro”
  • 7. Grails – The search is over Closure def name = “Paulo” def printName = {println “Hello, ${name}”} printName() def listNames = [“Gabriela”, “Maria”] def sayHello = {println it} listNames.each(sayHello)
  • 8. Grails – The search is over Métodos Dinâmicos def methodName = “getYearBorn” user.”${methodName}”() new User().”getDayBorn”()
  • 9. Grails – The search is over Além de... Sobre carga de operadores; Ranges; MetaPrograming; e etc...
  • 10. Grails – The search is over Groovy veio acabar com a Regra dos 80/20 (Princípio de Pareto)
  • 11. Grails – The search is over import java.util.ArrayList; import java.util.List; class Seletor { private List selectBooksNameLessThan(List bookNames, int length) { List resultado = new ArrayList(); for (int i = 0; i < bookNames.size(); i++) { String candidate = (String) bookNames.get(i); if (candidate.length() < length) { resultado.add(candidate); } } return resultado; } public static void main(String[] args) { List books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); Seletor s = new Seletor(); List selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); for (int i = 0; i < selected.size(); i++) { String sel = (String) selecionados.get(i); System.out.println(sel); } }
  • 12. Grails – The search is over O que realmente interessa no código anterior?
  • 13. Grails – The search is over import java.util.ArrayList; import java.util.List; class Seletor { private List selectBooksNameLessThan(List bookNames, int length) { List resultado = new ArrayList(); for (int i = 0; i < bookNames.size(); i++) { String candidate = (String) bookNames.get(i); if (candidate.length() < length) { resultado.add(candidate); } } return resultado; } public static void main(String[] args) { List books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); Seletor s = new Seletor(); List selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); for (int i = 0; i < selected.size(); i++) { String sel = (String) selecionados.get(i); System.out.println(sel); } }
  • 14. Grails – The search is over
  • 15. Grails – The search is over Closure e import implícito
  • 16. Grails – The search is over import java.util.ArrayList; import java.util.List; class Seletor { private List selectBooksNameLessThan(List bookNames, int length) { List resultado = new ArrayList(); for (int i = 0; i < bookNames.size(); i++) { String candidate = (String) bookNames.get(i); if (candidate.length() < length) { resultado.add(candidate); } } return resultado; } public static void main(String[] args) { List books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); Seletor s = new Seletor(); List selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); for (int i = 0; i < selected.size(); i++) { String sel = (String) selecionados.get(i); System.out.println(sel); } }
  • 17. Grails – The search is over class Seletor { private List selectBooksNameLessThan(List bookNames, int length) { List resultado = new ArrayList(); bookNames.each { String candidate -> if (candidate.length() < length) { resultado.add(candidate); } } return resultado; } public static void main(String[] args) { List books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); Seletor s = new Seletor(); List selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); selected.each { String sel -> System.out.println(sel); } } }
  • 18. Grails – The search is over Closure e import implícito Declaração e Assinatura de Métodos
  • 19. Grails – The search is over class Seletor { private List selectBooksNameLessThan(List bookNames, int length) { List resultado = new ArrayList(); bookNames.each { String candidate -> if (candidate.length() < length) { resultado.add(candidate); } } return resultado; } public static void main(String[] args) { List books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); Seletor s = new Seletor(); List selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); selected.each { String sel -> System.out.println(sel); } } }
  • 20. Grails – The search is over List selectBooksNameLessThan(List bookNames, int length) { List resultado = new ArrayList(); bookNames.each { String candidate -> if (candidate.length() < length) { resultado.add(candidate); } } return resultado; } List books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); Seletor s = new Seletor(); List selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); selected.each { String sel -> System.out.println(sel); }
  • 21. Grails – The search is over Closure e import implícito Declaração e Assinatura de Métodos Tipagem Estática
  • 22. Grails – The search is over List selectBooksNameLessThan(List bookNames, int length) { List resultado = new ArrayList(); bookNames.each { String candidate -> if (candidate.length() < length) { resultado.add(candidate); } } return resultado; } List books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); Seletor s = new Seletor(); List selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); selected.each { String sel -> System.out.println(sel); }
  • 23. Grails – The search is over def selectBooksNameLessThan(bookNames, length) { def resultado = new ArrayList(); bookNames.each { candidate -> if (candidate.size() < length) { resultado.add(candidate); } } return resultado; } def books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); def selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); selected.each { sel -> System.out.println(sel); }
  • 24. Grails – The search is over Closure e import implícito Declaração e Assinatura de Métodos Tipagem Estática Instância simplificada de Listas Não necessidade de “return” “;” não obrigatório Impressão simples
  • 25. Grails – The search is over def selectBooksNameLessThan(bookNames, length) { def resultado = new ArrayList(); bookNames.each { candidate -> if (candidate.size() < length) { resultado.add(candidate); } } return resultado; } def books = new ArrayList(); books.add("Harry Potter"); books.add("A Vila"); books.add(“O Exorcista"); def selected = s.selectBooksNameLessThan(books, 10); System.out.println("Total Selecionados: " + selecionados.size()); selected.each { sel -> System.out.println(sel); }
  • 26. Grails – The search is over def selectBooksNameLessThan(bookNames, length) { def resultado = []; bookNames.each { candidate -> if (candidate.size) < length) { resultado.add(candidate) } } resultado } def books = ["Harry Potter”, "A Vila”, “O Exorcista”] def selected = s.selectBooksNameLessThan(books, 10) println "Total ${selecionados.size()}” selected.each { sel -> println sel }
  • 27. Grails – The search is over Closure e import implícito Declaração e Assinatura de Métodos Tipagem Estática Instância simplificada de Listas Não necessidade de “return” “;” não obrigatório Impressão simples Métódos Dinâmicos
  • 28. Grails – The search is over def selectBooksNameLessThan(bookNames, length) { def resultado = []; bookNames.each { candidate -> if (candidate.size) < length) { resultado.add(candidate) } } resultado } def books = ["Harry Potter”, "A Vila”, “O Exorcista”] def selected = s.selectBooksNameLessThan(books, 10) println "Total ${selecionados.size()}” selected.each { sel -> println sel }
  • 29. Grails – The search is over def selectBooksNameLessThan(bookNames, length) { bookNames.findAll { it.size() < length } } def books = ["Harry Potter”, "A Vila”, “O Exorcista”] def selected = s.selectBooksNameLessThan(books, 10) println "Total ${selecionados.size()}” selected.each { sel -> println sel }
  • 30. Grails – The search is over def selectBooksNameLessThan(bookNames, length) { bookNames.findAll { it.size() < length } } def books = ["Harry Potter”, "A Vila”, “O Exorcista”] def selected = s.selectBooksNameLessThan(books, 10) println "Total ${selecionados.size()}” selected.each { sel -> println sel }
  • 31. Grails – The search is over def books = ["Harry Potter”, "A Vila”, “O Exorcista”] def selected = books. findAll { it.size() <= 5} println "Total ${selecionados.size()}” selected.each { sel -> println sel }
  • 32. Grails – The search is over def books = ["Harry Potter”, "A Vila”, “O Exorcista”] def selected = books. findAll { it.size() <= 5} println "Total ${selecionados.size()}” selected.each { sel -> println sel } Seletor.groovy
  • 33. Grails – The search is over def books = ["Harry Potter”, "A Vila”, “O Exorcista”] def selected = books. findAll { it.size() <= 5} println "Total ${selecionados.size()}” selected.each { sel -> println sel Groovy é Java } Seletor.groovy
  • 34. Grails – The search is over Cenário Atual Web  Persistência  Validações  Logs  Visualização  Controladores  Controle Transacional  Injeção de Dependências  Ajax  Redirecionador de URL’s  Configuração por ambiente  Internacionalização
  • 35. Grails – The search is over
  • 36. Grails – The search is over Welcome to
  • 37. Grails – The search is over Framework Web de Alta produtividade para plataforma Java; Programação por convenção; MVC nativo; Fácil bootstrap; GORM; Scaffolding; Plugins; e tudo que você viu lá atras...
  • 38. Grails – The search is over Arquitetura do Grails
  • 39. Grails – The search is over Passos para criar a Aplicação $ grails create-app booklibrary $ grails run-app
  • 40. Grails – The search is over Classes de domínio $ grails create-domain-class cesar.example.Book class Book { String title Date releaseDate String ISBN }
  • 41. Grails – The search is over Scaffolding INSERT, UPDATE, DELETE, SEARCH $ grails generate-all cesar.example.Book
  • 42. Grails – The search is over Validations (Constraints) DSL interna baseada no recurso builder da linguagem Groovy; Constraints: http://grails.org/doc/latest/ref/Constraints/Usage.html static constraints = { title(blank: false) ISBN(blank: false, unique: true) }
  • 43. Grails – The search is over Relacionamento $ grails create-domain-class cesar.example.Person class Person { static hasMany = [books: Book] String name String email String password static constraints = { name(blank: false) email(blank: false, email: true) password(blank: false, password: true) } } Na classe Book: static belongsTo = [person: Person]
  • 44. Grails – The search is over View .gsp i18n # Book book.label=Livro book.title.label=Titulo book.person.label=Pessoa book.releaseDate.label=Data de lancamento # Person person.label=Pessoa person.name.label=Nome person.password.label=Senha
  • 45. Grails – The search is over GORM def books = Book.list(max:10, order:”name”) def books = Book.findByName(“The Developer”) def books = Book.findAllByPriceLessThan(10.0) def books = Book.findAllByTitleLikeAndPriceBetween(“Harry %”, 40.0, 70.0)
  • 46. Grails – The search is over GORM class BookController { def find() { def books = Book.findAllByTitleLike("%"+params.like+"%") render(view: "list", model: [bookInstanceList: books, bookInstanceTotal: books.size()]) } } <div> <br/> <g:form name="myForm" url="[controller:'book',action:'find']"> <g:actionSubmit value="Find" /> <g:textField name="like" value="" /> </g:form> </div>
  • 47. Grails – The search is over WebService REST import grails.converters.* def showRest() { def bookInstance = Book.get(params.id) if(!bookInstance){ render new Book() as JSON return } render bookInstance as JSON }
  • 48. Grails – The search is over Configuração por ambiente BuildConfig.groovy DataSource.groovy development { dataSource { pooled = true driverClassName = "com.mysql.jdbc.Driver” username = "book" password = "book123" dbCreate = "create-drop" dialect = "org.hibernate.dialect.MySQL5InnoDBDialect" url = "jdbc:mysql://localhost:3306/book_dev?autoreconnect=true" } } $ grails install-dependency mysql:mysql-connector-java:5.1.16
  • 49. Grails – The search is over Plugins GWT LDAP Spring Security Spring WS Maill Feeds Quartz Axis2 Wicket
  • 50. Grails – The search is over Deploy $ grails war http://ec2-184-73-69-212.compute-1.amazonaws.com:8080/manager http://ec2-184-73-69-212.compute-1.amazonaws.com:8080/booklibrary-0.1/
  • 53. contato Aécio Costa – aecio.costa@cesar.org.br – www.aeciocosta.com.br Felipe Coutinho – flc@cesar.org.br – www.felipelc.com