Translate

Wednesday, 6 October 2021

Working with Builders ObjectGraphBuilder in Groovy Scripting groovy training telugu 64

 Watch This Video

https://youtu.be/PYwziwU6FjQ

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


//objgraph.groovy

import groovy.transform.ToString

@ToString(includeNames = true)
class Book{
    String title
    String summary
    List<Section> sections =[]

}
@ToString(includeNames = true)
class Section{
    String title
    List<Chapter> chapters =[]
}
@ToString(includeNames = true)
class Chapter{
    String title
}

//Java Style
/*public Book createBook(){
    Book b=new Book();
    b.setTitle("My Book")
    b.setSummary("My Summary")

    Section s =new Section();
    s.setTitle("Section 1")

    Chapter c1=new Chapter();
    c1.setTitle("Chapter 1");
    Chapter c2=new Chapter();
    c2.setTitle("Chapter 2");

    s.addChapters(c1,c2);
    b.getSections().add(s)

    return book;
   }
 */

ObjectGraphBuilder builder= new ObjectGraphBuilder()
def book= builder.book(
    title:"Groovy is Action ",
    summary:"Groovy is  section "){
    section(title:"Section 1"){
        chapter(title:"Chapter 1")
        chapter(title:"Chapter 2")
        chapter(title:"Chapter 3")

    }
    section(title:"Section 2"){
        chapter(title:"Chapter 4")
        chapter(title:"Chapter 5")
        chapter(title:"Chapter 6")

    }
}
println book






Working with Builders JsonBuilder in Groovy Scripting groovy training telugu 63

 Watch This Video


https://youtu.be/oHZfdBgyWA0

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


//json.groovy
import groovy.json.JsonBuilder

JsonBuilder builder =new JsonBuilder()

builder.books{
    currentBook{
        title'The 4 Hour Work week'
        isbn'978-7888-88899'
        author(first:'Timothy',last:'Ferriss', twitter:'@tferriss')
        related'The 4 hour Body ,the 4 hour chef'
    }
    nextBook{
        title'#AskGaryvee'
        isbn'978-7888-889904-4556'
        author(first:'Gary',last:'Vaynerchuck', twitter:'@garyvee')
        related'Jab,Jab,Jab,Right Hook'
    }

}
println builder.toString()
println builder.toPrettyString()


Working with Builders MarkupBuilder Exercise in Groovy Scripting groovy training telugu 62

 Watch This Video


https://youtu.be/X3UkB5ONEAU

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

[Exercise] MarkupBuilder
XML
Use the MarkupBuilder to generate the following XML

<books>
    <book isbn="978-1935182443">
        <title>Groovy in Action 2nd Edition</title>
        <author>Dierk Koenig</author>
        <price>50.58</price>
    </book>
    <book isbn="978-1935182948">
        <title>Making Java Groovy</title>
        <author>Ken Kousen</author>
        <price>33.96</price>
    </book>
    <book isbn="978-1937785307">
        <title>Programming Groovy 2: Dynamic Productivity for the Java Developer</title>
        <author>Venkat Subramaniam</author>
        <price>28.92</price>
    </book>
</books>


HTML
With the same data from the xml version build an HTML page that lists that data.

Bonus
Using a FileWriter write the contents of the HTML from the MarkupBuilder to a file.



//CODE

//html.groovy

import groovy.xml.MarkupBuilder


def books =[
        [isbn:"978-1935182443",title:"Groovy in Action 2nd Edition",author:"Dierk Koeting",priece:50.58],
        [isbn:"978-1935182948",title:"Making Java Groovy",author:"Ken Kousen",priece:33.96],
        [isbn:"978-1937785307",title:"Programming Groovy 2:Dynamic Productivity for the Java Developer",author:"Venkat Subramaniam",priece:28.92]
]

MarkupBuilder builder = new MarkupBuilder()

builder.html{
    head{
        title("My Favorite Books")

    }
    body{
        h1("My Favorite Books")
        table{
            tr{
                th("ISBN")
                th("Title")
                th("Author")
                th("Price")

            }
            books.each {book ->
                tr{
                    td(book.isbon)
                    td(book.title)
                    td(book.author)
                    td(book.price)


                }

            }
        }


    }
}





//xml.groovy


import groovy.xml.MarkupBuilder

MarkupBuilder builder=new MarkupBuilder()
builder.books{
    book(isbn: "978-1935182443"){
        title("Groovy in Action 2nd Edition")
        author("Dierk Koeting")
        price("50.58")
    }
    book(isbn: "978-1935182948"){
        title("Making Java Groovy")
        author("Ken Kousen")
        price("33.96")
    }
    book(isbn: "978-1937785307"){
        title("Programming Groovy 2:Dynamic Productivity for the Java Developer")
        author("Venkat Subramaniam")
        price("28.92")
    }
}
























