Translate

Tuesday 5 October 2021

Object Oriented Programming Traits in Groovy Scripting groovy training telugu 40

 Watch This Video

https://youtu.be/eMB0XxDblsY

----------------------------------------------------------------------------------------------------------



//Bird.groovy

package com.theraldanvega.traits


class Bird implements FlyingAbility, SpeakingAbility{

}


//FlyingAbility.groovy
package com.theraldanvega.traits

trait FlyingAbility{
String fly(){

'I am Fly'
}

}

//SpeakingAbility.groovy
package com.therealdanvega.traits

trait SpeakingAbility
{
trait SpeakingAbility{
 String speak(){
"I am Speaking"
}
}

//App.groovy
package com.therealdanvega
import com.therealdanvega.traits.Bird

Bird b=new Bird()
assert b.fly()== "I am Flying"
assert b.speak() =="I am Speaking"








Object Oriented Programming Interface in Groovy Scripting groovy training telugu 39

 Watch This Video

https://youtu.be/lh-VDCkqodc

------------------------------------------------------------------------------------------------

//Person.groovy
package com.therealdanvega.domain
@groovy.transform.ToString()
class Person{

String first, last

}

//IPersonService.groovy
package com.therealdanvega.service

import com.therealdanvega.domain.Person

interface IPersonService{

Person find()
List <People> findAll()

}

//PersonService.groovy
package com.therealdanvega.service
import com.therealdanvega.domain.Person
class PersonService implements IPersonService{
@Override
Person find(){
person p= new Person(first:"Dan",last:"vega")
return p
}

@Override

List <People> findAll(){
person p1= new Person(first:"Dan",last:"vega")
person p2= new Person(first:"jam",last:"vega")
[p1,p2]

}
}

//App.groovy

package com.therealdanvega

import com.therealdanvega.service.PersonService

PersonService ps=new PersonService()
println ps.find()




 

Object Oriented Programming Inheritance in Groovy Scripting groovy training telugu 38

 Watch This Video

https://youtu.be/H47LNtADQ7c

-------------------------------------------------------------------------------------------------------------


// Phone.groovy

package com.therealdanvega.domain

class Phone{
String name
String os
String appStore

def powerOn(){
}

def powerOff(){

}

def ring(){

}
}
//Iphone.groovy

package com.therealdanvega.domain
@groovy.transform.ToString
class Iphone extends Phone{

String iosVersion
def homeButtonPressed(){

}
def airplay(){

}
def powerOn()

{

}

}


//App.groovy
package com.therealdanvega
package com.therealdanvega.domain.Iphone

Iphone phone = new Iphone(name:"iphone",appStore:"Apple Store",os:"ios")
println phone

Object Oriented Programming Organizing Classes into Packages in Groovy Scripting training intelugu37

 Watch This Video

https://youtu.be/nFSX-QXlHH4

------------------------------------------------------------------------------------------------------------------



Object Oriented Programming Constructors & Methods in Groovy Scripting training telugu 36

 Watch This Video

https://youtu.be/Y0tnvA2SKGs


-------------------------------------------------------------------------------------------------------------

@groovy.transform.ToString
class Person{
String first,last
//Constractor
Person(String fullName){
List parts =fullName.split(' ')
this.first=parts[0]
this.first=parts[1]

}
//methods

public void foo(String a, String b){
//do stuff
}
String getFullName(){
"$last $first"
}
def bar(){

}
ststic String doGoodWork(){
println "do some good work............"
}
List someMethod (List num=[1,,2,3] Boolean canAccessAll=false){

}
}
/*Person p= new Person ("Dan Vega")
println p */

Person.doGoodWork()

Object Oriented Programming Classes Fields Local Variables in groovy Scripting groovy training telugu 35

 Watch This Video

https://youtu.be/A9mtl7GDZXU


---------------------------------------------------------------------------------------------------------------


class Person{
String firstName,lastName
def dob
//private |  protected |public
protected String f1,f2,f3
private Date createdOn= new Date()


static welcomeMsg="Hello"

public static final String WELCOME_MSG="HELLO"

}
//LOCAL VARIABLES
def foo(){
String msg ="Hello"
String firstName="Dan"
println"$msg, $firstName"
}
}

def Person =new Person()

println Person.foo()
 

