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"

Monday, November 5, 2012

DNS lookup - timed

int maxTimeout = 30000
int minTimeout = 15000

List domainList = [
    'gmail.com', 'google.co.uk', 'google.com', 'bbc.co.uk', 'cnn.com', 'java.oracle.com',
    'facebook.com', 'twitter.com', 'oracle.com', 'zen.co.uk', 'java.net', 'www.scala-lang.org',
    'plus.google.com', 'guardian.co.uk', 'linkedin.com', 'www.typesafe.com', 'www.yahoo.com',
    'www.ibm.com', 'www.apache.org', 'www.adobe.com', 'www.microsoft.com', 'www.stackoverflow.com',
    'www.apple.com', 'groovy.codehaus.org', 'java.oracle.com', 'www.telegraph.co.uk', 'www.jroller.com',
    'www.dell.com', 'www.samsung.com', 'www.amazon.co.uk', 'docs.oracle.com', 'www.infoq.com',
    'www.devoxx.com', 'www.qconlondon.com', 'www.smashingmagazine.com', 'en.wikipedia.com' ]

int count = 1
while (true) {
    int idx = (int)( Math.random() * domainList.size )    
    println "[$count]  nslookup ${domainList[idx]}"
    def process = "nslookup ${domainList[idx]}".execute()
    println "Found text ${process.text}"
    
    int sleepTime = (int)( minTimeout + Math.random() * ( maxTimeout  - minTimeout))
    Thread.sleep( sleepTime );
    
    ++count
}