// 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 Data {
    int ival
    String sval
    @Override
    String toString() {
        return String.format("(%d,%s)", ival, sval)
    }
}

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()
}

def testGetOne(urlstr, v) {
    response = interact("GET", urlstr + "/" + v, "application/json", null)
    gson = new Gson()
    d = gson.fromJson(response, Data.class)
    println(d)
}

def testGetAll(urlstr) {
    response = interact("GET", urlstr, "application/json", null)
    gson = new Gson()
    t = new TypeToken<TreeMap<String,ArrayList<Data>>>(){}.getType()
    result = gson.fromJson(response, t)
    println(result.get("data"))
}

def testAdd(urlstr, d1) {
    gson = new Gson()
    request = gson.toJson(d1)
    response = interact("POST", urlstr + "/", "application/json", request)
    d2 = gson.fromJson(response, Data.class)
    println(d2)
}

urlstr = "http://localhost:8003/Server/data"
testGetOne(urlstr, 2)
testGetAll(urlstr)
testAdd(urlstr, new Data(ival: 4, sval: "DDDD"))
testGetAll(urlstr)
