Working with the GDK

This is a bits and pieces section regarding programming in Groovy the stuff that I have not covered in other sections, like files and directories, file io, threads, templates and dates.

I will update this section from time to time as my experience with Groovy grows.

Files and Directories

This section covers writing and read from files and how to create and deleted and moe aropund directories.

File examples
// create a new file
def file = new File('dummy.txt')
file.write("This is some text\n")

// append to a file
file.append("I am adding some more text\n")

// reading a file
List lines = file.readLines()
lines.each { line -> println line }                 // using closures

// list files in the directory
println "----------------------------------"
String dir = '.'
new File(dir).eachFile { file1 ->                   // can also use eachFileRecurse
    if (file1.isFile()){
        println file1.name
    }
}

Note: Directories in Groovy are represented as a file.
Directory examples
// List files and directories
List hidden = []
new File('.').eachFile { file ->                     // Directories in Groovy are files.
    if(file.isFile()){
        println file.name + " is a file"
    }
    if (file.isDirectory()){
        println file.name + " is a directory"
    }
    if (file.isHidden()){
        hidden << file.name
    }
}

println hidden

// list directories only
new File('.').eachDir { dir ->
        println dir.name
}

// create directories
new File("dummy").mkdir()
new File("one/two/three").mkdirs()

// delete directory
new File("dummy").deleteDir()
IO examples (System.in)
String team

println "Please Enter Your Favorite Sports Team"
System.in.withReader { reader -> team = reader.readLine() }                 // use a closure

println "Your favorite team is: $team"

Threads

Threads in Java are difficult to work with, but Groovy simplifies them.

Thread basics
def t = new Thread(){ /* do something */ }                 // closures implement Runnable
t.start()

// You can pass closures to the Thread class
Thread.start { /* do something */ }
Thread.start('thread-name') { /* do something */ }

Thread.startDaemon { /* do something */ }
Thread.startDaemon {}('thread-name') { /* do something */ }
Producer/Consumer example
BlockingQueue sharedQueue = [] as LinkedBlockingQueue

Thread.start('push') {
    10.times {
        try {
            println "${Thread.currentThread().name}\t: ${it}"
            sharedQueue << it
            sleep 100
        } catch (InterruptedException ignore){
            // do something here
        }
    }
}

Thread.start('pop') {
    for( i in 0..9){
      sleep 125
        println "${Thread.currentThread().name}\t ${sharedQueue.take()}"
    }
}

Templates

Groovy templates processes template source files substituting variables and expressions into placeholders in a template source text to produce the desired output.

Template example
// 3 components to building a dynamic template

// 1. Engine (SimpleTemplateEngine)
// 2. Template (the email)
// 3. Data Bindings (The Data to insert into the dynamic portions of our email)

// new SimpleTemplateEngine(true)
SimpleTemplateEngine engine = new SimpleTemplateEngine(true)
Template template = engine.createTemplate( new File('dynamic-email.txt') )

// show error if properties are missing
Map bindings = [
        firstName: "Paul",
        lastName: "Valle",
        first_house_year: 1994,
        houses: [
            [location:'London'],
            [location:'Aylesbury'],
            [location:'Milton Keynes']
        ]
]

println template.make(bindings)


dynamic-email.txt - The template file
----------------------------------------------------------
Dear $firstName $lastName,
You currently have ${houses.size()} places where you have lived you're first house was brought in $first_house_year.

<% houses.each { house ->
    println "\t> $house.location"
} %>


Thank You
Where you lived

Dates

Some examples of getting and manipulating dates in Groovy

Dates example
Date today = new Date()
println today

Date bday = new Date("04/04/1999")
println bday

println bday.format('d-MMM-Y')

// add & subtract
Date oneWeekFromToday = today.plus(7)   // or can use + 7
Date oneWeekAgo = today.minus(7)        // or can use - 7
println oneWeekFromToday
println oneWeekAgo

// down to and up to
println "--------------------------------------"
oneWeekFromToday.downto(today){
    println it
}
println "--------------------------------------"

// create a range for dates
Range twoWeeks = oneWeekAgo..oneWeekFromToday
twoWeeks.each { println it}
println "--------------------------------------"

// next and previous
Date newYear = new Date('01/01/2018')
println newYear.next()
println newYear.previous()
println "--------------------------------------"

Date rightnow = new Date()
println rightnow.toTimestamp()