root/trunk/grails-app/controllers/dbnp/importer/ImporterController.groovy @ 976

Revision 976, 10.7 KB (checked in by robert@…, 4 years ago)

Authentication and authorization for studies is added, according to ticket 118

  • Property svn:keywords set to Author Date Rev
Line 
1/**
2 * Importer controller
3 *
4 * The importer controller handles the uploading of tabular, comma delimited and Excel format
5 * based files. When uploaded a preview is shown of the data and the user can adjust the column
6 * type. Data in cells which don't correspond to the specified column type will be represented as "#error".
7 *
8 * The importer controller catches the actions and consecutively performs the
9 * logic behind it.
10 *
11 * @package     importer
12 * @author      t.w.abma@umcutrecht.nl
13 * @since       20100126
14 *
15 * Revision information:
16 * $Rev$
17 * $Author$
18 * $Date$
19 */
20
21package dbnp.importer
22
23import dbnp.studycapturing.Template
24import dbnp.studycapturing.Study
25import dbnp.studycapturing.Subject
26import dbnp.studycapturing.Event
27
28import dbnp.studycapturing.Sample
29import dbnp.studycapturing.TemplateFieldType
30import dbnp.studycapturing.TemplateField
31import grails.converters.JSON
32import org.apache.poi.hssf.usermodel.HSSFWorkbook
33import grails.plugins.springsecurity.Secured
34
35@Secured(['IS_AUTHENTICATED_REMEMBERED'])
36class ImporterController {
37    def ImporterService   
38
39    /**
40     * Default page
41     **/
42    def index = {       
43    }
44
45    def simpleWizard = {
46        render(view:"index_simple", model:[studies:Study.list(), entities: grailsApplication.config.gscf.domain.importableEntities])
47    }
48
49    def advancedWizard = {
50        render(view:"index_advanced", model:[templates:Template.list()])
51    }
52
53    /**
54    * This method will move the uploaded file to a temporary path and send the header
55    * and the first n rows to the preview
56    * @param importfile uploaded file to import
57    * @param study.id study identifier
58    */
59    def upload_advanced = {
60        def wb = handleUpload('importfile')
61
62        session.importer_header = ImporterService.getHeader(wb, 0)
63        session.importer_study = Study.get(params.study.id.toInteger())
64        session.importer_template_id = params.template_id
65        session.importer_workbook = wb
66
67        render (view:"step1_advanced", model:[header:session.importer_header, datamatrix:ImporterService.getDatamatrix(wb, session.importer_header, 0, 5)])
68    }
69
70    /**
71    * This method will move the uploaded file to a temporary path and send the header
72    * and the rows to the postview
73    *
74    * @param importfile uploaded file to import
75    * @param entity string representation of the entity chosen
76    */
77    def upload_simple = {
78        def wb = handleUpload('importfile')
79        def selectedentities = []
80        def entity = grailsApplication.config.gscf.domain.importableEntities.get(params.entity).entity
81        def entityClass = Class.forName(entity, true, this.getClass().getClassLoader())
82
83        // Initialize some session variables
84        session.importer_workbook = wb
85        session.importer_study = Study.get(params.study.id.toInteger())
86        session.importer_template_id = params.template_id
87        session.importer_sheetindex = params.sheetindex.toInteger() -1 // 0 == first sheet
88        session.importer_datamatrix_start = params.datamatrix_start.toInteger() -1 // 0 == first row
89        session.importer_headerrow = params.headerrow.toInteger()
90
91        // Get the header from the Excel file using the arguments given in the first step of the wizard
92        session.importer_header = ImporterService.getHeader(wb,
93                                                            session.importer_sheetindex,
94                                                            session.importer_headerrow,
95                                                            session.importer_datamatrix_start,
96                                                            entityClass)
97       
98        // Initialize 'selected entities', used to show entities above the columns
99        session.importer_header.each {
100            selectedentities.add([name:params.entity, columnindex:it.key.toInteger()])
101        }
102
103        def templates = Template.get(session.importer_template_id)
104       
105        render(view:"step2_simple", model:[entities: selectedentities,
106                                           header:session.importer_header,
107                                           datamatrix:ImporterService.getDatamatrix(
108                                               wb, session.importer_header,
109                                               session.importer_sheetindex,
110                                               session.importer_datamatrix_start,
111                                               5),
112                                           templates:templates])
113    }
114
115    /**
116     * This method handles a file being uploaded and storing it in a temporary directory
117     * and returning a workbook
118     *
119     * @param formfilename name used for the file field in the form
120     * @return workbook object reference
121     */
122    private HSSFWorkbook handleUpload(formfilename) {
123
124        def downloadedfile = request.getFile(formfilename);
125        def tempfile = new File(System.getProperty('java.io.tmpdir') + File.separatorChar + System.currentTimeMillis() + ".nmcdsp")
126        downloadedfile.transferTo(tempfile)
127
128        return ImporterService.getWorkbook(new FileInputStream(tempfile))
129    }
130
131    /**
132     * Method to save the missing properties
133     * @param entity entity class we are using (dbnp.studycapturing.Subject etc.)
134     */
135
136    def saveMissingProperties = {
137
138        session.importer_importeddata.each { table ->
139            table.each { entity ->
140                entity.giveFields().each { field ->
141                    //print ":" + params["entity_" + entity.hashCode() + "_" + field.escapedName()]
142                    entity.setFieldValue (field.toString(), params["entity_" + entity.hashCode() + "_" + field.escapedName()])
143                }               
144            }
145        }
146
147        render(view:"step3", model:[datamatrix:session.importer_importeddata]) 
148    }
149
150    /**
151    * User has assigned all entities and templatefieldtypes to the columns and continues to the next step (assigning properties to columns)
152    * All information of the columns is stored in a session as MappingColumn object
153    *
154    * @param entities list of entities and columns it has been assigned to (columnindex.entitytype)
155    * @param templatefieldtype list of celltypes and columns it has been assigned to (columnindex:templatefieldtype format)
156    * @return properties page
157    *
158    * @see celltype: http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html
159    */
160    def savePreview = {
161        def tft = null 
162        def identifiercolumnindex = (params.identifier!=null) ? params.identifier.toInteger() : -1
163        def selectedentities = []
164
165        // loop all entities and see which column has been assigned which entitytype
166        // and build an array containing the selected entities
167        params.entity.index.each { columnindex, entityname ->
168            def _entity = [name:entityname,columnindex:columnindex.toInteger()]
169            selectedentities.add(_entity)
170        }
171
172        params.templatefieldtype.index.each { columnindex, _templatefieldtype ->
173            switch (_templatefieldtype) {
174                case "STRING"       : tft = TemplateFieldType.STRING
175                                      break
176                case "TEXT"         : tft = TemplateFieldType.TEXT
177                                      break
178                case "INTEGER"      : tft = TemplateFieldType.INTEGER
179                                      break
180                case "FLOAT"        : tft = TemplateFieldType.FLOAT
181                                      break
182                case "DOUBLE"       : tft = TemplateFieldType.DOUBLE
183                                      break
184                case "STRINGLIST"   : tft = TemplateFieldType.STRINGLIST
185                                      break
186                case "ONTOLOGYTERM" : tft = TemplateFieldType.ONTOLOGYTERM
187                                      break
188                case "DATE"         : tft = TemplateFieldType.DATE
189                                      break
190                default: break
191            }
192           
193            // Set the templatefield type for this column
194            session.importer_header[columnindex.toInteger()].templatefieldtype = tft
195        }
196
197        // Detect the entity type
198        params.entity.index.each { columnindex, entityname ->
199            Class clazz = null
200
201            switch (entityname) {
202                case "Study"    : clazz = dbnp.studycapturing.Study
203                        break
204                case "Subject"  : clazz = dbnp.studycapturing.Subject
205                        break
206                case "Event"    : clazz = dbnp.studycapturing.Event
207                        break
208                case "Protocol" : clazz = dbnp.studycapturing.Protocol
209                        break
210                case "Sample"   : clazz = dbnp.studycapturing.Sample
211                        break
212                default: clazz = Object
213                        break
214            }
215
216            // Store properties for this column
217            session.importer_header[columnindex.toInteger()].identifier = (columnindex.toInteger() == identifiercolumnindex) ? true : false
218            session.importer_header[columnindex.toInteger()].index = columnindex.toInteger()
219            session.importer_header[columnindex.toInteger()].entity = clazz
220        }
221
222        // currently only one template is used for all entities
223        // TODO: show template fields per entity
224       
225        def templates = Template.get(session.importer_template_id)
226
227        render(view:"step2", model:[entities:selectedentities, header:session.importer_header, templates:templates])
228    }
229
230    /**
231    * @param columnproperty array of columns containing index and property (represented as a String)
232    *
233    */
234    def saveProperties = {
235
236        // Find actual Template object from the chosen template name
237        def template = Template.get(session.importer_template_id)
238
239        params.columnproperty.index.each { columnindex, property ->
240
241                // Create an actual class instance of the selected entity with the selected template
242                // This should be inside the closure because in some cases in the advanced importer, the fields can have different target entities
243                def entityClass = Class.forName(session.importer_header[columnindex.toInteger()].entity.getName(), true, this.getClass().getClassLoader())
244                def entityObj = entityClass.newInstance(template:template)
245
246                // Store the selected property for this column into the column map for the ImporterService
247                session.importer_header[columnindex.toInteger()].property = property
248
249                // Look up the template field type of the target TemplateField and store it also in the map
250                session.importer_header[columnindex.toInteger()].templatefieldtype = entityObj.giveFieldType(property)
251
252                // Is a "Don't import" property assigned to the column?
253                session.importer_header[columnindex.toInteger()].dontimport = (property=="dontimport") ? true : false
254
255                //if it's an identifier set the mapping column true or false
256                entityObj.giveFields().each {
257                    (it.preferredIdentifier && (it.name==property)) ? session.importer_header[columnindex.toInteger()].identifier = true : false
258                }
259        }
260
261        //import workbook
262        session.importer_importeddata = ImporterService.importdata(session.importer_template_id, session.importer_workbook, session.importer_sheetindex, session.importer_datamatrix_start, session.importer_header)
263
264        if (params.layout=="horizontal")
265            render(view:"step3_simple", model:[datamatrix:session.importer_importeddata])
266        else if (params.layout=="vertical")
267            render(view:"step3", model:[datamatrix:session.importer_importeddata])
268    }
269
270    /**
271     * Method which saves the data matrix to the database
272     */
273    def savePostview = {
274        def validatedSuccesfully = ImporterService.saveDatamatrix(session.importer_study, session.importer_importeddata)
275        render(view:"step4", model:[validatedSuccesfully:validatedSuccesfully, totalrows:session.importer_importeddata.size])
276    }
277
278    /**
279    * Return templates which belong to a certain entity type
280    *
281    * @param entity entity name string (Sample, Subject, Study et cetera)
282    * @return JSON object containing the found templates
283    */
284    def ajaxGetTemplatesByEntity = {
285        def entityClass = grailsApplication.config.gscf.domain.importableEntities.get(params.entity).entity
286       
287
288        // fetch all templates for a specific entity
289        def templates = Template.findAllByEntity(Class.forName(entityClass, true, this.getClass().getClassLoader()))   
290
291        // render as JSON
292        render templates as JSON
293    }
294}
Note: See TracBrowser for help on using the browser.