Exercise UsingControl Structures Groovy Scripting in groovy traing telugu 34

 Watch This Video

https://youtu.be/6HhokTVjIaM


-----------------------------------------------------------------------------------------------

[Exercise] Control Structures
Control Structures

We used a class similar to this in a previous exercise but I think it's a short and sweet example of what we need to review in this exercise. 

Create An Account Class

create a property of type BigDecimal called balance with an initial value of 0.0

Create a method called deposit

use a conditional structure (if would work great here) to check if the amount being passed is less than zero. If it is we should catch this case because we don't want to deposit negative numbers. In this case, throw an exception.

Create another method called deposit that takes a list of amounts

use a for loop to loop over these amounts and call deposit

Now that we have our class let's test it out. You can do all of this in the same file (just don't create a file called Account.groovy) 

Create an instance of the account class

deposit a valid amount

deposit an invalid amount (what happens?)

try / catch on invalid amounts

deposit a list of amounts. 


//CODE

class Account {
BigDecimal balance=0.0
def deposit(BigDecimal amount)
{
if(amount <0){
throw new Exception("Deposit amoubt must be greater than 0")
}

balance += amount
}
def deposit(List amounts){
for (amount in amounts){
deposit(amount)
}
}
}
Account checking =new Account()
checking.deposit(10.00)
println checking.blance
try{
checking.deposit(-2)
}
catch(Exception e)
{
println "You entet invalid amount"
}
println checking.blance


ExceptionHandling in Groovy Scripting grrovy training in telugu 33

 Watch This Video

https://youtu.be/VnLR1LEz7CE

------------------------------------------------------------------------------------------------------

def foo(){
//do stuff
throw new Exception("Foo Exception")
}
List log=[]
try{
foo()
}
catch(Exception e){
log <<e.message
}
finally{
log <<'finally'
}
println log

//Java 7 version multiple catch block

try{

//do something

}
catch (FileNotFoundException | NullPointerException)
{
println e.class.name
println e.message
}

Looping in Groovy Scripting groovy training telugu 32

 Watch This Video

https://youtu.be/KuEJVM7iJv0

---------------------------------------------------------------------------------------------------------


//Looping
//while

List numbers=[1,2,3]
while(numbers)
{
//do something
numbers.remove(0)
}

assert numbers ==[]

//for

List nums=[1,2,3,4]
for(Integer i in 1..10){
println i
}
for(j in 1..5)
{
println j

}

Conditional Structure in Groovy Scripting groovy training telugu 31

 Watch This Video

https://youtu.be/-3Pt0lcbPgk


-------------------------------------------------------------------------------------------------------------

// if boolean (expression) {// logic}

if (true){

println true
}

if (true)
println true

def age=35

if (age>=35){
println "can run president"

}


if (false){

println true
}

else {

println false
}

def yourage=18
if(yourage>=21){
println"eligible for Marriage"
}
else{
println "not eligible for Marriage"
}


def someage=37

if(someage>= 21 && someage <35){
println "eligible for Marriage"
}

else if(someage >= 35){

println "run for president"

}
else {
println "not eligible for Marriage"

}

// ternary operator

def name='Dan'
def isitdan=(name.toUpperCase()=='DAN')?'YES":'NO'
println isitdan

//switch

def num=5
switch(num){
case 1:
println "1"

case 2:

println "2"
default:
println "default value"

}

Groovy Truth in Groovy Scripting groovy training telugu 30

 Watch This Video

https://youtu.be/bNzfxyJfaCw

-----------------------------------------------------------------------------------------------------------------------------

// Boolean

assert true

assert !false

//matcher

assert ('a'=='a')
assert !('a'=='b')

//collection

assert [1]
assert ![]

//map
assert [1:'one']
assert ![:]

//String
assert "asd"
assert !""

//Number
assert 1
assert 3.5
assert !0

//None of the above

assert new Object()
assert null





Exercise Using Closure in Groovy Scripting groovy traing telugu 29

 Watch This Video

https://youtu.be/vt52uM74u80

-----------------------------------------------------------------------------------------------------------------------------


[Exercise] Using Closures
Closure Basics

Locate the class groovy.lang.Closure and spend a few minutes looking through documentation.

Create a Method that accepts a closure as an argument

Create a closure that performs some action

Call the method and pass the closure to it.

Create a list and use them each to iterate over each item in the list and print it out

