source: trunk/grails-app/controllers/api/ApiController.groovy @ 2190

Last change on this file since 2190 was 2190, checked in by work@…, 11 years ago
  • added getAssayData api call
File size: 8.8 KB
Line 
1/**
2 * Api Controler
3 *
4 * API for third party applications to interact
5 * with GSCF
6 *
7 * @author  your email (+name?)
8 * @since       20120328ma
9 *
10 * Revision information:
11 * $Rev$
12 * $Author$
13 * $Date$
14 */
15package api
16
17import grails.plugins.springsecurity.Secured
18import grails.converters.JSON
19import dbnp.studycapturing.Study
20import dbnp.studycapturing.Assay
21import dbnp.authentication.SecUser
22import org.dbnp.gdt.TemplateFieldType
23
24class ApiController {
25    def authenticationService
26    def moduleCommunicationService
27    def ApiService
28
29        /**
30         * index closure
31         */
32    def index = {
33        render(view:'index')
34    }
35
36    @Secured(['ROLE_CLIENT', 'ROLE_ADMIN'])
37    def authenticate = {
38        println "api::authenticate: ${params}"
39
40        // see if we already have a token on file for this device id
41        def token = Token.findByDeviceID(params?.deviceID)
42       
43        // generate a new token if we don't have a token on file
44        def result = [:]
45        try {
46            // TODO - check if token belongs to current user?
47            if (!token) {
48                // generate a token for this device
49                token = new Token(
50                        deviceID    : params.deviceID,
51                        deviceToken : UUID.randomUUID().toString(),
52                        user        : authenticationService.getLoggedInUser(),
53                        sequence    : 0
54                ).save(failOnError: true)
55            }
56           
57            result = ['token':token.deviceToken,'sequence':token.sequence]
58
59            // set output headers
60            response.status = 200
61        } catch (Exception e) {
62            // caught an error
63            response.status = 500
64            result = ['error':e.getMessage()]
65        }
66
67        response.contentType = 'application/json;charset=UTF-8'
68
69        if (params.containsKey('callback')) {
70            render "${params.callback}(${result as JSON})"
71        } else {
72            render result as JSON
73        }
74    }
75
76    def getStudies = {
77        println "api::getStudies: ${params}"
78
79        String deviceID = (params.containsKey('deviceID')) ? params.deviceID : ''
80        String validation = (params.containsKey('validation')) ? params.validation : ''
81
82        // check
83        if (!apiService.validateRequest(deviceID,validation)) {
84            response.sendError(401, 'Unauthorized')
85        } else {
86            def user = Token.findByDeviceID(deviceID)?.user
87            def readableStudies = Study.giveReadableStudies(user)
88            def studies = []
89           
90            // iterate through studies and define resultset
91            readableStudies.each { study ->
92                // get result data
93                studies[ studies.size() ] = [
94                        'token'                 : study.getToken(),
95                        'title'                 : study.title,
96                        'description'           : study.description,
97                        'subjects'              : study.subjects.size(),
98                        'species'               : study.subjects.species.collect { it.name }.unique(),
99                        'assays'                : study.assays.collect { it.name }.unique(),
100                        'modules'               : study.assays.collect { it.module.name }.unique(),
101                        'events'                : study.events.size(),
102                        'uniqueEvents'          : study.events.collect { it.toString() }.unique(),
103                        'samplingEvents'        : study.samplingEvents.size(),
104                        'uniqueSamplingEvents'  : study.samplingEvents.collect { it.toString() }.unique(),
105                        'eventGroups'           : study.eventGroups.size(),
106                        'uniqueEventGroups'     : study.eventGroups.collect { it.name }.unique(),
107                        'samples'               : study.samples.size()
108                ]
109            }
110
111            def result = [
112                    'count'     : studies.size(),
113                    'studies'   : studies
114            ]
115
116            // set output headers
117            response.status = 200
118            response.contentType = 'application/json;charset=UTF-8'
119
120            if (params.containsKey('callback')) {
121                render "${params.callback}(${result as JSON})"
122            } else {
123                render result as JSON
124            }
125        }
126    }
127
128    def getSubjectsForStudy = {
129        println "api::getSubjectsForStudy: ${params}"
130
131        String deviceID     = (params.containsKey('deviceID')) ? params.deviceID : ''
132        String validation   = (params.containsKey('validation')) ? params.validation : ''
133        String studyToken   = (params.containsKey('studyToken')) ? params.studyToken : ''
134
135        // fetch user and study
136        def user    = Token.findByDeviceID(deviceID)?.user
137        def study   = Study.findByStudyUUID(studyToken)
138       
139        // check
140        if (!apiService.validateRequest(deviceID,validation)) {
141            response.sendError(401, 'Unauthorized')
142        } else if (!study) {
143            response.sendError(400, 'No such study')
144        } else if (!study.canRead(user)) {
145            response.sendError(401, 'Unauthorized')
146        } else {
147            def subjects = apiService.flattenDomainData( study.subjects )
148
149            // define result
150            def result = [
151                    'count'     : subjects.size(),
152                    'subjects'  : subjects
153            ]
154
155            // set output headers
156            response.status = 200
157            response.contentType = 'application/json;charset=UTF-8'
158
159            if (params.containsKey('callback')) {
160                render "${params.callback}(${result as JSON})"
161            } else {
162                render result as JSON
163            }
164        }
165    }
166
167    def getAssaysForStudy = {
168        println "api::getAssaysForStudy: ${params}"
169
170        String deviceID     = (params.containsKey('deviceID')) ? params.deviceID : ''
171        String validation   = (params.containsKey('validation')) ? params.validation : ''
172        String studyToken   = (params.containsKey('studyToken')) ? params.studyToken : ''
173
174        // fetch user and study
175        def user    = Token.findByDeviceID(deviceID)?.user
176        def study   = Study.findByStudyUUID(studyToken)
177
178        // check
179        if (!apiService.validateRequest(deviceID,validation)) {
180            response.sendError(401, 'Unauthorized')
181        } else if (!study) {
182            response.sendError(400, 'No such study')
183        } else if (!study.canRead(user)) {
184            response.sendError(401, 'Unauthorized')
185        } else {
186            def assays = apiService.flattenDomainData( study.assays )
187           
188            // define result
189            def result = [
190                    'count'     : assays.size(),
191                    'assays'    : assays
192            ]
193
194            // set output headers
195            response.status = 200
196            response.contentType = 'application/json;charset=UTF-8'
197
198            if (params.containsKey('callback')) {
199                render "${params.callback}(${result as JSON})"
200            } else {
201                render result as JSON
202            }
203        }
204    }
205
206    def getAssayData = {
207        println "api:getAssayData: ${params}"
208
209        String deviceID     = (params.containsKey('deviceID')) ? params.deviceID : ''
210        String validation   = (params.containsKey('validation')) ? params.validation : ''
211        String assayToken   = (params.containsKey('assayToken')) ? params.assayToken : ''
212
213        // fetch user and study
214        def user    = Token.findByDeviceID(deviceID)?.user
215        def assay   = Assay.findByAssayUUID(assayToken)
216
217        // check
218        if (!apiService.validateRequest(deviceID,validation)) {
219            response.sendError(401, 'Unauthorized')
220        } else if (!assay) {
221            response.sendError(400, 'No such assay')
222        } else if (!assay.parent.canRead(user)) {
223            response.sendError(401, 'Unauthorized')
224        } else {
225//            def assays = apiService.flattenDomainData( study.assays )
226
227            def serviceURL = "${assay.module.url}/rest/getMeasurements"
228            def serviceArguments = "assayToken=${assayToken}"
229
230            def json = moduleCommunicationService.callModuleMethod(
231                    assay.module.url,
232                    serviceURL,
233                    serviceArguments,
234                    "POST"
235            );
236
237
238            // define result
239            def result = [
240                'bla': 'hoi',
241                'json' : json
242            ]
243
244            // set output headers
245            response.status = 200
246            response.contentType = 'application/json;charset=UTF-8'
247
248            if (params.containsKey('callback')) {
249                render "${params.callback}(${result as JSON})"
250            } else {
251                render result as JSON
252            }
253        }
254    }
255}
Note: See TracBrowser for help on using the repository browser.