Working with Builders MarkupBuilder HTML in Groovy Scripting groovy training telugu 61

 Watch This Video


https://youtu.be/udYbS0gJ4Bw

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


html.groovy
import groovy.xml.MarkupBuilder

MarkupBuilder builder= new MarkupBuilder()
List courses =[
        [id:1, name:'Apache Groovy'],
        [id:2, name:'java']
]

builder.html{

    head{
        title'About Rashmi'
        description  'This is an about me page'
        keywords'Rashmi ,Groovy, Java'
    }
    body{
        h1'About Me'
        p'This is a bunch of text about me........'
        section{
            h2 'About Me'
            table{
                tr{
                    th 'id'
                    th'name'
                }
              courses.each {course ->
                  tr{
                      td course.id
                      td course.name
                  }

              }

            }
        }
    }

}

Working with Builders MarkupBuilder XML in Groovy Scripting groovy training telugu 60

 Watch This Video


https://youtu.be/2BQY0TjJxV4


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


xml.groovy

import groovy.xml.MarkupBuilder

MarkupBuilder builder=new MarkupBuilder()
builder.omitEmptyAttributes= true
builder.omitNullAttributes=true

builder.sports{
    sport(id:1){
        name'Baseball'

    }
    sport(id:2){
        name'Basketball'

    }
    sport(id:3){
        name'Football'

    }
    sport(id:4){
        name'Hockey'

    }
    sport(id:null,foo:''){
        name:''
    }


}

Compile Time Meta Programming Exercise in Groovy Scripting groovy training telugu 59

 Watch This Video

https://youtu.be/L2B_6uzvdsI

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

[Exercise] AST Transformations
AST Transformations

We looking at a lot of AST Transformations in this section. 
Now I want you to go through the documentation and 
find one that we didn't look at and see if you can get it to work on
 your own.





//Person.groovy

package clone

import groovy.transform.AutoClone

@AutoClone
class Person {
    String first
    String last
    List favItems
    Date since
}



//clonedemo.groovy

package clone

def p = new Person(first:'John', last:'Smith', favItems:['ipod', 'shiraz'], since:new Date())
def p2 = p.clone()

assert p instanceof Cloneable
assert p.favItems instanceof Cloneable
assert p.since instanceof Cloneable
assert !(p.first instanceof Cloneable)

assert !p.is(p2)
assert !p.favItems.is(p2.favItems)
assert !p.since.is(p2.since)
assert p.first.is(p2.first)

Compile Time Meta Programming @Builder in Groovy Scripting groovy training telugu 58

 Watch This Video


https://youtu.be/LWtnxu3NEgU


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

//Developer

package builder

import groovy.transform.ToString
import groovy.transform.builder.Builder

@Builder
@ToString(includeNames = true)
class Developer {

    String firstName
    String lastName
    String middleInitial
    String email
    Date hireDate
    List languages


}


//default.groovy

package builder

Developer dan =Developer
    .builder()
    .firstName("Dan")
    .lastName("Vega")
    .middleInitial("A")
    .email("danvega@gmail.com")
    .hireDate(new Date())
    .languages(["java","Groovy"])
    .build()
println dan
assert dan.firstName="Dan"
assert dan.lastName="Vega"
assert dan.languages.size()==2


Compile Time Meta Programming @CompileStatic in Groovy Scripting groovy training telugu 57

 Watch This Video

https://youtu.be/uxVhd8MwCmo


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


import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import groovy.transform.TypeCheckinMode

@CompileStatic

class SomeClass
{

String foo()

}

String bar()
{

}

@CompileStatic(TypeCheckingMode.SKIP)
void noReturn(){


}
}

Compile Time Meta Programming @Typechecked in Groovy Scripting groovy training telugu 56

 Watch This Video

https://youtu.be/R5S6JEVcTu8


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

package TypeChecked

import groovy.transform.TypeChecked

@TypeChecked
class Person {
    String firstname
    String lastname

    String getFullName(){

        "$firstname $lastname"
    }

}

Compile Time Meta Programming @Immutable in Groovy Scripting groovy training telugu 55

 Watch This Video


https://youtu.be/0kVxTGqSdrg

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




//Person.groovy
package Immutable

import groovy.transform.Immutable
import groovy.transform.ToString


@ToString
@Immutable
class Person {
    String first
    String last

}


//app.groovy
package Immutable
Person p= new Person(first:"Dan",last:"vega")
println p.toString()

p.first ="Andy"

Compile Time Meta Programming @Sortable in Groovy Scripting groovy training telugu 54

 Watch This Video


https://youtu.be/s8hMyeu0xZA

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

//Person.groovy



package theraldanvega

import groovy.transform.Canonical
import groovy.transform.Sortable
@Sortable(includes = ['last','first'])
@Canonical
class Person {
    String first
    String last
}