Hint - You can use the implicit it or use your own variable

Create a map of data and iterate over it using each method. 

This method can take a closure that accepts 1 or 2 arguments. 

Use 2 arguments and print out the key and value on each line.

Demonstrate the use of curry and try to come up with an example different from the one we used in the lecture. 

Explore the GDK

In the following exercises we are going to explore the GDK to find some methods that take closures and learn how to use them. Hint - I would narrow your search to java.util.Collection, java.lang.Iterable & java.util.List

Search for the find and findAll methods.

What is the difference between the two? 

Write some code to show how they both work.

Search for the any and every methods.

What is the difference between the two? 

Write some code to show how they both work. 

Search for the method groupBy that accepts a closure

What does this method do? 

Write an example of how to use this method.


def mymethod(Closure c){
c()
}
def foo={
println"foooo..............."
}
mymethod(foo)
List names=["Dan","Vega","Jhon","rashmi","rasi"]
names.each{name ->
 println name
}
Map teams=[baseball:"Cleveland Indians", basketball:"Cleveland Cavs", football:"Cleveland Browns"]
teams.each{k,v ->
println"$k=$v"
}
def greet ={ String greeting, String name ->
println "$greeting,$name"

}
greet ("HELLO","DAN")
def sayHello=greet.curry("HELLO")

List people=[
[name:"Jame", city:"New York City"]
[name:"Jhon", city:"Cleveland"]
[name:"Mary", city:"New York City"]
[name:"Dan", city:"Cleveland"]
[name:"Ton", city:"New York City"]
[name:"Frank", city:"New York City"]
[name:"Jason", city:"Cleveland"]
]
println people.find{person ->person.city=="Cleveland"}
println people.findAll{person ->person.city=="Cleveland"}
println people.any{person ->person.city=="Cleveland"}
println people.every{person ->person.city=="Cleveland"}

def peopleByCity =people.groupBy{person ->person.city}
println peopleByCity





Scope of Delegate in Groovy Scripting groovy trainig telugu 28

 Watch This Video

https://youtu.be/56TcvetOsg4

------------------------------------------------------------------------------------------------------------------

class ScopeDemo{
def outerClosure ={
println this.class.name
println owner.class.name
println delegate.class.name
def innerClosure={
println this.class.name
println owner.class.name
println delegate.class.name
}
innerClosure()
}
}
def demo=new ScopeDemo()

//other Example

def writer={
append 'Dan'
append 'lives in USA'

}

def append(String s){

println "append() called with argument of $s"
}

StringBuffer sb= new StringBuffer()
writer.resolveStrategy=Closure.DELEGATE_FIRST
writer.delegate=sb
writer()




Curry Methods in Groovy Scripting groovy training telugu 27

 Watch This Video

https://youtu.be/f23J76-sXGo

----------------------------------------------------------------------------------------------------------------------

def log={String type,Date createdOn,String  msg ->

println"$createdOn [$type]-$mgs"

}

log("DEBUG", new Date(),"This is my first debug statement......")

def debuglog =log.curry("DEBUG")

debuglog(new Date(),"This is my first debug statement.........")
debuglog(new Date(),"This is onOther")


def todayDebugLog= log.curry("DEBUG",new Date())
todayDebugLog("This is today Bug")

//right curry


def crazyPersonLog =log.rcurry("Why i am logging this way")
crazyPersonLog("ERROR",new Date())

//index based Curring

def typeMsgLog=log.ncurry(1,new Date())
typeMsgLog("ERROR","This is using ncurry")

Collection Methods in Groovy Scripting groovy scripting training telugu 26

 Watch This Video

https://youtu.be/ZSYYBOANyac


--------------------------------------------------------------------------------------------------------------------------


//each &eachWithIndex

List nums =[2,21,44,35,8,4]
for (i in nums){
println i
}
nums.each{println it}

for (int j=0;j<nums.size();j++){
println "$j:${nums[j]}"
}

nums.eachWithIndex{num.idx ->
println "$idx:$num"
}

//findAll

List days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
List weekend=days.findAll{it.startsWith("S")}

println days
println weekend

//collect

List number=[3,6,7,9,8]

List numsTimesTen=[]

number.each{num ->

numsTimesTen << num*10
}
List newTimesTen = number.collect{ num -> num*10}


