root/trunk/grails-app/controllers/dbnp/exporter/ExporterController.groovy @ 1456

Revision 1456, 9.2 KB (checked in by business@…, 3 years ago)

moved gdt package to org.dbnp, moved tests for RelTime?, TemplateEntity?, Template etc. to gdt plugin

  • Property svn:keywords set to Rev Author Date
Line 
1/**
2 * ExporterController Controler
3 *
4 * Description of my controller
5 *
6 * @author  your email (+name?)
7 * @since       2010mmdd
8 * @package     ???
9 *
10 * Revision information:
11 * $Rev$
12 * $Author$
13 * $Date$
14 */
15package dbnp.exporter
16
17import dbnp.studycapturing.*
18import org.dbnp.gdt.*
19
20import org.apache.poi.hssf.util.HSSFColor
21import org.apache.poi.*
22import org.apache.poi.hssf.usermodel.*
23import org.apache.poi.poifs.filesystem.POIFSFileSystem
24import org.apache.poi.ss.usermodel.DataFormatter
25import java.util.zip.ZipEntry
26import java.util.zip.ZipOutputStream
27import java.util.zip.ZipInputStream
28import javax.servlet.ServletOutputStream
29
30import grails.plugins.springsecurity.Secured
31
32class ExporterController {
33
34    def AuthenticationService
35    def ImporterService
36
37    /*
38     * List of all studies for selection the study to export
39     * Using the same code as 'list' into StudyController
40     */
41    def index = {
42
43        def user = AuthenticationService.getLoggedInUser()
44        def max = Math.min(params.max ? params.int('max') : 10, 100)
45
46        def c = dbnp.studycapturing.Study.createCriteria()
47
48        def studies = Study.giveReadableStudies(user, max);
49        [studyInstanceList: studies, studyInstanceTotal: studies.count()]
50    }
51
52    def export = {
53
54        def studies = []
55        for ( j in dbnp.studycapturing.Study.list() ){
56            if (params.containsKey(j.code)){
57                studies.add(j)
58            }
59        }
60       
61        if(studies.size()>1){
62            // Create a ZIP file containing all the SimpleTox files
63            def files = []
64            for (studyInstance in studies){
65                downloadFile(studyInstance,false)
66                files.add(new File("web-app/fileuploads/"+studyInstance.code+"_SimpleTox.xls"))
67            }
68
69            response.setContentType( "application/zip" ) ;
70            response.addHeader( "Content-Disposition", "attachment; filename=\"GSCF_SimpleToxStudies.zip\"" ) ;
71
72            // get a ZipOutputStream, so we can zip our files together
73            ZipOutputStream outZip = new ZipOutputStream( response.getOutputStream() );
74
75            // add SimpleTox files to the zip
76            for (outFiles in files){
77
78                FileInputStream inStream = null
79                try
80                {
81                    // Add ZIP entry to output stream.
82                    outZip.putNextEntry( new ZipEntry( outFiles.getName() ) ) ;
83
84                    inStream = new FileInputStream( outFiles )
85
86                    // Transfer bytes from the file to the ZIP file
87                    byte[] buf = new byte[ 4096 ] ;
88                    int len
89                    while( ( len = inStream.read( buf ) ) > 0 )
90                    {
91                        outZip.write( buf, 0, len )
92                    }
93                }
94                catch( Exception ex ) {  }
95                finally
96                {
97                    // Complete the entry
98                    try{ outZip.closeEntry() } catch( Exception ex ) { }
99                    try{ inStream.close() } catch( Exception ex ) { }
100                }
101                outFiles.delete()
102            }
103            outZip.flush()
104            outZip.close()
105        }
106
107
108        else {
109            def studyInstance = studies.getAt(0)
110            // make the file downloadable
111            if ((studyInstance!=null) && (studyInstance.samples.size()>0)){
112                downloadFile(studyInstance,true)
113            }
114            else {
115                flash.message= "Error while exporting the file, please try again or choose another file"
116                redirect(action:index)
117            }
118
119        }
120
121    }
122    /*
123     * the export method will create a SimpleTox format for the selected study
124     */
125    def downloadFile(studyInstance, boolean dl) {
126        // the attributes list for the SimpleTox format
127        def attributes_list = ["SubjectID","DataFile","HybName","SampleName","ArrayType","Label","StudyTitle","Array_ID",
128        "Species"]
129        println studyInstance.samples.size()
130        println "StudyInstance :" + studyInstance
131               
132        // The first row contains the attributes names
133        HSSFWorkbook wb = new HSSFWorkbook()
134        HSSFSheet sheet = wb.createSheet()
135        HSSFRow row     = sheet.createRow((short)0)
136        for (i in 0..attributes_list.size()){
137            row.createCell((short)i).setCellValue(attributes_list[i])
138        }
139
140        // Adding the next lines
141        for (s in 1..studyInstance.samples.size()){
142            // creating new line for every sample
143            HSSFRow sub     = sheet.createRow((short)s)
144            def sample = studyInstance.samples.getAt(s-1)
145           
146            writeMandatoryFields(sub,sample,studyInstance)
147
148            try {
149                // adding the subject domain + template properties
150                writeSubjectProperties(sub,sample,row)
151
152                // adding the samplingEvent domain + template properties
153                writeSamplingEventProperties(sub,sample,row)
154           
155                // adding EventGroup domain + template properties
156                //                writeEventGroupProperties(sub,sample,rows)
157
158                // adding Sample domain + template properties
159                writeSampleProperties(sub,sample,row)
160            }
161            catch (Exception e){
162                println "Error adding properties"
163            }
164        }
165
166        // Make the file downlodable
167        if(dl) {
168            println "Creation for downloading the file "+studyInstance.title+"_SimpleTox.xls"
169            response.setHeader("Content-disposition", "attachment;filename=\"${studyInstance.code}_SimpleTox.xls\"")
170            response.setContentType("application/octet-stream")
171            wb.write(response.outputStream)
172            response.outputStream.close()
173        }
174
175        // Create the file and save into ZIP
176        if(!dl){
177            FileOutputStream fileOut = new FileOutputStream("web-app/fileuploads/"+studyInstance.code+"_SimpleTox.xls", true)
178            wb.write(fileOut)
179            fileOut.close()
180        }
181    }
182
183    def writeMandatoryFields(sub,sample,study) {
184        // adding subject name in row 1
185        sample.parentSubject ? sub.createCell((short)0).setCellValue(sample.parentSubject.name) : "not defined"
186        // adding sample in row 4
187        sample.name!=null ? sub.createCell((short)3).setCellValue(sample.name) : "not defined"
188        // adding label (EventGroup) in row 6
189        for (ev in EventGroup.list()){
190            if(sample.parentSubject){
191                if ( (sample.parentSubject.name) && (ev.subjects.name.contains(sample.parentSubject.name))) {
192                    sub.createCell((short)5).setCellValue(ev.name)
193                    break
194                }
195                else {
196                    sub.createCell((short)5).setCellValue(" ")
197                }}
198            else {
199                sub.createCell((short)5).setCellValue(" ")
200            }
201        }
202        // adding study title in row 7
203        sub.createCell((short)6).setCellValue(study.title)
204        // Species row 9
205//        sample.parentSubject.species.name!=null ? sub.createCell((short)8).setCellValue(sample.parentSubject.species.name) : "not defined"
206        sample.parentSubject ? sub.createCell((short)8).setCellValue(sample.parentSubject.species.name) : "not defined"
207    }
208
209    // writing subject properties
210    def writeSubjectProperties(sub,sample,row) {
211        println "----- SUBJECT -----"
212        for (u in 0..sample.parentSubject.giveFields().unique().size()-1){
213            TemplateField tf = sample.parentSubject.giveFields().getAt(u)
214            println tf.name
215            row.createCell((short)9+u).setCellValue(tf.name)
216            sample.parentSubject.getFieldValue(tf.name) ? sub.createCell((short)9+u).setCellValue(sample.parentSubject.getFieldValue(tf.name).toString()) : "not define"
217        }
218    }
219
220    // writing samplingEvent properties
221    def writeSamplingEventProperties(sub,sample,row){
222        println "----- SAMPLING EVENT -----"
223        for (t in 0..sample.parentEvent.giveFields().unique().size()-1){
224            TemplateField tf =sample.parentEvent.giveFields().getAt(t)
225            println tf.name
226            row.createCell((short)9+sample.parentSubject.giveFields().unique().size()+t).setCellValue("samplingEvent-"+tf.name)
227            sample.parentEvent.getFieldValue(tf.name) ? sub.createCell((short)9+sample.parentSubject.giveFields().unique().size()+t).setCellValue(sample.parentEvent.getFieldValue(tf.name).toString()) : "not define"
228        }
229    }
230
231    // writing EventGroup properties
232    def writeEventGroupProperties(sub,sample,row){
233     
234    }
235
236    // writing sample properties
237    def writeSampleProperties(sub,sample,row){
238        println "----- SAMPLE -----"
239        for (v in 0..sample.giveFields().unique().size()-1){
240            TemplateField tf =sample.giveFields().getAt(v)
241            println tf.name
242            row.createCell((short)9+sample.parentSubject.giveFields().unique().size()+v+sample.parentEvent.giveFields().unique().size()).setCellValue("sample-"+tf.name)
243            sample.getFieldValue(tf.name) ? sub.createCell((short)9+sample.parentSubject.giveFields().unique().size()+v+sample.parentEvent.giveFields().unique().size()).setCellValue(sample.getFieldValue(tf.name).toString()) : "not define"
244        }
245    }
246}
Note: See TracBrowser for help on using the browser.