//app.groovy
package theraldanvega
Person p1=new Person("Katie","Vega")
Person p2=new Person("Dan","Vega")
Person p3=new Person("andy","Vega")
Person p4=new Person("Jan","Vega")
Person p5=new Person("Jason","NotaVega")

def vegas=[p1,p2,p3,p4,p5]
println vegas.toSorted()

Compile Time Meta Programming @Singleton in Groovy Scripting groovy training telugu 53

Watch This Video 

https://youtu.be/gQJrecEqK5k


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

//DatabaseConnection.groovy

@Singleton

class DatabaseConnection {


}




//app.groovy

DatabaseConnection db =new DatabaseConnection()
println db



Compile Time Meta Programming @Canonical in Groovy Scripting groovy training telugu 52

 Watch This Video

https://youtu.be/0omfYgUId0c


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



http://docs.groovy-lang.org/latest/html/gapi/index.html?groovy/lang/Range

//app.groovy

Person p1= new Person("Dan","vega","danvega@gmail.com")
Person p2= new Person("Dan","vega","danvega@gmail.com")

assert p1==p2

println p.toString()


//Person.groovy

import groovy.transform.Canonical


@Canonical

class Person{

String first
String last
String email

}

Compile Time Meta Programming @Tuple Constructor in Groovy Scripting groovy training telugu 51

 Watch This Video

https://youtu.be/ZHh7odsQhUk


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

http://docs.groovy-lang.org/latest/html/gapi/index.html?groovy/lang/Range

//app.groovy

Person p= new Person("Dan","vega","danvega@gmail.com")
println p.toString()


//Person.groocy

import groovy.transform.ToString
import groovy.transform.TupleConstructor

@ToString
@TupleConstructor

class Person{

String first
String last
String email

}

Compile Time Meta Programming @EqualsAndHashCode in Groovy Scripting groovy training telugu 50

 Watch This Video

https://youtu.be/MHehGPvtttY


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

http://docs.groovy-lang.org/latest/html/gapi/index.html?groovy/lang/Range

//Person.groovy

import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(exludes =["email"])
class Person {

String first
String last
String email

}

//app.groovy

Person p1= new Person(first:"Dan",last:"vega",email:"danvega@gmail.com")
Person p2= new Person(first:"Dan",last:"vega",email:"danvega@gmail.com")

assert p1==p2

Compile Time Meta Programming @ToString in Groovy Scripting groovy training telugu 49

 Watch This Video


https://youtu.be/QAuLSbC7uW8

---------------------------------------------------------------------------------
//Person.groovy

import groovy.transform.ToString
@ToString(includeNames = true, excludes =['email'])
class Person {

    String first
    String last
    String email

   
    }


//app.groovy

Person p= new Person(first:"Dan",last:"vega",email:"danvega@gmail.com")

println p.toString()

Exercise Runtime Metaprogrammings in Groovy Scripting groovy training telugu 48

 Watch This Video

https://youtu.be/_y-ZklOVVHo

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


[Exercise] Runtime Metaprogramming
GroovyObject

Create a class and implement each of the following methods from the GroovyObject Interface

invokeMethod

getProperty

setProperty

Expando

Create an Expando Class

Add some properties and methods to it

Knowing that a class's metaclass is an expando to create your own class and add properties and methods to it.

Times Two

Add a new method to the Integer class called `timesTwo`

This method should be available to any instance of Integer

What is another approach that we can take to create this method that would be a little more controlled?
 
//Code


//Developer.groovy

class Developer{
String first
String last
String email
List languages

Developer(){

}

def invokeMethod(String name,Object args){

println "invokeMethod()called with args $args"
}

defgetProperty(String property){
println"getProperty called..."
metaClass.getProperty(this,property)
}
void setProperty(String property,Object newValue){

println"setProperty() called with name $property and newValue $newValue"
metaClass.setProperty(this,property,newValue)
}
}

//GroovyObjectDemo.groovy


