Monday, June 17, 2013

Script template

// this is just intended to give a little more OOP structure to a script.
// put most code inside of run(), plus class variables and methods.

class Script {
    
    private String hello = "Hello"
    
    public Script run(Map options = [:]) {
        println "$hello ${options.name ?: 'World'}${shout(23)}"
        
        
        return this // for method chaining
    }
    
    private String shout(int times = 1) {
        return ('!' * times)
    }
    
}

new Script()
    .run()
    .run([name:'Crazy4Groovy'])

println 'DONE'

Friday, June 14, 2013

Simple Performance Benchmarking

int delayMillis = 100

Long startMillis = Calendar.instance.time.time

Thread.sleep(delayMillis)

Long passedMillis = Calendar.instance.time.time - startMillis

println passedMillis

assert passedMillis >= delayMillis

Wednesday, June 12, 2013

XML StreamingMarkupBuilder

import groovy.xml.StreamingMarkupBuilder

Map props = [addressid:'1', line1:'line-1_VALUE', line2:'line-2_VALUE']

def builder = new StreamingMarkupBuilder()

def address = {
     "address"(id: props.addressid) {
         "line-1"(props.line1)
         "line-2"(props.line2)
         "city"("city_VALUE") // typing wimped out...
         "state"("State_VALUE")
         "postal-code"("postal_VALUE")
     }
}

println builder.bind(address).toString() // something XML-compatible <address id="1">
...</address>

Thursday, June 6, 2013

Scrape image src's from a web page

import java.net.URLEncoder

String url = "http://msnbc.com"

String serviceUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22${URLEncoder.encode(url)}%22%20and%20xpath%3D%22%2F%2Fimg%22"
//println serviceUrl

String resultXML = serviceUrl.toURL().text // YQL will return the HTML page as XML!
//println resultXML

def root = new XmlSlurper().parseText(resultXML)

List imgSrcs = root.results.img.@src as List
imgSrcs = imgSrcs*.toString().unique()
//println imgSrcs.join('\n')

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)
*/