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

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

- preview fixed (sometimes didn't show all values read from Excel), now shows all data

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