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

Revision 1588, 9.2 KB (checked in by s.h.sikkema@…, 3 years ago)

Fixed tests (except webtests); cleaned up Example{Studies,Templates}.groovy; decapitalized injected services; made 'transactional' properties static

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