Wednesday, June 5, 2013

Immutable Maps (and Lists)

//source: http://royontechnology.blogspot.co.at/2010/06/creating-collection-with-single-element.html

//note the different constructor args; both return immutables

assert [2] == Collections.singletonMap(1, 1).collect {k,v ->
    return k+v
}

assert [3, 7] == Collections.unmodifiableMap([1:2, 3:4]).collect {k,v ->
    return k+v
}

Wednesday, May 29, 2013

Immutable (Annotation)

import groovy.transform.Immutable

@Immutable
class A {
    Date d // private final
    Date z // private final
    
    /* //no constructor def'n needed with @Immutable
    public A(Date D, Date Z) {
        d = D
        z = Z
    }*/
}

A a = new A(new Date(), new Date())

println a // see provided toString()

Date d1 = a.d // get property
assert (d1 == a.d)
d1.setHours(0) // mutate copy of property
assert (d1 != a.d) // this would not pass if class was mutable

println a.d
a.d.setHours(0) // no consequence/ignored
println a.d

Thursday, May 16, 2013

POJO to JSON : binding and serializing

//see: http://www.cowtowncoder.com/blog/archives/2009/01/entry_137.html
//see: https://github.com/FasterXML/jackson-databind

@Grapes([
/*
  @Grab(
    group='com.fasterxml.jackson.core', module='jackson-core', version='2.2.1'
  ),
  @Grab(
    group='com.fasterxml.jackson.core', module='jackson-annotations', version='2.2.1'
  ),
*/
  @Grab(
    group='com.fasterxml.jackson.core', module='jackson-databind', version='2.2.1'
  )
])
import com.fasterxml.jackson.databind.ObjectMapper

class Abc {
    int id, age
    String person
}

ObjectMapper mapper = new ObjectMapper();
Abc entry = mapper.readValue('{"id": 1, "person": "Steve", "age": "1"}', Abc.class);

assert entry1.id == 1
assert entry1.person == "Steve"
assert entry1.age == 1 //notice the auto type conversion from the JSON!

def entry2 = mapper.readValue('{"id": 1, "person": "Steve", "age": [1, {}, 3]}', LinkedHashMap.class);

assert entry2.id == 1
assert entry2.person == "Steve"
assert entry2.age.size() == 3
assert entry2.age[1].getClass().name == 'java.util.LinkedHashMap'


mapper.writeValue(new File("C:\\result.json"), entry1)  //--> {"id":1,"person":"Steve","age":1}
/*
  public void com.fasterxml.jackson.databind.ObjectMapper#writeValue(java.io.File, java.lang.Object)
  public void com.fasterxml.jackson.databind.ObjectMapper#writeValue(java.io.OutputStream, java.lang.Object)
  public void com.fasterxml.jackson.databind.ObjectMapper#writeValue(java.io.Writer, java.lang.Object)
*/

Monday, January 7, 2013

Simple Timer & TimerTask

public class MyTask extends TimerTask{
    Closure onFinish
    int count, repeat
    
    public MyTask(Closure onFinish = {}, int repeat = 1){
        this.onFinish = onFinish
        this.repeat = repeat
        this.count = 1
    }
    
    private void toDo(){
        println "count-> ${count}"      
    }
    
    private void checkFinished() {
        if (count > repeat) { //this is the condition when you want to stop the task.
            println "DONE-> before ${count}"
            onFinish()
            return
        }
    }
    
    @Override
    public void run() {        
        toDo()
        count++
        checkFinished()
    }
}

public class MyScheduler {
    public static void doIt( Closure then = {} ) {
        Timer timer = new Timer()
        MyTask myTask = new MyTask( repeat:3, 
            onFinish:{ 
                timer.cancel() // stop the timer
                then() // do the callback
            })
        int delayStartMs = 2000
        int intervalMs = 1000
        timer.schedule(myTask, delayStartMs, intervalMs)
    }
}

MyScheduler.doIt( { println "#1 DONE" } )
MyScheduler.doIt( { println "#2 DONE" } )

Run OS command

//windows
String cmd = "ping google.com"

String[] command = ["CMD", "/C", cmd] as String[]
ProcessBuilder builder = new ProcessBuilder(command)
Process process = builder.start()

println process.text

println "*"*5+"DONE"+"*"*5

Sunday, January 6, 2013

String padding with zeros

String.metaClass.zeropad = { Integer padding = 0 ->
    return ("0" * Math.max(0, (padding ?: 0) - delegate.size())) + delegate
}
Integer.metaClass.zeropad = { Integer padding = 0 ->
    return delegate.toString().zeropad(padding)
}

assert "123".zeropad()     == "123"
assert "123".zeropad(null) == "123"
assert "123".zeropad(5)    == "00123"
assert "1234".zeropad(5)   == "01234"
assert "12345".zeropad(5)  == "12345"
assert "123456".zeropad(5) == "123456"

assert 123.zeropad()     == "123"
assert 123.zeropad(null) == "123"
assert 123.zeropad(5)    == "00123"
assert 1234.zeropad(5)   == "01234"
assert 12345.zeropad(5)  == "12345"
assert 123456.zeropad(5) == "123456"

Thursday, November 15, 2012

@Delegate vs. Extends

// "favor composition over inheritance" ~Effective Java

class Parent {
    def getAll() {
        String resp = ""
        2.times {
            resp += get(it)
        }
        return resp
    }
    
    def get(def i) {
        "get PARENT $i\n"
    }
}

class Child1 extends Parent {
    def get(def i) {
        "get CHILD $i\n" // is used by parent's getAll
    }
}

class Child2 {
    @Delegate Parent p = new Parent() // decorated Parent instance
    
    def get(def i) {
        "get CHILD $i\n" // not used by parent's getAll
    }
}

Parent c1 = new Child1()
assert c1.getAll() == "get CHILD 0\nget CHILD 1\n" // calls child's get()
assert c1.get(0) == "get CHILD 0\n"

//Parent c2 = new Child2() // Child2 is not a Parent!
Child2 c2 = new Child2()
assert c2.getAll() == "get PARENT 0\nget PARENT 1\n" // calls parent's get()
assert c2.get(0) == "get CHILD 0\n"