// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import com.google.gson.reflect.*
import com.google.gson.*

class Message {
    String text;
}

def interact(method, urlstr, typ, body) {
    con = (new URL(urlstr)).openConnection()
    con.setRequestMethod(method)
    con.addRequestProperty("accept",  typ)
    if(body != null) {
        con.addRequestProperty("content-type", typ)
        con.setDoOutput(true)
        con.outputStream.write(body.bytes)
    }
    sb = new StringBuilder()
    con.connect()
    if(con.responseCode.intdiv(100) == 2) {
        is = con.inputStream
        b = new byte[1000]
        while((n = is.read(b)) >= 0) {
            sb.append(new String(b, 0, n))
        }
        is.close()
    } else {
        println("Error: ${con.responseCode} ${con.responseMessage}")
    }
    con.disconnect()
    return sb.toString()
}

gson = new Gson()
msg = new Message(text: "Hi from Groovy!")
request1 = gson.toJson(msg)
response1 = interact("POST", "http://localhost:8001/msgs", "application/json", request1)
response2 = interact("GET", "http://localhost:8001/msgs", "application/json", null)
t = new TypeToken<TreeMap<String,ArrayList<Message>>>(){}.getType()
msgs = gson.fromJson(response2, t)
for(msg in msgs.get("message")) {
    println(msg.text)
}
