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

Revision 1103, 13.1 KB (checked in by t.w.abma@…, 3 years ago)

- added error page for importer
- empty ontologies detected in Excel still should be shown as "unknown" fields in the failed ontology-mapping step

  • 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
25
26import dbnp.studycapturing.TemplateFieldType
27import grails.converters.JSON
28import org.apache.poi.ss.usermodel.Workbook
29import grails.plugins.springsecurity.Secured
30
31@Secured(['IS_AUTHENTICATED_REMEMBERED'])
32class ImporterController {
33    def ImporterService
34    def AuthenticationService
35
36    /**
37     * Default page
38     **/
39
40    def index = {
41        //session.import_referer = request.forwardURI
42        // should do a check what is in the url, strip it?
43        session.import_referer = params.redirectTo
44        render(view:"index_simple",
45               model:[studies:Study.findAllWhere(owner:AuthenticationService.getLoggedInUser()),
46               entities: grailsApplication.config.gscf.domain.importableEntities])
47    }
48
49    def simpleWizard = {
50        //render(view:"index_simple", model:[studies:Study.findAllWhere(owner:AuthenticationService.getLoggedInUser()), entities: grailsApplication.config.gscf.domain.importableEntities])
51    }
52
53    def advancedWizard = {
54        //render(view:"index_advanced", model:[templates:Template.list()])
55    }
56
57    /**
58    * This method will move the uploaded file to a temporary path and send the header
59    * and the first n rows to the preview
60    * @param importfile uploaded file to import
61    * @param study.id study identifier
62    */
63    def upload_advanced = {
64        def wb = handleUpload('importfile')
65
66        session.importer_header = ImporterService.getHeader(wb, 0)
67        session.importer_study = Study.get(params.study.id.toInteger())
68        session.importer_template_id = params.template_id
69        session.importer_workbook = wb
70
71        render (view:"step1_advanced", model:[header:session.importer_header, datamatrix:ImporterService.getDatamatrix(wb, session.importer_header, 0, 5)])
72    }
73
74    /**
75    * This method will move the uploaded file to a temporary path and send the header
76    * and the rows to the postview
77    *
78    * @param importfile uploaded file to import
79    * @param entity string representation of the entity chosen
80    */
81    def upload_simple = {
82        def wb = handleUpload('importfile')
83        def selectedentities = []
84        def entity = grailsApplication.config.gscf.domain.importableEntities.get(params.entity).entity
85        def entityClass = Class.forName(entity, true, this.getClass().getClassLoader())
86
87        // Initialize some session variables
88        session.importer_workbook = wb
89        session.importer_study = Study.get(params.study.id.toInteger())
90       
91        if (session.importer_study.canWrite(AuthenticationService.getLoggedInUser())) {
92            session.importer_template_id = params.template_id
93            session.importer_sheetindex = params.sheetindex.toInteger() -1 // 0 == first sheet
94            session.importer_datamatrix_start = params.datamatrix_start.toInteger() -1 // 0 == first row
95            session.importer_headerrow = params.headerrow.toInteger()
96
97            // Get the header from the Excel file using the arguments given in the first step of the wizard
98            session.importer_header = ImporterService.getHeader(wb,
99                                                                session.importer_sheetindex,
100                                                                session.importer_headerrow,
101                                                                session.importer_datamatrix_start,
102                                                                entityClass)
103       
104            // Initialize 'selected entities', used to show entities above the columns
105            session.importer_header.each {
106                selectedentities.add([name:params.entity, columnindex:it.key.toInteger()])
107            }
108
109            def templates = Template.get(session.importer_template_id)
110       
111            render(view:"step2_simple", model:[entities: selectedentities,
112                                        header:session.importer_header,
113                                        datamatrix:ImporterService.getDatamatrix(
114                                        wb, session.importer_header,
115                                        session.importer_sheetindex,
116                                        session.importer_datamatrix_start,
117                                        5),
118                                        templates:templates])
119        } // end of if
120        else {
121            render (template:"common/error",
122                    model:[error:"Wrong permissions: you are not allowed to write to the study you selected (${session.importer_study})."])
123        }
124    }
125
126    /**
127     * This method handles a file being uploaded and storing it in a temporary directory
128     * and returning a workbook
129     *
130     * @param formfilename name used for the file field in the form
131     * @return workbook object reference
132     */
133    private Workbook handleUpload(formfilename) {
134
135        def downloadedfile = request.getFile(formfilename);
136        def tempfile = new File(System.getProperty('java.io.tmpdir') + File.separatorChar + System.currentTimeMillis() + ".nmcdsp")
137        downloadedfile.transferTo(tempfile)
138
139        return ImporterService.getWorkbook(new FileInputStream(tempfile))
140    }
141
142    /**
143     * Method to save the missing properties
144     * @param entity entity class we are using (dbnp.studycapturing.Subject etc.)
145     */
146
147    def saveMissingProperties = {
148
149        session.importer_importeddata.each { table ->
150            table.each { entity ->
151                entity.giveFields().each { field ->                 
152                    entity.setFieldValue (field.toString(), params["entity_" + entity.hashCode() + "_" + field.escapedName()])
153                }               
154            }
155        }
156
157        render(view:"step3", model:[datamatrix:session.importer_importeddata]) 
158    }
159
160    /*
161     * Store the corrected cells back into the datamatrix. Be sure to check
162     * if the corrected ontology is not blank. If so, it should keep
163     * the original value which was read from the Excel file.
164     *
165     * @param cell array of cells with corrected cells (ontologies)
166     *
167    */
168    def saveCorrectedCells = {
169        def correctedcells = [:]
170
171        // Loop through the form with cell fields and values
172        params.cell.index.each { mappingcolumnhash, value ->
173            correctedcells.put(mappingcolumnhash, value)
174        }
175
176        // Store the corrected cells back into the datamatrix
177        ImporterService.saveCorrectedCells(
178                    session.importer_importeddata,
179                    session.importer_failedcells,
180                    correctedcells)
181
182        render(view:"step3_simple", model:[datamatrix:session.importer_importeddata])
183
184    }
185
186    /**
187    * User has assigned all entities and templatefieldtypes to the columns and continues to the next step (assigning properties to columns)
188    * All information of the columns is stored in a session as MappingColumn object
189    *
190    * @param entities list of entities and columns it has been assigned to (columnindex.entitytype)
191    * @param templatefieldtype list of celltypes and columns it has been assigned to (columnindex:templatefieldtype format)
192    * @return properties page
193    *
194    * @see celltype: http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html
195    */
196    def savePreview = {
197        def tft = null 
198        def identifiercolumnindex = (params.identifier!=null) ? params.identifier.toInteger() : -1
199        def selectedentities = []
200
201        // loop all entities and see which column has been assigned which entitytype
202        // and build an array containing the selected entities
203        params.entity.index.each { columnindex, entityname ->
204            def _entity = [name:entityname,columnindex:columnindex.toInteger()]
205            selectedentities.add(_entity)
206        }
207
208        params.templatefieldtype.index.each { columnindex, _templatefieldtype ->
209            switch (_templatefieldtype) {
210                case "STRING"       : tft = TemplateFieldType.STRING
211                                      break
212                case "TEXT"         : tft = TemplateFieldType.TEXT
213                                      break
214                case "INTEGER"      : tft = TemplateFieldType.INTEGER
215                                      break
216                case "FLOAT"        : tft = TemplateFieldType.FLOAT
217                                      break
218                case "DOUBLE"       : tft = TemplateFieldType.DOUBLE
219                                      break
220                case "STRINGLIST"   : tft = TemplateFieldType.STRINGLIST
221                                      break
222                case "ONTOLOGYTERM" : tft = TemplateFieldType.ONTOLOGYTERM
223                                      break
224                case "DATE"         : tft = TemplateFieldType.DATE
225                                      break
226                default: break
227            }
228           
229            // Set the templatefield type for this column
230            session.importer_header[columnindex.toInteger()].templatefieldtype = tft
231        }
232
233        // Detect the entity type
234        params.entity.index.each { columnindex, entityname ->
235            Class clazz = null
236
237            switch (entityname) {
238                case "Study"    : clazz = dbnp.studycapturing.Study
239                        break
240                case "Subject"  : clazz = dbnp.studycapturing.Subject
241                        break
242                case "Event"    : clazz = dbnp.studycapturing.Event
243                        break
244                case "Protocol" : clazz = dbnp.studycapturing.Protocol
245                        break
246                case "Sample"   : clazz = dbnp.studycapturing.Sample
247                        break
248                default: clazz = Object
249                        break
250            }
251
252            // Store properties for this column
253            session.importer_header[columnindex.toInteger()].identifier = (columnindex.toInteger() == identifiercolumnindex) ? true : false
254            session.importer_header[columnindex.toInteger()].index = columnindex.toInteger()
255            session.importer_header[columnindex.toInteger()].entity = clazz
256        }
257
258        // currently only one template is used for all entities
259        // TODO: show template fields per entity
260       
261        def templates = Template.get(session.importer_template_id)
262
263        render(view:"step2", model:[entities:selectedentities, header:session.importer_header, templates:templates])
264    }
265   
266    /**
267     * Method which stores the properties set per column and then imports the data.
268     *
269     * @param columnproperty array of columns containing index and property (represented as a String)
270    *
271    */
272    def saveProperties = {       
273
274        // Find actual Template object from the chosen template name
275        def template = Template.get(session.importer_template_id)
276
277        params.columnproperty.index.each { columnindex, property ->
278
279                // Create an actual class instance of the selected entity with the selected template
280                // This should be inside the closure because in some cases in the advanced importer, the fields can have different target entities
281                def entityClass = Class.forName(session.importer_header[columnindex.toInteger()].entity.getName(), true, this.getClass().getClassLoader())
282                def entityObj = entityClass.newInstance(template:template)
283
284                // Store the selected property for this column into the column map for the ImporterService
285                session.importer_header[columnindex.toInteger()].property = property
286
287                // Look up the template field type of the target TemplateField and store it also in the map
288                session.importer_header[columnindex.toInteger()].templatefieldtype = entityObj.giveFieldType(property)
289
290                // Is a "Don't import" property assigned to the column?
291                session.importer_header[columnindex.toInteger()].dontimport = (property=="dontimport") ? true : false
292
293                //if it's an identifier set the mapping column true or false
294                entityObj.giveFields().each {
295                    (it.preferredIdentifier && (it.name==property)) ? session.importer_header[columnindex.toInteger()].identifier = true : false
296                }
297        }
298
299        // Import the workbook and store the table with entity records and store the failed cells
300        def (table, failedcells) = ImporterService.importData(session.importer_template_id, session.importer_workbook, session.importer_sheetindex, session.importer_datamatrix_start, session.importer_header)
301
302        session.importer_importeddata = table       
303        session.importer_failedcells = failedcells
304
305        if (failedcells.size()!=0)
306            render(view:"step2a_simple", model:[failedcells:session.importer_failedcells])
307        else {
308            if (params.layout=="horizontal")
309                render(view:"step3_simple", model:[datamatrix:session.importer_importeddata])
310            else if (params.layout=="vertical")
311                render(view:"step3", model:[datamatrix:session.importer_importeddata])
312        }
313    }
314
315    /**
316     * Method which saves the data matrix to the database
317     */
318    def savePostview = {
319        def validatedSuccesfully = ImporterService.saveDatamatrix(session.importer_study, session.importer_importeddata)
320        render(view:"step4", model:[validatedSuccesfully:validatedSuccesfully, totalrows:session.importer_importeddata.size, referer: session.import_referer])
321    }
322
323    /**
324    * Return templates which belong to a certain entity type
325    *
326    * @param entity entity name string (Sample, Subject, Study et cetera)
327    * @return JSON object containing the found templates
328    */
329    def ajaxGetTemplatesByEntity = {
330        def entityClass = grailsApplication.config.gscf.domain.importableEntities.get(params.entity).entity
331       
332
333        // fetch all templates for a specific entity
334        def templates = Template.findAllByEntity(Class.forName(entityClass, true, this.getClass().getClassLoader()))   
335
336        // render as JSON
337        render templates as JSON
338    }
339}
Note: See TracBrowser for help on using the browser.