forked from netconomy/restflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestFlow.groovy
561 lines (513 loc) · 18.9 KB
/
RestFlow.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package net.netconomy.tools.restflow.dsl
import net.netconomy.tools.restflow.impl.*
import org.apache.http.client.CookieStore
import org.apache.http.client.config.CookieSpecs
import org.apache.http.client.methods.*
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.ssl.SSLContextBuilder
import org.apache.http.ssl.TrustStrategy
import java.awt.*
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.List
/**
* Represent the state of a REST flow. This includes a cookie store, the
* base template request, a reference to the last response.
*
* @since 2018-10-14
* @author Raffael Herzog (r.herzog@netconomy.net)
*/
class RestFlow {
private static final Object GLOBAL_LOCK = new Object()
private static volatile RestFlow GLOBAL = null
private final ProfileLoader profileLoader
private final CloseableHttpClient httpBackend
final Cookies cookies = new Cookies()
/**
* @deprecated Use {@link #cookies} instead.
*/
@Deprecated
final CookieStore cookieStore = cookies.store
/**
* A list of {@link PreRequestHandler}s that may modify the request
* configuration before each HTTP request.
*/
final List<PreRequestHandler> preRequestHandlers = new ArrayList<>()
/**
* Allows access to the this instance by a different name. Useful in
* closures that delegate to another instance, e.g.
* <code>flow.host</code> in a closure delegating to
* {@link RequestConfig}, where <code>host</code> would delegate to the
* request's <code>host</code>.
*/
final RestFlow flow = this
/**
* A map for extension objects. Any reference to a unknown property will
* also look here (using {@code propertyMissing( )}.
*/
final Map<String, Object> ext = new LinkedHashMap<>()
final CommLog log
/**
* The default charset for decoding text responses.
*/
Charset defaultResponseCharset
/**
* The current base request.
*/
RequestConfig request
/**
* The response of the last HTTP request or {@code null}.
*/
Response response
RestFlow(ProfileLoader profileLoader, CommLog log = new PrintCommLog()) {
this.profileLoader = profileLoader ?: new ProfileLoader(
Thread.currentThread().contextClassLoader ?: RestFlow.classLoader)
this.log = log
SSLContextBuilder sslCtxBuilder = new SSLContextBuilder()
sslCtxBuilder.loadTrustMaterial(null, new TrustStrategy() {
@Override
boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true
}
})
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
sslCtxBuilder.build(), {n, session -> true})
httpBackend = HttpClients.custom().
setSSLSocketFactory(sslSocketFactory).
setDefaultRequestConfig(org.apache.http.client.config.RequestConfig.custom().
setCookieSpec(CookieSpecs.STANDARD).
build()).
disableRedirectHandling().
setDefaultCookieStore(NoCookiesStore.INSTANCE).
addInterceptorLast(new LogRequestInterceptor(this)).
build()
reset()
}
/**
* Get the global RESTflow instance creating it if necessary.
*/
static RestFlow getGlobalInstance() {
if (GLOBAL == null) {
synchronized (GLOBAL_LOCK) {
if (GLOBAL == null) {
GLOBAL = new RestFlow(null)
}
}
}
return GLOBAL
}
/**
* Run the closure in the global {@code RestFlow} instance.
*
* @return The result of the closure.
*
* @deprecated The global instance will be removed.
*/
@Deprecated
static <T> T global(@RestDsl(RestFlow) Closure<T> closure) {
DslUtil.invokeDelegateFirst(closure, getGlobalInstance())
}
/**
* Run the closure in a new RESTflow instance and return the instance.
*
* @return The new RESTflow instance initialized by the closure.
*/
RestFlow init(@RestDsl(RestFlow) Closure closure) {
DslUtil.invokeDelegateFirst(closure, this)
return this
}
/**
* Run the closure in this RESTflow instance.
*
* @return The result of the closure.
*/
def <T> T run(@RestDsl(RestFlow) Closure<T> closure) {
DslUtil.invokeDelegateFirst(closure, this)
}
/**
* Reset the RESTflow instance to the default state, clear all customisations.
*/
void reset() {
cookies.store.clear()
ext.clear()
defaultResponseCharset = StandardCharsets.UTF_8
request = new RequestConfig()
response = null
profileLoader.applyAuto(this)
}
/**
* Apply the named extension to this RESTflow instance.
*
* @param args A map of arguments.
*
* @param name The name of the extension.
*/
void apply(Map<String, Object> args = null, String name) {
profileLoader.apply(this, name, args)
}
/**
* Add a pre-request handler to this RESTflow instance.
*
* @param closure The closure to be executed before each request; the
* delegate will be set to the RESTflow instance, the request configuration of the request to be run is passed as parameter.
*/
void preRequestHandler(@RestDsl(RequestConfig) Closure<?> closure) {
preRequestHandlers.add(new PreRequestHandler() {
@Override
void preRequest(RestFlow flow, RequestConfig requestConfig) {
DslUtil.invokeDelegateFirst(closure, requestConfig)
}
})
}
/**
* Configure the current base request using the closure. In most cases,
* there is just one base request, however, this is actually a stack. An
* empty base request can be temporarily pushed using {@link
* RestFlow#group(groovy.lang.Closure) group()}.
*
* @return The result of the closure
*
* @deprecated use {@link #request(Closure)} instead
*/
@Deprecated
<T> T baseRequest(@RestDsl(RequestConfig) Closure<T> closure) {
request(closure)
}
/**
* @deprecated use {@link #request} instead.
*/
@Deprecated getBaseRequest() {
request
}
/**
* Configure the current base request using the closure. In most cases,
* there is just one base request, however, this is actually a stack. An
* empty base request can be temporarily pushed using {@link
* RestFlow#group(groovy.lang.Closure) group()}.
*
* @return The result of the closure
*/
def <T> T request(@RestDsl(RequestConfig) Closure<T> closure) {
DslUtil.invokeDelegateFirst(closure, request)
}
/**
* Pushes an empty base request applying the given path on the stack and
* runs the closure and finally pops it. Useful for grouping several
* request that apply to the same base path.
*
* @return The result of the closure.
*/
def <T> T group(String path, @RestDsl(RestFlow) Closure<T> closure) {
request = new RequestConfig(request)
try {
request.path path
DslUtil.invokeDelegateFirst(closure, this)
} finally {
request = request.parent
}
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP GET request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response GET(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpGetWithEntity()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP GET request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response GET(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpGetWithEntity()}, path, null, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP PUT request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response PUT(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpPut()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP PUT request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response PUT(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpPut()}, path, null, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP POST request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response POST(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpPost()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP POST request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response POST(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpPost()}, path, null, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP DELETE request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response DELETE(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpDeleteWithEntity()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP DELETE request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response DELETE(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpDeleteWithEntity()}, path, null, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP HEAD request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response HEAD(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpHead()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP HEAD request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response HEAD(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpHead()}, path, null, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP OPTIONS request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response OPTIONS(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpOptions()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP OPTIONS request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response OPTIONS(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpOptions()}, path, null, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP TRACE request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response TRACE(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpTrace()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP TRACE request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response TRACE(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpTrace()}, path, null, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP PATCH request. The response will be available as in
* the field {@code response}.
*
* @param query Query parameters.
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response PATCH(Map<String, ?> query, String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpPatch()}, path, query, closure)
}
/**
* Push a new request on the stack, configure it using the closure and
* submit it as HTTP PATCH request. The response will be available as in
* the field {@code response}.
*
* @param path The path of the request.
* @param closure The configuration clsoure
*
* @return The response.
*/
Response PATCH(String path, @RestDsl(RequestConfig) Closure closure = null) {
__executeRequest({new HttpPatch()}, path, null, closure)
}
private Response __executeRequest(Closure<? extends HttpRequestBase> createRequest, String path, Map<String, ?> query, Closure closure) {
RequestConfig request = new RequestConfig(request, path)
if (query) {
request.query query
}
DslUtil.invokeDelegateFirst(closure, request)
response = RequestExecution.execute(httpBackend, createRequest.call(), this, request)
}
/**
* Announce some activity. This is mainly used for the IDEA plugin. The last logged
* activity will be shown in the log tree and whenever another nodes is appended,
* the activity will be removed. This is useful to inform the user that the script
* is doing something other than HTTP (a classic example would be a countdown).
*
* Example:
*
* <pre>
* GET('...')
* (5..1).each {activity "Continuing in $it s"; sleep 1000}
* GET('...')
* </pre>
*/
void activity(Object... msg) {
log.activity(msg)
}
/**
* Pin some information. This is mainly used for the IDEA plugin. The information
* will be shown as a node in the request tree. This way, you can point out some
* fact that you/the user is probably most interested in, e.g. the amount of
* search results.
*
* Example:
*
* <pre>
* GET('search', q: 'test')
* pin "Found ${result.json.results?.size()} items"
* </pre>
*/
void pin(Object... msg) {
log.pin(msg)
}
/**
* Retrieve a password. This will first try to retrieve the password
* from a system property named {@code restflow.auth.<name> .<username>},
* then it will attempt to show a password prompt using a Swing dialog,
* and finally, if this throws a {@code HeadlessException}, it will try
* to read the password from the console.
*
* @param username The username
* @param name A name for the password, shown in the password prompt
* or used to lookup the system property.
*
* @return The password or {@code null}.
*/
String promptPassword(String username, String name) {
String password = PasswordPrompt.nonInteractivePassword(username, name)
boolean retryPasswordPrompt = true
if (password == null && retryPasswordPrompt) {
try {
password = PasswordPrompt.swingPasswordPrompt(username, name)
retryPasswordPrompt = false
} catch (HeadlessException e) {
log.info "Cannot show password dialog: $e"
}
}
if (password == null && retryPasswordPrompt) {
try {
password = PasswordPrompt.consolePasswordPrompt(username, name)
} catch (IOException e) {
log.info "Cannot read password from console: $e"
}
}
if (password == null) {
log.warn "No password for $username ($name)"
}
return password
}
def propertyMissing(String name) {
if (ext.containsKey(name)) {
return ext.get(name)
} else {
throw new MissingPropertyException(name, getClass())
}
}
}