The document discusses Groovy and Grails. It begins by explaining some of Groovy's key features like dynamic typing, closures, and implicit imports. It then demonstrates how these features simplify and shorten Java code. The document concludes by describing Grails, a web framework that uses Groovy. It outlines some of Grails' main capabilities like persistence, validation, scaffolding, and its convention over configuration approach to web development.
Apresentação criada para o Intervalo Técnico do CESAR realizado em 07/03/2012.
Grails é um framework web de alta produtividade para a plataforma Java.
Para isso ele utiliza tecnologias maduras do mundo Java, como os frameworks Hibernate e Spring, através de uma interface simples e consistente. Com pouca codificação e configuração, graças a linguagem Groovy, é possível criar aplicações web de forma fácil e ágil.
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
Contact
FUNCTIONAL PROGRAMING AND EVENT SOURCING - A PAIR MADE IN HEAVEN - EXTENDED, 2 HOURS LONG BRAINWASH
TL;DR: This is talk is a solid introduction to two (supposedly) different topics: FP & ES. I will cover both the theory and the practice. We will emerage ES+FP application starting from ES+OO one.
While reading blogs or attending conferences, you might have heard about Event Sourcing. But didn't you get this feeling, that while there is a lot of theory out there, it is really hard to see a hands-on example? And even if you find some, those are always orbiting around Object Oriented concepts?
Greg Young once said "When we talk about Event Sourcing, current state is a left-fold of previous behaviours. Nothing new to Functional Programmers". If Functional Programming is such a natural concept for event sourced systems, shouldn't they fit together on a single codebase?
In this talk we will quickly introduce Event Sourcing (but without going into details), we will introduce some functional concepts as well (like State monad). Armoured with that knowledge we will try to transform sample ES application (OO-style, tightly coupled with framework) to frameworkless, FP-style solution).
Talk is targeted for beginner and intermediate audience. Examples will be in Scala but nothing fancy - normal syntax.
This talk is an extended version of a presentation "Event Sourcing & Functional Programming - a pair made in heaven". It is enriched with content of presentations: "Monads - asking the right question" and "It's all been done before - The Hitchhiker's Guide to Time Travel".
Курс "Программирование на Java". Лекция 04 "Обобщения и лямбды".
Массивы. Механизм обобщений (Generics), надтипы и подтипы (supertypes and subtypes). Лямбда-функции, функциональные интерфейсы. Пакет java.util.collections, списки (Lists), множества (Sets), словари (Maps), итераторы (Iterators and Iterables). Иерархия коллекций.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
Apresentação criada para o Intervalo Técnico do CESAR realizado em 07/03/2012.
Grails é um framework web de alta produtividade para a plataforma Java.
Para isso ele utiliza tecnologias maduras do mundo Java, como os frameworks Hibernate e Spring, através de uma interface simples e consistente. Com pouca codificação e configuração, graças a linguagem Groovy, é possível criar aplicações web de forma fácil e ágil.
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
Contact
FUNCTIONAL PROGRAMING AND EVENT SOURCING - A PAIR MADE IN HEAVEN - EXTENDED, 2 HOURS LONG BRAINWASH
TL;DR: This is talk is a solid introduction to two (supposedly) different topics: FP & ES. I will cover both the theory and the practice. We will emerage ES+FP application starting from ES+OO one.
While reading blogs or attending conferences, you might have heard about Event Sourcing. But didn't you get this feeling, that while there is a lot of theory out there, it is really hard to see a hands-on example? And even if you find some, those are always orbiting around Object Oriented concepts?
Greg Young once said "When we talk about Event Sourcing, current state is a left-fold of previous behaviours. Nothing new to Functional Programmers". If Functional Programming is such a natural concept for event sourced systems, shouldn't they fit together on a single codebase?
In this talk we will quickly introduce Event Sourcing (but without going into details), we will introduce some functional concepts as well (like State monad). Armoured with that knowledge we will try to transform sample ES application (OO-style, tightly coupled with framework) to frameworkless, FP-style solution).
Talk is targeted for beginner and intermediate audience. Examples will be in Scala but nothing fancy - normal syntax.
This talk is an extended version of a presentation "Event Sourcing & Functional Programming - a pair made in heaven". It is enriched with content of presentations: "Monads - asking the right question" and "It's all been done before - The Hitchhiker's Guide to Time Travel".
Курс "Программирование на Java". Лекция 04 "Обобщения и лямбды".
Массивы. Механизм обобщений (Generics), надтипы и подтипы (supertypes and subtypes). Лямбда-функции, функциональные интерфейсы. Пакет java.util.collections, списки (Lists), множества (Sets), словари (Maps), итераторы (Iterators and Iterables). Иерархия коллекций.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
If you saw the "Crusty Talk" (Protocol Oriented Programming in Swift) at WWDC, you saw Apple announce Swift as the first "Protocol Oriented language." If you immediately jumped into Xcode and tried to write a lot of protocol oriented code, you may have discovered that the promise isn't quite the reality. In this talk, you'll learn how to rethink your types so that you can avoid complex protocol problems without giving up their power.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
This session will take you on a tour of several languages that on the surface only share one thing in common – they all run on JVM as the execution platform. However, despite completely different appearances of Scala, Clojure, Jython and Groovy, we will demonstrate that they have some important commonalities. You will also see the emerging importance of JVM as a generic platform (as opposed to focusing on Java the language).
During the session we will implement a solution to a simple problem in each language, then compare these languages to Java. These solutions, while simple, will nonetheless highlight some of the common principles and implementation patterns that exist across the languages based on different paradigms. The solutions will also show how these approaches are different from implementation patterns common in Java.
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
Slides of a talk I gave at work on Scala. It is geared toward Java developers. Some of the examples are in my company's domain, which is analyzing energy usage (i.e. a "read" is an electric meter read).
Paco van der Linden, werkzaam als Senior ADF Ontwikkelaar bij AMIS, heeft met Groovy een aantal interessante oplossingen ontwikkeld. De kennis en ervaring die hij daarbij met Groovy in combinatie met Java (en ADF) heeft opgedaan, heeft hij op maandag 26 november gedeeld in een kennissessie.
Functional programming is all the rage. It can undoubtedly produce cleaner and more expressive code, but why switch to Scala or wait for Java 8? In fact, there are many ways to dramatically improve your Java code quality by using a more functional style today. This presentation discusses how techniques such as functional programming, using fluent APIs, and other clean coding practices can make your code more concise, more readable, and much easier to maintain. But more importantly, you will learn about libraries such as LambdaJ and Google Guava that make this possible today with your existing Java code base.
If you saw the "Crusty Talk" (Protocol Oriented Programming in Swift) at WWDC, you saw Apple announce Swift as the first "Protocol Oriented language." If you immediately jumped into Xcode and tried to write a lot of protocol oriented code, you may have discovered that the promise isn't quite the reality. In this talk, you'll learn how to rethink your types so that you can avoid complex protocol problems without giving up their power.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
This session will take you on a tour of several languages that on the surface only share one thing in common – they all run on JVM as the execution platform. However, despite completely different appearances of Scala, Clojure, Jython and Groovy, we will demonstrate that they have some important commonalities. You will also see the emerging importance of JVM as a generic platform (as opposed to focusing on Java the language).
During the session we will implement a solution to a simple problem in each language, then compare these languages to Java. These solutions, while simple, will nonetheless highlight some of the common principles and implementation patterns that exist across the languages based on different paradigms. The solutions will also show how these approaches are different from implementation patterns common in Java.
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
Slides of a talk I gave at work on Scala. It is geared toward Java developers. Some of the examples are in my company's domain, which is analyzing energy usage (i.e. a "read" is an electric meter read).
Paco van der Linden, werkzaam als Senior ADF Ontwikkelaar bij AMIS, heeft met Groovy een aantal interessante oplossingen ontwikkeld. De kennis en ervaring die hij daarbij met Groovy in combinatie met Java (en ADF) heeft opgedaan, heeft hij op maandag 26 november gedeeld in een kennissessie.
Functional programming is all the rage. It can undoubtedly produce cleaner and more expressive code, but why switch to Scala or wait for Java 8? In fact, there are many ways to dramatically improve your Java code quality by using a more functional style today. This presentation discusses how techniques such as functional programming, using fluent APIs, and other clean coding practices can make your code more concise, more readable, and much easier to maintain. But more importantly, you will learn about libraries such as LambdaJ and Google Guava that make this possible today with your existing Java code base.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static java.lang.System.out;
public class homework {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++)
list.add(int) (Math.random()* 10) + 1);
Collections.sort(list);
System.out.println("The list id : " + list);
int index =linearSearch(list, 10);
if (index >+ 0)
System.out.println("Linear search: the number 5 was found at index " + index);
else
System.out.println("Linear search: the number 5 is not found ");
List<String> names = new ArrayList<>();
names.add("Tyson");
names.add("John");
names.add("Edgar");
names.add("LouLou");
Collections.sort(list);
System.out.println("The names are : " + names);
index = linearSearch(names, "JOhn");
if (index >= 0)
System.out.println("Linear search: Edgar was found at index " + names);
else
System.out.println("Linear search: Edgar is not found" + names);
}
public static <E> int linearSearch(List<E> lsit, E data) {
for (int i = 0; i < list.size(); i++)
if (list.get(i).equals(data))
return i;
return -1;
}
}
Chapter 14 - Linear Search and Binary Search - Assignment Due Wednesday by 11:59pm P
Points 100 Submitting a text entry box or a file upload Allowed Attempts 1 Available until Mar
1 at 11:59pm Modify the binarySearch method shown in the video lecture so that it's generic.
Test it with at least two types to make sure it works. Hint 1: Examine the review problem and its
solution, which modifies the linear search algorithm in the same way. Hint 2: Your binarySearch
method signature should be: "private static < E extends Comparable > boolean binarySearch(List
list, E data): Turn in the following, - The source files (no zip file, just the individual java files). -
A screen shot of your program in action. It should show the result of the test run.
.
Are you a Java programmer having wrist pain typing a lot (yes, I have!)? Does your mind keep swinging from loving to hating Java? Do you want to become more productive without leaving your world of Java? If so, this presentation is for you. I have been experimenting with Groovy for the last three months and I'm loving it - I am not going back to programming in plan old Java anymore. Yes, I have become Groovy - have you?
Programing with java for begniers .pptxadityaraj7711
Java is a high-level, object-oriented programming language developed by Sun Microsystems in the mid-1990s (now owned by Oracle Corporation). It is widely used for building a variety of applications, including desktop, web, mobile, and enterprise software. Java's design emphasizes portability, simplicity, and security, making it one of the most popular programming languages in the world.
### Importance of Java:
1. **Platform Independence**:
- Java programs can run on any device or operating system that supports the Java Virtual Machine (JVM).
- This "write once, run anywhere" (WORA) capability makes Java applications highly portable.
2. **Object-Oriented Programming (OOP)**:
- Java supports key OOP principles such as inheritance, encapsulation, polymorphism, and abstraction.
- These principles enable developers to create modular and reusable code.
3. **Rich Ecosystem and Libraries**:
- Java has a vast ecosystem of libraries, frameworks, and tools that facilitate development across various domains.
- Popular frameworks like Spring, Hibernate, and Apache Struts streamline development in enterprise environments.
4. **Robustness and Reliability**:
- Java has strong exception handling and type-checking mechanisms that contribute to the robustness and reliability of applications.
5. **Community and Support**:
- Java has a large and active developer community, providing support and resources for learning and troubleshooting.
- Java's extensive documentation and community forums are valuable resources for developers.
6. **Performance**:
- Java's just-in-time (JIT) compilation allows for optimized execution, improving performance.
- Java can handle large-scale applications and complex computations efficiently.
7. **Security**:
- Java's architecture includes features such as runtime security checks and a security manager for safe execution.
- This makes it a preferred choice for developing secure applications.
8. **Enterprise Applications**:
- Java is a dominant language in enterprise development due to its scalability, stability, and compatibility with existing systems.
- Many businesses rely on Java for mission-critical applications.
9. **Career Opportunities**:
- Proficiency in Java opens up many career opportunities, particularly in enterprise development, finance, healthcare, and telecommunications.
10. **Future-Proofing**:
- Java's continuous updates and compatibility with emerging technologies ensure that it remains relevant and future-proof.
Overall, Java's versatility, reliability, and widespread adoption make it an essential language for developers across various industries
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfarpaqindia
JAVA
LAB #8 - ARRAY BASED LISTS
The next exercise is based on this implemetation for an UnorderedArrayList of integers:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] = list[i + 1.
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
Desafios e perspectivas para TV ConectadaAécio Costa
O título: Desafios e Perspectivas para a TV Conectada tem como objetivo a discussão sobre a evolução da TV que precisou ser integrada com a Internet, o modelo de TV que conhecemos e a mudança que ele enfrenta e os desafios que ainda não foram resolvidos. Nessa conversa iremos debater alguns desses desafios, discutir possibilidades sobre a transformação do ambiente de TV (tecnológico, negócio e etc) e o que os principais 'players' desse mundo tem pensado e feito a respeito.
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);
}
}
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
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)
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/