-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestTemplateBuilder.groovy
82 lines (78 loc) · 1.75 KB
/
RestTemplateBuilder.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@Grapes(
@Grab(group='org.springframework', module='spring-web', version='3.2.3.RELEASE')
)
import org.springframework.web.client.*
import groovy.json.JsonSlurper
class MyRestTemplateBuilder {
def url, method, vars, checkpoint, retType
def make = {
this
}
def _method = { m ->
checkpoint = "method"
method = m
this
}
def _retType = { t ->
retType = t
this
}
def a = { query ->
this
}
def GET = { to ->
this._method "GET"
}
def POST = { to ->
this._method "POST"
}
def with = { p ->
this
}
def params = { m ->
vars = Eval.me(m)
this
}
def and = {
this
}
def give = {
this
}
def back = { t ->
retType = t
this
}
def methodMissing(String name, args) {
if (checkpoint == "method") this.url = name; this.checkpoint = null
return this
}
def propertyMissing(String name) {
this.url = name
return this
}
def execute(clos) {
this.with(clos)
this._do()
}
def _do() {
def rt = new RestTemplate()
def res = rt."${method.toLowerCase()}ForObject"(url, String, vars ?: [:])
switch (retType.toUpperCase()) {
case "JSON":
new JsonSlurper().parseText(res)
break
case "XML":
new XmlSlurper().parseText(res)
break
default:
res
}
}
}
def json = new MyRestTemplateBuilder().execute {
make a GET to "http://localhost/groovy/controller.json?id={id}" with params "[id: 1]" and give back "json"
}
println json
assert json instanceof Map
assert json.result