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

Revision 1617, 9.2 KB (checked in by robert@…, 3 years ago)

Bugfix in advanced query

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