-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApiController.groovy
980 lines (837 loc) · 31.8 KB
/
ApiController.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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
/**
* Api Controler
*
* API for third party applications to interact
* with GSCF
*
* @author Jeroen Wesbeek <work@osx.eu>
* @since 20120328
* @package api
*
* Revision information:
* $Rev$
* $Author$
* $Date$
*/
package api
import grails.plugins.springsecurity.Secured
import grails.converters.JSON
import dbnp.authentication.SecUser
import dbnp.studycapturing.*
import org.codehaus.groovy.grails.web.json.JSONObject
import org.dbnp.gdt.*
import org.codehaus.groovy.grails.plugins.web.taglib.ValidationTagLib
class ApiController {
def authenticationService
def apiService
def dataSource
def validationTagLib = new ValidationTagLib()
/**
* index closure
*/
def index = {
}
/**
* authenticate with the api using HTTP_BASIC authentication
*
* This means
* 1. the client should send the HTTP_BASIC authentication header
* which is an md5 hash of the username + password concatenated:
*
* Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
*
* 2. the user used to authenticate with the API should have
* the ROLE_CLIENT role
*
* @param string deviceID
*/
@Secured(['ROLE_CLIENT', 'ROLE_ADMIN'])
def authenticate = {
println "api::authenticate: ${params}"
// see if we already have a token on file for this device id
String deviceID = (params.containsKey('deviceID')) ? params.deviceID : ''
SecUser user = authenticationService.getLoggedInUser()
Token token = Token.findByDeviceID(deviceID)
// generate a new token if we don't have a token on file
def result = [:]
try {
if (!token) {
// generate a token for this device
token = new Token(
deviceID : deviceID,
deviceToken : UUID.randomUUID().toString(),
user : user,
sequence : 0
).save(flush: true)
// create result
response.status = 200
result = ['token':token.deviceToken, 'sequence':token.sequence]
} else if (user != token.user) {
response.status = 409
result = ['error':"the deviceID '${deviceID}' is already in use by user '${token.user}', please use user '${token.user}' to authenticate or use another deviceID"]
} else {
result = ['token':token.deviceToken, 'sequence':token.sequence]
// set output headers
response.status = 200
}
} catch (Exception e) {
// caught an error
response.status = 500
result = ['error':e.getMessage()]
}
response.contentType = 'application/json;charset=UTF-8'
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
}
/**
* get all readable studies
*
* @param string deviceID
* @param string validation md5 sum
*/
def getStudies = {
println "api::getStudies: ${params}"
String deviceID = (params.containsKey('deviceID')) ? params.deviceID : ''
String validation = (params.containsKey('validation')) ? params.validation : ''
// check
if (!apiService.validateRequest(deviceID,validation)) {
response.sendError(401, 'Unauthorized')
} else {
def user = Token.findByDeviceID(deviceID)?.user
def readableStudies = Study.giveReadableStudies(user)
def studies = []
// iterate through studies and define resultset
readableStudies.each { study ->
// get result data
studies[ studies.size() ] = [
'token' : study.UUID,
'code' : study.code,
'title' : study.title,
'description' : study.description,
'subjects' : study.subjects.size(),
'species' : study.subjects.species.collect { it.name }.unique(),
'assays' : study.assays.collect { it.name }.unique(),
'modules' : study.assays.collect { it.module.name }.unique(),
'events' : study.events.size(),
'uniqueEvents' : study.events.collect { it.toString() }.unique(),
'samplingEvents' : study.samplingEvents.size(),
'uniqueSamplingEvents' : study.samplingEvents.collect { it.toString() }.unique(),
'eventGroups' : study.eventGroups.size(),
'uniqueEventGroups' : study.eventGroups.collect { it.name }.unique(),
'samples' : study.samples.size(),
'subjectGroups' : study.subjectGroups.size(),
'uniqueSubjectGroups' : study.subjectGroups.collect { it.name }.unique()
]
}
def result = [
'count' : studies.size(),
'studies' : studies
]
response.status = 200
response.contentType = 'application/json;charset=UTF-8'
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
}
}
/**
* get all subjects for a study
*
* @param string deviceID
* @param string studyToken
* @param string validation md5 sum
*/
def getSubjectsForStudy = {
println "api::getSubjectsForStudy: ${params}"
Study study = getStudy()
// wrap result in api call validator
render apiService.executeApiCall(params,response,'study',study,{
def subjects = apiService.flattenDomainData( study.subjects )
// define result
def result = [
'count' : subjects.size(),
'subjects' : subjects
]
return result
})
}
/**
* get all assays for a study
*
* @param string deviceID
* @param string studyToken
* @param string validation md5 sum
*/
def getAssaysForStudy = {
println "api::getAssaysForStudy: ${params}"
Study study = getStudy()
// wrap result in api call validator
render apiService.executeApiCall(params,response,'study',study,{
def assays = apiService.flattenDomainData( study.assays )
// define result
def result = [
'count' : assays.size(),
'assays' : assays
]
return result
})
}
/**
* get all eventGroups for a study
*
* @param string deviceID
* @param string studyToken
* @param string validation md5 sum
*/
def getEventGroupsForStudy = {
println "api::getEventGroupsForStudy: ${params}"
Study study = getStudy()
// wrap result in api call validator
render apiService.executeApiCall(params,response,'study',study,{
def eventGroups = apiService.flattenDomainData( study.eventGroups )
// define result
def result = [
'count' : eventGroups.size(),
'eventGroups' : eventGroups
]
return result
})
}
/**
* get all events for a study
*
* @param string deviceID
* @param string studyToken
* @param string validation md5 sum
*/
def getEventsForStudy = {
println "api::getEventsForStudy: ${params}"
Study study = getStudy()
// wrap result in api call validator
render apiService.executeApiCall(params,response,'study',study,{
def events = apiService.flattenDomainData( study.events )
// define result
def result = [
'count' : events.size(),
'events': events
]
return result
})
}
/**
* get all samplingEvents for a study
*
* @param string deviceID
* @param string studyToken
* @param string validation md5 sum
*/
def getSamplingEventsForStudy = {
println "api::getSamplingEventsForStudy: ${params}"
Study study = getStudy()
// wrap result in api call validator
render apiService.executeApiCall(params,response,'study',study,{
def samplingEvents = apiService.flattenDomainData( study.samplingEvents )
// define result
def result = [
'count' : samplingEvents.size(),
'samplingEvents': samplingEvents
]
return result
})
}
/**
* get all samples for a study
*
* @param string deviceID
* @param string studyToken
* @param string validation md5 sum
*/
def getSamplesForStudy = {
println "api::getSamplesForStudy: ${params}"
Study study = getStudy()
// wrap result in api call validator
render apiService.executeApiCall(params,response,'study',study,{
def studySamples = study.samples
def samples = apiService.flattenDomainData( studySamples )
def result = [
'count' : samples.size(),
'samples' : samples
]
return result
})
}
/**
* get all samples for an assay
*
* @param string deviceID
* @param string assayToken
* @param string validation md5 sum
*/
def getSamplesForAssay = {
println "api::getSamplesForAssay: ${params}"
// fetch assay
String assayToken = (params.containsKey('assayToken')) ? params.assayToken : ''
def assay = Assay.findWhere(UUID: assayToken)
// wrap result in api call validator
render apiService.executeApiCall(params,response,'assay',assay,{
def samples = apiService.flattenDomainData( assay.samples )
def result = [
'count' : samples.size(),
'samples' : samples
]
return result
})
}
def getSubjectGroupsForStudy = {
Study study = getStudy()
render apiService.executeApiCall(params,response,'study',study,{
def studySubjectGroups = study.subjectGroups.findAll()
[
'count' : studySubjectGroups.size(),
'subjectGroups' : getSubjectGroups(studySubjectGroups)
]
})
}
private Study getStudy() {
Study.findWhere(UUID: getStudyToken())
}
private String getStudyToken() {
(params.containsKey('studyToken')) ? params.studyToken : ''
}
private ArrayList<Map<String, ArrayList<Map<String, String, Integer>>>> getSubjectGroups(studySubjectGroup) {
studySubjectGroup.collect {
[name: it.name, subjectEventGroups: it.subjectEventGroups.collect {
[startTime: it.startTime, description: it.description, eventGroupId: it.eventGroup.id]
}]
}
}
/**
* get all measurement data from a linked module for an assay
*
* @param string deviceID
* @param string assayToken
* @param string validation md5 sum
*/
def getMeasurementDataForAssay = {
println "api::getMeasurementDataForAssay: ${params}"
// fetch assay
String assayToken = (params.containsKey('assayToken')) ? params.assayToken : ''
def assay = Assay.findWhere(UUID: assayToken)
// fetch user based on deviceID
String deviceID = (params.containsKey('deviceID')) ? params.deviceID : ''
def user = Token.findByDeviceID(deviceID)?.user
// wrap result in api call validator
apiService.executeApiCall(params,response,'assay',assay,{
// define sample measurement data matrix
def matrix = [:]
def measurementData = apiService.getMeasurementData(assay, user).toArray()
//def measurementMetaData = apiService.getMeasurementData(assay, user)
// iterate through measurementData and build data matrix
try {
measurementData.each { data ->
try {
if (!matrix.containsKey(data.sampleToken)) matrix[data.sampleToken] = [:]
matrix[data.sampleToken][data.measurementToken] = data.value
} catch (Exception e) {
// it seems that some measurement data does not contain a sample token?
println "getMeasurementDataForAssay error for data of assay '${assay.name}' (token '${assayToken}', module: '${assay.module.name}'): ${e.getMessage()}"
println data.dump()
}
}
// define result
def result = [:]
result = [
'measurements' : matrix
]
// set output headers
response.status = 200
response.contentType = 'application/json;charset=UTF-8'
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
} catch (Exception e) {
println "getMeasurementDataForAssay exception: ${e.getMessage()}"
response.sendError(500, "module '${assay.module}' does not properly implement getMeasurementData REST specification (${e.getMessage()})")
}
})
}
/**
* get all measurement data from a linked module for an assay
*
* @param string deviceID
* @param string assayToken
* @param string validation md5 sum
*/
def getPlainMeasurementDataForAssay = {
println "api::getPlainMeasurementDataForAssay: ${params}"
// fetch output parameter, features: feature metadata, subject: subject metadata
// measurements: subjectname, starttime, featurename, value, all: all (default)
String outputOptions = ['all', 'measurements', 'subjects', 'features']
String output = params.containsKey('dataSelection') ? params.dataSelection : ''
if(!outputOptions.contains(output)) {
output = "all"
}
// fetch assay
String assayToken = (params.containsKey('assayToken')) ? params.assayToken : ''
def assay = Assay.findWhere(UUID: assayToken)
// fetch user based on deviceID
String deviceID = (params.containsKey('deviceID')) ? params.deviceID : ''
def user = Token.findByDeviceID(deviceID)?.user
// wrap result in api call validator
apiService.executeApiCall(params,response,'assay',assay,{
// define data elements
def measurements
def features
def subjects
// get subjects (metadata) data for assay
def subjectMap = [:]
assay.parent.subjects.each() { Subject subject ->
def fieldMap = [:]
subject.giveFields().each() { field ->
// skip field 'name' since this is already the key
if (!field.name.equals('name')) {
fieldMap.put(field.name, subject.getFieldValue(field.name).toString())
}
}
subjectMap.put(subject.name, fieldMap)
}
// iterate through measurementData and build data matrix
try {
if (output.equals('all') || output.equals('subjects')) {
// cast subjectMap to JSON
subjects = new JSONObject(subjectMap)
}
if (output.equals('all') || output.equals('measurements')) {
// get measurements for assay
measurements = apiService.getPlainMeasurementData(assay, user)
}
if (output.equals('all') || output.equals('features')) {
// get features (metadata) for assay
features = apiService.getFeaturesForAssay(assay, user)
}
// define result
def result = [:]
result = [
"measurements" : measurements,
"features" : features,
"subjects" : subjects
]
// set output headers
response.status = 200
response.contentType = 'plain/text;charset=UTF-8'
//response.contentType = 'application/json;charset=UTF-8'
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
} catch (Exception e) {
println "getMeasurementDataForAssay exception: ${e.getMessage()}"
response.sendError(500, "module '${assay.module}' does not properly implement getMeasurementData REST specification (${e.getMessage()})")
}
})
}
/**
* get all modules connected to this GSCF instance
*
* @param string deviceID
* @param string validation md5 sum
*/
def getModules = {
println "api::getModules: ${params}"
// get all modules
def modules = AssayModule.findAll()
// wrap in api call validator
apiService.executeApiCall(params, response, 'modules', modules, {
def result2 = apiService.flattenDomainData(modules)
def result = [:]
modules.each {
result[ result.size() ] = [
'name' : it.name,
'url' : it.url,
'token' : 'to be completed...'
]
}
// set output headers
response.status = 200
response.contentType = 'application/json;charset=UTF-8'
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
})
}
/**
* get all domain classes that extend GDT's TemplateEntity (entities)
*
* @param string deviceID
* @param string validation md5 sum
*/
def getEntityTypes = {
println "api::getEntityTypes: ${params}"
// list of entities
def entities = apiService.getEntities().keySet()
// wrap result in api call validator
apiService.executeApiCall(params, response, 'entities', entities, {
// set output headers
response.status = 200
response.contentType = 'application/json;charset=UTF-8'
if (params.containsKey('callback')) {
render "${params.callback}(${entities as JSON})"
} else {
render entities as JSON
}
})
}
/**
* get all templates for a specific entity
*
* @param string deviceID
* @param string validation md5 sum
* @param string entityType
*/
def getTemplatesForEntity = {
println "api::getTemplatesForEntity: ${params}"
def result = [:]
String entityType = (params.containsKey('entityType')) ? params.get('entityType') : ''
try {
def entity = apiService.getEntity(entityType)
def templates = Template.findAllByEntity(entity)
// wrap result in api call validator
apiService.executeApiCall(params, response, 'templates', templates, {
// set output headers
response.status = 200
response.contentType = 'application/json;charset=UTF-8'
result = ['templates': apiService.flattenDomainData(templates,['id'])]
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
})
} catch (Exception e) {
println "getTemplatesForEntity exception: ${e.getMessage()}"
response.sendError(500, "unknown error occured (${e.getMessage()})")
}
}
/**
* get all fields for a specific entity
*
* @param string deviceID
* @param string validation md5 sum
* @param string entityType
*/
def getFieldsForEntity = {
println "api::getFieldsForEntity: ${params}"
// while we pass this call through to getFieldsForEntityWithTemplate,
// this particular call was designed to be called with no template
// argument set, so strip it from the parameters so the result data is
// as expected
if (params.containsKey('templateToken')) params.remove('templateToken')
// add a passthrough parameter
params['passthrough'] = true
// passthrough to getFieldsForEntityWithTemplate
getFieldsForEntityWithTemplate(params)
}
/**
* get all fields for a specific entity and optionally a template
*
* @param string deviceID
* @param string validation md5 sum
* @param string entityType
* @param string templateToken
*/
def getFieldsForEntityWithTemplate = {
if (!params.containsKey('passthrough')) {
// entityToken can only be passed by the getFieldsForEntity call
// so strip it if we're not passing through
params.remove('entityToken')
println "api::getFieldsForEntityWithTemplate: ${params}"
}
def result = [:]
String entityType = (params.containsKey('entityType')) ? params.get('entityType') : ''
String templateToken = (params.containsKey('templateToken')) ? params.get('templateToken') : ''
String entityToken = (params.containsKey('entityToken')) ? params.get('entityToken') : ''
if (entityType) {
try {
// get entity
def entity = apiService.getEntity(entityType)
// got an entity?
if (!entity) throw new Exception("invalid entity '${entityType}', call getEntityTypes for a list of valid entities. Note that entityType is case sensitive!")
// instantiate entity
def entityInstance = entity.newInstance()
// got an entityToken or a templatetoken?
if (entityToken) {
// find the entity with this token
def foundInstance = entityInstance.findWhere(UUID: entityToken)
// found an instance?
if (foundInstance) {
// yes, use this instance instead
entityInstance = foundInstance
} else {
throw new Exception("no such ${entityType} with token ${entityToken}")
}
} else if (templateToken) {
// no entity token, but we have a template token instead
def template = Template.findWhere(UUID: templateToken)
// was a valid template specified?
if (template && entity.equals(template.entity)) {
// set template
entityInstance.setTemplate(template)
} else {
throw new Exception("invalid template token specified, call getTemplatesForEntity(${entityType}) for a list of valid templates")
}
}
// wrap result in api call validator
apiService.executeApiCall(params, response, entityType, entityInstance, {
// set output headers
response.status = 200
response.contentType = 'application/json;charset=UTF-8'
// gather data
def fields = []
def requiredFields = entityInstance.getRequiredFields().collect { it.name }
// gather fields
entityInstance.giveFields().each { field ->
def flattenedField = apiService.flattenTemplateField(field)
flattenedField.required = requiredFields.contains(flattenedField.name)
fields.add(flattenedField)
}
// fetch all fields
result = [
'fields' : fields,
'requiredFields': requiredFields
]
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
})
} catch (Exception e) {
response.sendError(500, "unknown error occured (${e.getMessage()})")
}
} else {
response.sendError(400, "entityType is missing")
}
}
/**
* create a new entity
*
* @param string deviceID
* @param string validation md5 sum
* @param string entityType
*/
def createEntity = {
println "api::createEntity: ${params}"
// while we pass this call through to createEntityWithTemplate,
// this particular call was designed to be called with no template
// argument set, so strip it from the parameters so the result data is
// as expected
if (params.containsKey('templateToken')) params.remove('templateToken')
// add a passthrough parameter
params['passthrough'] = true
// passthrough to getFieldsForEntityWithTemplate
createEntityWithTemplate(params)
}
/**
* create a new entity with a specific template defined
*
* @param string deviceID
* @param string validation md5 sum
* @param string entityType
* @param string templateToken
*/
def createEntityWithTemplate = {
if (!params.containsKey('passthrough')) {
println "api::createEntityWithTemplate: ${params}"
}
String entityType = (params.containsKey('entityType')) ? params.get('entityType') : ''
String templateToken = (params.containsKey('templateToken')) ? params.get('templateToken') : ''
Map hasManyRelationships = [:] // belongsTo relationship
Map relationships = [:] // one to one relationship
Map reverseRelationships = [:] // non belongsTo relationships (parent hasMany relationship)
if (entityType) {
try {
// get entity
def entity = apiService.getEntity(entityType)
// got an entity?
if (!entity) throw new Exception("invalid entity '${entityType}', call getEntityTypes for a list of valid entities. Note that entityType is case sensitive!")
// instantiate entity
def entityInstance = entity.newInstance()
// got a template token?
if (templateToken) {
// no entity token, but we have a template token instead
def template = Template.findWhere(UUID: templateToken)
// was a valid template specified?
if (template && entity.equals(template.entity)) {
// set template
entityInstance.setTemplate(template)
} else {
throw new Exception("invalid template token specified, call getTemplatesForEntity(${entityType}) for a list of valid templates")
}
}
// iterate through all fields for this instance and try to set them
entityInstance.giveFields().each {
if (params.containsKey(it.name)) {
entityInstance.setFieldValue(it.name, params.get(it.name))
}
}
// try to set the relationships
def changed = false
if (entityInstance.hasProperty('belongsTo')) {
entityInstance.belongsTo.each { name, type ->
def matches = type.toString() =~ /\.([^\.]+)$/
def tokenEntity = matches[0][1]
def tokenName = "${tokenEntity.toLowerCase()[0]}${tokenEntity.substring(1)}Token".toString()
def uuid = (params.containsKey(tokenName)) ? params.remove(tokenName) : ''
// does the tokenName exist in the parameters (e.g. studyToken)?
if (uuid) {
// yes, find an instance of this entity
def tokenInstance = apiService.getEntity(tokenEntity)
// find the entity with this particular token
def foundEntity = tokenInstance.findWhere(UUID: uuid)
// did we indeed found the entity we need to set a relationship with?
if (foundEntity) {
// check if there is a hasMany relationship for this entity type
def relationship = foundEntity.hasMany.find { n, t ->
def m = t.toString() =~ /\.([^\.]+)$/
return (entityType == m[0][1])
}
// found a hasMany relationship?
if (relationship) {
// yes, set relationship
def relationsName = relationship.key.toString()
foundEntity."addTo${relationsName.toUpperCase()[0]}${relationsName.substring(1)}"( entityInstance )
hasManyRelationships["${relationsName.toUpperCase()[0]}${relationsName.substring(1)}"] = foundEntity
changed = true
} else {
// no, check if it's a one to one relationship
relationship = foundEntity.properties.find { n, t ->
def m = t.toString() =~ /\.([^\.]+)$/
return (m && entityType == m[0][1])
}
// got one?
if (relationship) {
// yes, set it
def relationsName = relationship.key.toString()
foundEntity."${relationsName}" = entityInstance
relationships["${relationsName}"] = foundEntity
changed = true
}
}
} else {
throw new Exception("A ${tokenEntity} with token ${uuid} does not exist")
}
}
}
}
// do we have other relationships in the parameter set? E.g.
// reverse relationships where belongsTo (cascaded deletes) is
// not defined, yet in a parent object this instance is defined
// in a hasMany relationship?
params.findAll{ name, value -> name =~ /Token$/ }.each { name, value ->
// get the reverse (parent) instance name
// for example: Sample -> Assay where Assay does have a
// hasMany relationship to Sample but Sample does not
// have a belongsTo set for Assay
def m = name =~ /^([a-zA-Z]+)Token$/
def reverseInstanceName = m[0][1].toUpperCase()[0] + m[0][1].substring(1)
// get an instance of this class
def reverseBaseInstance = apiService.getEntity(reverseInstanceName)
def reverseInstance = null
// fetch the reverse instance (if possible)
try {
reverseInstance = reverseBaseInstance.findWhere(UUID: value)
} catch (Exception e) { }
// got a reverse relationship?
if (reverseInstance) {
reverseInstance.hasMany.findAll { hasManyName, hasManyValue ->
hasManyValue == entity
}.each { hasManyName, hasManyValue ->
def functionName = "${hasManyName.toUpperCase()[0]}${hasManyName.substring(1)}"
// remember relationship for rollback purposes
reverseRelationships[ functionName ] = reverseInstance
// add relationship
reverseInstance."addTo${functionName}"( entityInstance )
}
}
}
// validate instance
if (entityInstance.validate()) {
// wrap result in api call validator
apiService.executeApiCall(params, response, entityType, entityInstance, {
// try to save instance
try {
// save item, although it may already have been
// implicitely saved by any addToXyz statement
// earlier
if (!changed) entityInstance.save()
// set output headers
response.status = 200
response.contentType = 'application/json;charset=UTF-8'
// fetch all fields
def result = [
'success' : true,
'entityType': entityType,
'token' : entityInstance.UUID
]
if (params.containsKey('callback')) {
render "${params.callback}(${result as JSON})"
} else {
render result as JSON
}
} catch (Exception e) {
response.sendError(500, "unknown error occured (${e.getMessage()})")
}
}, {
// undo relationships - CLEANUP!
hasManyRelationships.each { name, instance ->
instance."removeFrom${name}"(entityInstance)
}
relationships.each { name, instance ->
instance[name] = null
}
entityInstance.delete(flush: true)
})
} else {
// blast, we've got errors
// undo relationships - CLEANUP!
hasManyRelationships.each { name, instance ->
println " rollback ${instance}::${name}"
instance."removeFrom${name}"(entityInstance)
}
relationships.each { name, instance ->
println " rollback ${instance}::${name}"
instance[name] = null
}
reverseRelationships.each { name, instance ->
println " rollback ${instance}::${name}"
instance."removeFrom${name}"(entityInstance)
}
entityInstance.delete(flush: true)
// propagate errors
throw new Exception(entityInstance.errors.getAllErrors().collect { validationTagLib.message(error: it) }.join(', '))
}
} catch (Exception e) {
response.sendError(500, "unknown error occured (${e.getMessage()})")
}
} else {
response.sendError(400, "entityType is missing")
}
}
/**
* Implementation of RFC 2324
*/
def teapot = {
// ask, and the Mad Hatter will reply...
response.sendError(418, "'Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.")
}
}