Developer developer = newDeveloper(first:"Dan",last:"Vega",email:"danvega@gmail.com")
developer.writeCode("Groovy")
println developer.first
developer.languages=["Groovy","Java]

//ExpandoDemo.groovy


Expando e = new Expando()

e.first="Dan"
e.last="Vega"
e.email="danvega@gmail.com"

e.getFullName={
"$first,$last"
}
println e.toString()
println e.getFullName()

@groovy.transform.ToString(includeNames =true)
class Person {

String first,last


}

Person p=new Person(first:"Dan,last:"Vega")
p.metaClass.email="danvega@gmail.com"
println p
println p.email


//SquaredDemo.groovy

Integer.metaClass.timesTwo={delegate *2}
println 2.timesTwo()
println 4.timesTwo()
println 5.timesTwo()
println 6.timesTwo()









MetaProgramming Intercept Cache Invoke Patternin Groovy Scripting groovy training telugu 47

 Watch This Video

https://youtu.be/VO3MosXEluc


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



//InterceptCacheInvoke.groovy

class Developer{

List languages =[]
def methodMissing(String name, args){

println "${name}() method was called..."
if(name.startsWith('write')){
String language = name.split("write")[1]
if(languages.contains(language)){
def impl ={Object [] theArgs ->
"I like to write code in $language"


}
getMetaClass()."$name"=impl
return impl(args)
}
}
}
}

Developer dan =new Developer()
dan.languages << "Groovy"
dan.languages << "Java"
println dan.metaClass.method.size()

dan.writeGroovy()
dan.writeGroovy()
dan.writeGroovy()

println dan.metaClass.method.size()

dan.writeJava()

dan.writeJava()

dan.writeJava()
println dan.metaClass.method.size()

MetaProgramming Category Class in Groovy Scripting groovy training telugu 46

 Watch This Video

https://youtu.be/rkZVfviJWW4


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

//catDemo.groovy

package therealdanvega

//String.metaClass.shout={-> toUpperCase()}
//println "Hello World!".shout()

use(StringCategory){
println "Hello,World!".shout()
}

println "Hello,World!".shout()

//StringCategory.groovvy


package therealdanvega

class StringCategory{
static String shout(String str){

str.toUpperCase()
}
}

//time.groovy
package therealdanvega
import groovy.time.TimeCategory

use(TimeCategory){
println 1.minute.from.now
println 10.hour.ago
def someDate=new Date()
println someDate -3.months

}


MetaProgramming Meta Class in Groovy Scripting groovy training telugu 45

 Watch This Video

https://youtu.be/E9qRy981Y0s


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

package therealdanvega

//meta class
//Expando e= new Expando()
//e.name='Dan'
//e.writeCode={-> println "$nsme loves to write code....."}
//e.writeCode


class Developer{

}

Developer dan= new Developer()
dan.metaClass.name="Dan"
dan.metaClass.wrutwCode={-> println "$name loves to write code...."}
dan.writeCode()


String.metaClass.shout={-> toUpperCase()}
println"hello dan".shout()

MetaProgramming Customizing the MOP in Groovy Scripting groovy training telugu 44

 Watch This Video

https://youtu.be/AIyNehq684s


------------------------------------------------------------------------------------------------------------------
//InvokeDemo.groovy

package therealdnvega

//this method is called when the method you called is not present in the groovy


class InvokeDemo{

def invokeMethod(String name,Object args){

return"called invokeMethod $name $args"

}

def test(){

return "method exists"

}
}
def invokeDemo = new InvokeDemo()
assert invokeDemo.test()=="method exists"
assert invokeDemo.someMethod()=="called invokeMEthod someMethod[]"

//GetPropertyDemo.groovy

package therealdnvega

class PropertyDemo{

def prop1="prop1"
def prop2="prop2"
def prop3="prop3"
def getProperty(String name){
println "getProperty() called with argumeny $name"
// return

if(metaClass.getProperty(this,name)){
return metaClass.getProperty(this,name)
}
else{
println "less do something fun with this property"
return "party time....
}
}
}
def pd=new PropertyDemo()
println pd.prop1
println pd.prop2
println pd.prop3
println pd.prop4


MetaProgramming Meta Object Protocol in Groovy Scripting groovy training telugu 43

 Watch This Video

https://youtu.be/pEIRoL0AnhU


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

Object Oriented Programming Exercise in Groovy Scripting groovy training telugu 42

 Watch This Video

https://youtu.be/Q1utvq3c4QQ


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


[Exercise] What makes up a class
Tweet

We are going to create a class that represents a single tweet.
This is an exercise both about code and starting to think about what
goes into building a class. There is no right or wrong answer here 
so don't be afraid to build your class how you see fit. I will go 
over in the review what I was thinking about when I built mine but 
again my answer is not the right one. 

What properties and methods go into building a tweet class? 

Bonus Points
How could you extract mentions and hashtags from the post text? 


class Tweet{
String post
String username
Date postDateTime

private List favorites=[]
private List retweets=[]
private List mentions=[]
private List hashtags=[]

void favorite(String username){

favorites<<username

}

List getFavorites(){

favorites
}

void retweets(String username){
retweets << username
}
List getRetweets(){
retweets
}
}

Tweet tweet= new Tweet(post:"This Groovy Course is Awesome",username:"@therealdanvega",postDateTime:new Date())
println tweet

tweet.favorite("@ApacheGroovy")
tweet.retweet("@ApacheGroovy")
println tweet.getFavorites()
println tweet.getRetweets()

Object Oriented Programming Groovy Beans in Groovy Scripting groovy training telugu 41

 Watch This Video

https://youtu.be/CB0yJC81JTA



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