println number
println numsTimesTen
println newTimesTen

Closures Parameters in Groovy Scripting groovy training telugu 25

 Watch This Video

https://youtu.be/zq68KxNyFwc


--------------------------------------------------------------------------------------------------------------------------

//implict parameter

def foo={
println it
}

foo('don')

def noparass={->
println "no parss...."

}

noparass()

def sayHello ={String first, String last ->
println "Hello, $first $last"
}

sayHello("Dan","vega")

// Default values


def greet={String name, String greeting ="Howdy"->
println "$greeting,$name"
}

greet ("Dan","Hello")
greet("vega")

//var-arg

def concat={String...args->
agrs.join('')
}

println concat('abc','def')
println concat('abc','def','gfd')


Creating Closures in Groovy Scripting groovy training telugu 24

 Watch This Video

https://youtu.be/HckcKTZJi0A


--------------------------------------------------------------------------------------------------------------------------

def c ={}
println c.class.name
println c instanceof Closure

def sayHelo={ name ->

println "Hello $name"
}

sayHello('rashmi')

List num=[3,4,5,6,7]
num.each({ nums ->
println nums

})

//closures are object

def timesTen(num,closure){
 closure{num *10}
}

timesTen(10,{println it})
timesTen(2,{println it})

Clousers in Groovy Scripting groovy training telugu 23

 Watch This Video

https://youtu.be/-bDzR88icQw

--------------------------------------------------------------------------------------------------------------------------
http://groovy-lang.org/closures.html



Closures:


This chapter covers Groovy Closures. A closure in Groovy is an open,
anonymous, block of code that can take arguments, return a value 
and be assigned to a variable. A closure may reference variables 
declared in its surrounding scope. In opposition to the formal 
definition of a closure, Closure in the Groovy language can also 
contain free variables which are defined outside of its surrounding scope.
While breaking the formal concept of a closure, it offers a variety of 
advantages which are described in this chapter.


Syntax:

{ [closureParameters -> ] statements }






Exercise Collections in Groovy Scripting groovy training telugu 22

Watch This Video

https://youtu.be/gp3HA0Wi9ZM 

----------------------------------------------------------------------------------------------------------------------------

[Exercise] Using Collections

1)Ranges

If you are new to Java or Groovy the idea of an Enum might be new. An Enum is a collection of constant values. We can use this collection of constants to create ranges. I want you to do some reading up on enum's and create an enum for days of the week. ex Sunday, Monday, etc...

Create a range from that enum
Print the size of the Range
Use the contains method to see if Wednesday is in that Range
Print the from element of this range
Print the to element of this range

2)Lists

Create a list days (Sun - Sat)
Print out the list
Print the size of the list
Remove Saturday from the list
Add Saturday back by appending it to the list
Print out the Wednesday using its index

3)Maps

Create a map of days of the week
1: Sunday, 2:Monday, etc...
Print out the map
Print out the class name of the map
Print the size of the map
Is there a method that would easily print out all of the days (values)? 
Without closures you may have to look at the Java API for LinkedHashMap


//Range

enum Days{
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY
}
def dayRange=Days.SUNDAY..days.SATURDAY
//for in loop
for(day in dayRange){
println day

}
// using Closures

dayRange.each{day ->
println day
}

println dayRange.size()
println dayRange.contains(Days.WEDNESDAY)
println dayRange.from
println dayRange.to


//List

def days = ["SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"]
println days
println days.size()
days.pop()
println days
days<<"Sunday"
println days
println days[2]



//Map

def days = [1:"SUNDAY",2:"MONDAY",3:"TUESDAY",4:"WEDNESDAY",5:"THURSDAY",6:"FRIDAY",7:"SATURDAY"]
println days

println days.getClass().getName()
println days.size()
println days.values()





Collections Map in GroovyScripting groovy training in telugu 21

 Watch This Video

https://youtu.be/MKAfMekRaJc


---------------------------------------------------------------------------------------------------------------------

Map map=[:]
println map
println map.getClass().getName()

def person =[first:"ravi",email:"ravikuamr@email.com"]
println person
println person.first
person.twiter="qdfefefregre"

println person

def emailkey="emailadress"
def whatsapp=[name:"rashmi", (emailkey):"uiwhdiuhi@email.com"]
println(whatsapp)

println person.size()