source: trunk/grails-app/controllers/nl/tno/metagenomics/integration/RestController.groovy @ 4

Last change on this file since 4 was 4, checked in by robert@…, 12 years ago

Implemented trash in order to prevent deletion of data

File size: 15.0 KB
Line 
1package nl.tno.metagenomics.integration
2
3
4import grails.converters.*
5import nl.tno.metagenomics.Study
6import org.codehaus.groovy.grails.commons.ConfigurationHolder
7
8/** Expose the list of features within a certain assay
9 *
10 * @author Robert Horlings (robert@isdat.nl)
11 * @since 20101229
12 * @see   SAM.RestController
13 *
14 * $Rev$
15 *
16 * This class provides a REST-full service for getting and setting the data
17 * in the Metagenomics Module. The service consists of several
18 * resources listed below. So far, all resources are GET resoruces, i.e. we
19 * do not use PUT, POST or DELETE. Because we are using Grails' web libaries,
20 * each resource corresponds to exactly one action of this controller.
21 *
22 *
23 * The REST resources implemented in this controller are:
24 *
25 * metagenomics-host:port/metagenomics/rest/getMeasurements(assayToken)
26 * metagenomics-host:port/metagenomics/rest/getMeasurementMetadata(assayToken, measurementTokens)
27 * metagenomics-host:port/metagenomics/rest/getMeasurementData(assayToken, measurementTokens, sampleTokens)
28 * metagenomics-host:port/metagenomics/rest/getAssayURL(assayToken)
29 *
30 * Where 'metagenomics-host' is the url of the metagenomics server's host with port number 'port'.
31 *
32 */
33class RestController {
34        def synchronizationService
35
36        /****************************************************************/
37        /* REST resources for providing basic data to the GSCF          */
38        /****************************************************************/
39        private getMeasurementTypes() {
40                return [ "# sequences", "average quality" ]
41        }
42
43        /**
44         * Return a list of simple assay measurements matching the querying text.
45         *
46         * @param assayToken
47         * @return list of measurements for token. Each member of the list is a hash.
48         *                      the hash contains the three keys values pairs: value, sampleToken, and
49         *                      measurementMetadata.
50         *
51         * Example REST call:
52         * http://localhost:8184/metagenomics/rest/getMeasurements/query?assayToken=16S-5162
53         *
54         * Resulting JSON object:
55         *
56         * [ "# sequences", "average quality" ]
57         *
58         */
59        def getMeasurements = {
60                def assayToken = params.assayToken;
61
62                if( !checkAssayToken( assayToken ) ) {
63                        response.sendError(404)
64                        return false
65                }
66
67                render getMeasurementTypes() as JSON
68        }
69
70
71        /**
72         * Return measurement metadata for measurement
73         *
74         * @param assayToken
75         * @param measurementTokens. List of measurements for which the metadata is returned.
76         *                           If this is not given, then return metadata for all
77         *                           measurements belonging to the specified assay.
78         * @return list of measurements
79         *
80         * Example REST call:
81         * http://localhost:8184/metagenomics/rest/getMeasurementMetadata/query?assayToken=16S-5162
82         *      &measurementToken=# sequences
83         *              &measurementToken=average quality
84         *
85         * Example resulting JSON object:
86         *
87         * [ {"name":"# sequences","type":"raw"},
88         *   {"name":"average quality", "unit":"Phred"} ]
89         */
90        def getMeasurementMetadata = {
91                def assayToken = params.assayToken
92                def measurementTokens = params.measurementToken
93
94                if( !checkAssayToken( assayToken ) ) {
95                        response.sendError(404)
96                        return false
97                }
98
99                // For now, we don't have any metadata about the measurements
100                def measurements = getMeasurementTypes();
101                def measurementMetadata = []
102
103                measurementTokens.each { token ->
104                        if( measurements.contains( token ) )
105                                measurementMetadata << [ "name" : token ];
106                }
107
108                render measurementMetadata as JSON
109        }
110
111
112        /*
113         * Return list of measurement data.
114         *
115         * @param assayTokes
116         * @param measurementToken. Restrict the returned data to the measurementTokens specified here.
117         *                                              If this argument is not given, all samples for the measurementTokens are returned.
118         *                                              Multiple occurences of this argument are possible.
119         * @param sampleToken. Restrict the returned data to the samples specified here.
120         *                                              If this argument is not given, all samples for the measurementTokens are returned.
121         *                                              Multiple occurences of this argument are possible.
122         * @param boolean verbose. If this argument is not present or it's value is true, then return
123         *                      the date in a redundant format that is easier to process.
124         *                                              By default, return a more compact JSON object as follows.
125         *
126         *                                              The list contains three elements:
127         *
128         *                                              (1) a list of sampleTokens,
129         *                                              (2) a list of measurementTokens,
130         *                                              (3) a list of values.
131         *
132         *                                              The list of values is a matrix represented as a list. Each row of the matrix
133         *                                              contains the values of a measurementToken (in the order given in the measurement
134         *                                              token list, (2)). Each column of the matrix contains the values for the sampleTokens
135         *                                              (in the order given in the list of sampleTokens, (1)).
136         *                                              (cf. example below.)
137         *
138         *
139         * @return  table (as hash) with values for given samples and measurements
140         *
141         *
142         * List of examples.
143         *
144         *
145         * Example REST call:
146         * http://localhost:8184/metagenomics/rest/getMeasurementData/doit?assayToken=PPSH-Glu-A
147         *    &measurementToken=total carbon dioxide (tCO)
148         *    &sampleToken=5_A
149         *    &sampleToken=1_A
150         *    &verbose=true
151         *
152         * Resulting JSON object:
153         * [ {"sampleToken":"1_A","measurementToken":"total carbon dioxide (tCO)","value":28},
154         *   {"sampleToken":"5_A","measurementToken":"total carbon dioxide (tCO)","value":29} ]
155         *
156         *
157         *
158         * Example REST call without sampleToken, without measurementToken,
159         *    and with verbose representation:
160         * http://localhost:8184/metagenomics/rest/getMeasurementData/dossit?assayToken=PPSH-Glu-A
161         *    &verbose=true
162         *
163         * Resulting JSON object:
164         * [ {"sampleToken":"1_A","measurementToken":"sodium (Na+)","value":139},
165         *       {"sampleToken":"1_A","measurementToken":"potassium (K+)","value":4.5},
166         *       {"sampleToken":"1_A","measurementToken":"total carbon dioxide (tCO)","value":26},
167         *       {"sampleToken":"2_A","measurementToken":"sodium (Na+)","value":136},
168         *       {"sampleToken":"2_A","measurementToken":"potassium (K+)","value":4.3},
169         *       {"sampleToken":"2_A","measurementToken":"total carbon dioxide (tCO)","value":28},
170         *       {"sampleToken":"3_A","measurementToken":"sodium (Na+)","value":139},
171         *       {"sampleToken":"3_A","measurementToken":"potassium (K+)","value":4.6},
172         *       {"sampleToken":"3_A","measurementToken":"total carbon dioxide (tCO)","value":27},
173         *       {"sampleToken":"4_A","measurementToken":"sodium (Na+)","value":137},
174         *       {"sampleToken":"4_A","measurementToken":"potassium (K+)","value":4.6},
175         *       {"sampleToken":"4_A","measurementToken":"total carbon dioxide (tCO)","value":26},
176         *       {"sampleToken":"5_A","measurementToken":"sodium (Na+)","value":133},
177         *       {"sampleToken":"5_A","measurementToken":"potassium (K+)","value":4.5},
178         *       {"sampleToken":"5_A","measurementToken":"total carbon dioxide (tCO)","value":29} ]
179         *
180         *
181         *
182         * Example REST call with default (non-verbose) view and without sampleToken:
183         *
184         * Resulting JSON object:
185         * http://localhost:8184/metagenomics/rest/getMeasurementData/query?
186         *      assayToken=PPSH-Glu-A&
187         *      measurementToken=total carbon dioxide (tCO)
188         *
189         * Resulting JSON object:
190         * [ ["1_A","2_A","3_A","4_A","5_A"],
191         *   ["sodium (Na+)","potassium (K+)","total carbon dioxide (tCO)"],
192         *   [139,136,139,137,133,4.5,4.3,4.6,4.6,4.5,26,28,27,26,29] ]
193         *
194         * Explanation:
195         * The JSON object returned by default (i.e., unless verbose is set) is an array of three arrays.
196         * The first nested array gives the sampleTokens for which data was retrieved.
197         * The second nested array gives the measurementToken for which data was retrieved.
198         * The thrid nested array gives the data for sampleTokens and measurementTokens.
199         *
200         *
201         * In the example, the matrix represents the values of the above Example and
202         * looks like this:
203         *
204         *                      1_A             2_A             3_A             4_A             5_A
205         *
206         * Na+          139             136             139             137             133
207         *
208         * K+           4.5             4.3             4.6             4.6             4.5
209         *
210         * tCO          26              28              27              26              29
211         *
212         */
213        def getMeasurementData = {
214                def assayToken = params.assayToken
215                def measurementTokens = params.measurementToken
216                def sampleTokens = params.sampleToken
217                def verbose = false
218
219                if(params.verbose && (params.verbose=='true'||params.verbose==true) ) {
220                        verbose=true
221                }
222
223                def assay = checkAssayToken( assayToken );
224                if( !assay ) {
225                        response.sendError(404)
226                        return false
227                }
228
229                if( !measurementTokens ) {
230                        measurementTokens = []
231                }
232                else if( measurementTokens.class == java.lang.String ) {
233                        measurementTokens = [ measurementTokens ]
234                }
235
236                if( !sampleTokens ) {
237                        sampleTokens = []
238                }
239                else if( sampleTokens.class == java.lang.String ) {
240                        sampleTokens = [ sampleTokens ]
241                }
242
243                def data = SampleAssay.findAllByAssay( assay );
244                def measurements = getMeasurementTypes()
245
246                def results = []
247                data.each { sampleAssay ->
248                        measurements.each { type ->
249                                def sample = sampleAssay.sample.sampleToken
250                                def isMatch = false
251
252                                // Check if this measurement should be returned
253                                if( ( measurementTokens.isEmpty() || measurementTokens.contains( type ) ) &&
254                                ( sampleTokens.isEmpty()      || sampleTokens.contains( sample ) ) ) {
255                                        results.push( [ 'sampleToken': sample, 'measurementToken': type, 'value': sampleAssay[ type ] ] )
256                                }
257                        }
258                }
259
260                if(!verbose) {
261                        results = compactTable( results )
262                }
263
264                render results as JSON
265        }
266
267        /**
268         * Is called by GSCF when a study is added, changed or deleted.
269         * Sets the 'dirty' flag of a study to true, so that it will be updated
270         * next time the study is asked for.
271         *
272         * @param       studyToken
273         */
274        def notifyStudyChange = {
275                def studyToken = params.studyToken
276               
277                if( !studyToken ) {
278                        response.sendError(400, "No studyToken given" )
279                        return
280                }
281               
282                // Search for the changed study
283                def study = Study.findByStudyToken( studyToken );
284               
285                // If the study is not found, it is added in GSCF. Add a dummy (dirty) study, in order to
286                // update it immediately when asked for
287                if( !study ) {
288                        log.info( "METAGENOMICS: GSCF notification for new study " + studyToken );
289                        study = new Study(
290                                name: "",
291                                studyToken: studyToken,
292                                isDirty: true
293                        )
294                } else {
295                        log.info( "METAGENOMICS: GSCF notification for existing study " + studyToken );
296                        study.isDirty = true;
297                }
298                study.save(flush:true);
299               
300                def jsonData = [ 'studyToken': studyToken, message: "Notify succesful" ];
301               
302                render jsonData as JSON
303        }
304       
305        /**
306         * Return URL to view an assay.
307         *
308         * @param  assayToken
309         * @return URL to view an assay as single hash entry with key 'url'.
310         *
311         */
312        def getAssayURL = {
313                def assayToken = params.assayToken
314
315                if( !assayToken ) {
316                        render [] as JSON
317                        return
318                }
319
320                def assay = Assay.findByAssayToken( assayToken )
321
322                // If the assay is not found, try synchronizing
323                synchronizationService.sessionToken = session.sessionToken
324               
325                if( !assay ) {
326                        synchronizationService.synchronizeStudies()
327                        assay = Assay.findByAssayToken( assayToken );
328                       
329                        if( !assay ) {
330                                response.sendError(404, "Not Found" )
331                                return;
332                        }
333                } else {
334                        try {
335                                synchronizationService.synchronizeAssay(assay);
336                        } catch( Exception e ) {
337                                response.sendError( 500, e.getMessage())
338                                return
339                        }
340                       
341                        def url = [ 'url' : ConfigurationHolder.config.grails.serverURL + '/assay/show/' + assay.id.toString() ]
342
343                        render url as JSON
344                }
345        }
346       
347        /***************************************************/
348        /* REST resources related to the querying in GSCF  */
349        /***************************************************/
350
351        /**
352         * @param   (no parameters)
353         * @return  metadata fields that can be available for any assay stored in the module
354         */
355        def getAssayMetadataFields = {
356                def exampleType = Assay.find()
357                def list = []
358
359                exampleType.giveFields.each{
360                        list.push( it.name )
361                }
362
363                render list as JSON
364        }
365
366        /**
367         *
368         * @param   assayToken
369         * @param   measurementTokens
370         * @return  metadata values for the specified assay
371         */
372        def getAssayMetadataValues = {
373                def error = CommunicationManager.hasValidParameters( params, 'assayToken' )
374                if(error) {
375                        render error as JSON
376                        return
377                }
378                def assay = SimpleAssay.findByExternalAssayID( params.assayToken )
379                def types = []
380                def hash = []
381                token.getMeasurements.each {
382                        types.push( it.type     )
383                }
384                types.unique.each { type ->
385                        type.fields.each { field ->
386                                hash[field.name] = field.value
387                        }
388                }
389                render hash as JSON
390        }
391
392
393
394        /**
395         * @param   assayToken
396         * @return  list of metadata fields that are available for the samples in the specified assay
397         */
398        def getSampleMetadataFields = {
399                def error = CommunicationManager.hasValidParameters( params, 'assayToken' )
400                if(error) {
401                        render error as JSON
402                        return
403                }
404                def assay = SimpleAssay.findByExternalAssayID( params.assayToken )
405                def types = []
406                assay.getTypes.each{
407                        types.push(it.name)
408                }
409                render types as JSON
410        }
411
412
413
414        /**
415         * @param   assayToken
416         * @param   list of sampleTokens
417         * @return  List of sample metadata values for the specified samples in the specified assay.
418         *          Each element of the list is a hash containing values for one sample.
419         *          The hash contains the key "sampleToken" to indentify the sample. The other keys
420         *          of the hash contain information on the actual metadata values for the sample.
421         *          The keys are metadata fields, the values are the values of the corresponding
422         *          SimpleAssayMeasurements.
423         */
424        def getSampleMetadata = {
425                def error = CommunicationManager.hasValidParameters( params, 'assayToken', 'sampleToken' )
426                if(error) {
427                        render error as JSON
428                        return
429                }
430                def assay = SimpleAssay.findByExternalAssayID( params.assayToken )
431                def samples = []
432                def list = []
433                params.sampleToken.each{
434                        if( SimpleAssaySample.findByName(it).assay == assay ) {
435                                samples.push(it)
436                        }
437                }
438                samples.each{ sample ->
439                        def hash = ['sampleToken':sample.name]
440                        SimpleAssayMeasurement.findAllBySample(sample).each{ measurement ->
441                                hash[measurement.type.name]=measumrent.value
442                        }
443                        list.push hash
444                }
445                render list as JSON
446        }
447
448        private def checkAssayToken( def assayToken ) {
449                if( !assayToken || assayToken == null ) {
450                        return false
451                }
452                def list = []
453                def assay = Assay.findByAssayToken( assayToken )
454
455                if( !assay || assay == null ) {
456                        return false;
457                }
458
459                return assay;
460        }
461
462        /* helper function for getSamples
463         *
464         * Return compact JSON object for data. The format of the returned array is as follows.
465         *
466         * The list contains three elements:
467         *
468         * (1) a list of sampleTokens,
469         * (2) a list of measurementTokens,
470         * (3) a list of values.
471         *
472         * The list of values is a matrix represented as a list. Each row of the matrix
473         * contains the values of a measurementToken (in the order given in the measurement
474         * token list, (2)). Each column of the matrix contains the values for the sampleTokens
475         * (in the order given in the list of sampleTokens, (1)).
476         */
477        def compactTable( results ) {
478                def i = 0
479                def sampleTokenIndex = [:]
480                def sampleTokens = results.collect( { it['sampleToken'] } ).unique()
481                sampleTokens.each{ sampleTokenIndex[it] = i++ }
482
483                i = 0
484                def measurementTokenIndex= [:]
485                def measurementTokens = results.collect( { it['measurementToken'] } ).unique()
486                measurementTokens.each{ measurementTokenIndex[it] = i++ }
487
488                def data = []
489                measurementTokens.each{ m ->
490                        sampleTokens.each{ s ->
491                                def item = results.find{ it['sampleToken']==s && it['measurementToken']==m }
492                                data.push item ? item['value'] : null
493                        }
494                }
495
496                return [ sampleTokens, measurementTokens, data ]
497        }
498
499}
Note: See TracBrowser for help on using the repository browser.