source: trunk/grails-app/services/dbnp/importer/ImporterService.groovy @ 589

Last change on this file since 589 was 589, checked in by duh, 13 years ago
  • removed debug line cluttering the catalina.out tomcat output...
  • Property svn:keywords set to Date Author Rev
File size: 11.5 KB
Line 
1/**
2 * Importer service
3 *
4 * The importer service handles the import of tabular, comma delimited and Excel format
5 * based files.
6 *
7 * @package     importer
8 * @author      t.w.abma@umcutrecht.nl
9 * @since       20100126
10 *
11 * Revision information:
12 * $Rev: 589 $
13 * $Author: duh $
14 * $Date: 2010-06-18 14:51:34 +0000 (vr, 18 jun 2010) $
15 */
16
17package dbnp.importer
18import org.apache.poi.hssf.usermodel.*
19import org.apache.poi.poifs.filesystem.POIFSFileSystem
20import org.apache.poi.ss.usermodel.DataFormatter
21
22import dbnp.studycapturing.TemplateFieldType
23import dbnp.studycapturing.Template
24import dbnp.studycapturing.Study
25import dbnp.studycapturing.Subject
26import dbnp.studycapturing.Event
27
28import dbnp.studycapturing.Sample
29
30import dbnp.data.Term
31
32class ImporterService {
33
34    boolean transactional = true
35
36    /**
37    * @param is input stream representing the (workbook) resource
38    * @return high level representation of the workbook
39    */
40    HSSFWorkbook getWorkbook(InputStream is) {
41        POIFSFileSystem fs = new POIFSFileSystem(is)
42        HSSFWorkbook    wb = new HSSFWorkbook(fs);
43        return wb;
44    }
45
46    /**
47     * @param wb high level representation of the workbook
48     * @param sheetindex sheet to use within the workbook
49     * @return header representation as a MappingColumn hashmap
50     */
51    def getHeader(HSSFWorkbook wb, int sheetindex, theEntity=null){
52
53        def sheet = wb.getSheetAt(sheetindex)
54        def datamatrix_start = sheet.getFirstRowNum() + 1
55        //def header = []
56        def header = [:]
57        def df = new DataFormatter()
58        def property = new String()
59
60        for (HSSFCell c: sheet.getRow(datamatrix_start)) {
61            def index   =   c.getColumnIndex()
62            def datamatrix_celltype = sheet.getRow(datamatrix_start).getCell(index).getCellType()
63            def headercell = sheet.getRow(sheet.getFirstRowNum()).getCell(index)
64            def tft = TemplateFieldType.STRING //default templatefield type
65
66           
67            // Check for every celltype, currently redundant code, but possibly this will be
68            // a piece of custom code for every cell type like specific formatting
69               
70            switch (datamatrix_celltype) {
71                    case HSSFCell.CELL_TYPE_STRING:
72                            //parse cell value as double
73                            def parsable = true
74                            def fieldtype = TemplateFieldType.STRING
75
76                            // is this string perhaps a double?
77                            try {
78                                formatValue(c.getStringCellValue(), TemplateFieldType.DOUBLE)
79                            } catch (NumberFormatException nfe) { parsable = false }
80                            finally {
81                                if (parsable) fieldtype = TemplateFieldType.DOUBLE
82                            }
83
84                            header[index] = new dbnp.importer.MappingColumn(name:df.formatCellValue(headercell),
85                                                                            templatefieldtype:fieldtype,
86                                                                            index:index,
87                                                                            entity:theEntity,
88                                                                            property:property);
89
90                            break
91                    case HSSFCell.CELL_TYPE_NUMERIC:                   
92                            if (HSSFDateUtil.isCellDateFormatted(c)) {
93                                header[index] = new dbnp.importer.MappingColumn(name:df.formatCellValue(headercell),
94                                                                                templatefieldtype:TemplateFieldType.DATE,
95                                                                                index:index,
96                                                                                entity:theEntity,
97                                                                                property:property)
98                            }
99                            else
100                                header[index] = new dbnp.importer.MappingColumn(name:df.formatCellValue(headercell),
101                                                                                templatefieldtype:TemplateFieldType.INTEGER,
102                                                                                index:index,
103                                                                                entity:theEntity,
104                                                                                property:property);
105                            break
106                    case HSSFCell.CELL_TYPE_BLANK:
107                            header[index] = new dbnp.importer.MappingColumn(name:df.formatCellValue(headercell),
108                                                                            templatefieldtype:TemplateFieldType.STRING,
109                                                                            index:index,
110                                                                            entity:theEntity,
111                                                                            property:property);
112                            break
113                    default:
114                            header[index] = new dbnp.importer.MappingColumn(name:df.formatCellValue(headercell),
115                                                                            templatefieldtype:TemplateFieldType.STRING,
116                                                                            index:index,
117                                                                            entity:theEntity,
118                                                                            property:property);
119                            break
120            } // end of switch
121        } // end of cell loop
122        return header
123    }
124
125    /**
126     * This method is meant to return a matrix of the rows and columns
127     * used in the preview
128     *
129     * @param wb workbook object
130     * @param sheetindex sheet index used
131     * @param rows amount of rows returned
132     * @return two dimensional array (matrix) of HSSFCell objects
133     */
134
135    HSSFCell[][] getDatamatrix(HSSFWorkbook wb, int sheetindex, int count) {
136        def sheet = wb.getSheetAt(sheetindex)
137        def rows  = []
138        def df = new DataFormatter()
139        def datamatrix_start = 1
140
141        // walk through all rows
142        (count <= sheet.getLastRowNum()) ?
143        ((datamatrix_start+sheet.getFirstRowNum())..count).each { rowindex ->
144            def row = []
145
146            // walk through every cell
147            for (HSSFCell c: sheet.getRow(rowindex))
148                row.add(c)
149                //row.add(df.formatCellValue(c))
150            rows.add(row)
151        } : 0
152
153        return rows
154    }
155
156    /**
157    * This method will move a file to a new location.
158    *
159    * @param file File object to move
160    * @param folderpath folder to move the file to
161    * @param filename (new) filename to give
162    * @return if file has been moved succesful, the new path and filename will be returned, otherwise an empty string will be returned
163    */
164    def moveFile(File file, String folderpath, String filename) {
165        try {
166                def rnd = ""; //System.currentTimeMillis()
167                file.transferTo(new File(folderpath, rnd+filename))
168                return folderpath + filename
169            } catch(Exception exception) {
170                log.error "File move error, ${exception}"
171                return ""
172                }
173    }
174
175    /**
176    * @return random numeric value
177    */
178    def random = {
179            return System.currentTimeMillis() + Runtime.runtime.freeMemory()
180        }
181
182    /**
183    * Method to read data from a workbook and to import data into the database
184    * by using mapping information
185    *
186    * @param template_id template identifier to use fields from
187    * @param wb POI horrible spreadsheet formatted workbook object
188    * @param mcmap linked hashmap (preserved order) of MappingColumns
189    * @param sheetindex sheet to use when using multiple sheets
190    * @param rowindex first row to start with reading the actual data (NOT the header)
191    * @return two dimensional array containing records (with entities)
192    *
193    * @see dbnp.importer.MappingColumn
194    */
195    def importdata(template_id, HSSFWorkbook wb, int sheetindex, int rowindex, mcmap) {
196        def sheet = wb.getSheetAt(sheetindex)
197        def table = []
198
199       
200        // walk through all rows       
201        (rowindex..sheet.getLastRowNum()).each { i ->
202            table.add(createRecord(template_id, sheet.getRow(i), mcmap))
203        }
204
205        /*table.each {
206            it.each { entity ->
207                entity.giveFields().each { field ->
208                    print field.name + ":" + entity.getFieldValue(field.name) + "/"
209                }
210                println
211            }
212        }*/
213
214        return table   
215    }
216   
217     /**
218                     // start transaction
219                        def transaction = sessionFactory.getCurrentSession().beginTransaction()
220                              // persist data to the database
221                                try {
222                                   // commit transaction
223                                        println "commit"
224                                        transaction.commit()
225                                        success()
226                                } catch (Exception e) {
227                                        // rollback
228                                        // stacktrace in flash scope
229                                        flash.debug = e.getStackTrace()
230
231                                        println "rollback"
232                                        transaction.rollback()
233                                        error()
234                                }
235      */
236
237    /**
238     * Method to store a matrix containing the entities in a record like structure. Every row in the table
239     * contains one or more entity objects (which contain fields with values). So actually a row represents
240     * a record with fields from one or more different entities.
241     *
242     * @param study entity Study
243     * @param datamatrix two dimensional array containing entities with values read from Excel file     *
244     */   
245    def saveDatamatrix(Study study, datamatrix) {
246        study.refresh()
247       
248        datamatrix.each { record ->
249            record.each { entity ->
250                switch (entity.getClass()) {
251                    case Study   :  print "Persisting Study `" + entity.title + "`: "
252                                    persistEntity(entity)
253                                    break
254                    case Subject :  print "Persisting Subject `" + entity.name + "`: "
255                                    persistEntity(entity)
256                                    study.addToSubjects(entity)
257                                    break
258                    case Event   :  print "Persisting Event `" + entity.eventdescription + "`: "
259                                    persistEntity(entity)
260                                    break
261                    case Sample  :  print "Persisting Sample `" + entity.name +"`: "
262                                    persistEntity(entity)
263                                    break
264                    default      :  println "Skipping persisting of `" + entity.getclass() +"`"
265                                    break
266                }
267            }
268        }
269    }
270
271    /**
272     * Method to persist entities into the database
273     * Checks whether entity already exists (based on identifier column 'name')
274     *
275     * @param entity entity object like Study, Subject, Protocol et cetera
276     *
277     */
278    def persistEntity(entity) { 
279        if (entity.save(flush:true)) {  //.merge?           
280        } else entity.errors.allErrors.each {
281                println it
282        }
283    }
284
285    /**
286     * This method creates a record (array) containing entities with values
287     *
288     * @param template_id template identifier
289     * @param excelrow POI based Excel row containing the cells
290     * @param mcmap map containing MappingColumn objects
291     */
292    def createRecord(template_id, HSSFRow excelrow, mcmap) {
293        def df = new DataFormatter()
294        def template = Template.get(template_id)
295        def record = [] 
296       
297        def study = new Study(title:"New study", template:template)
298        def subject = new Subject(name:"New subject", species:Term.findByName("Homo sapiens"), template:template)
299        def event = new Event(eventdescription:"New event", template:template)
300        def sample = new Sample(name:"New sample", template:template)
301
302        for (HSSFCell cell: excelrow) {     
303            def mc = mcmap[cell.getColumnIndex()]
304            def value = formatValue(df.formatCellValue(cell), mc.templatefieldtype)
305
306            switch(mc.entity) {
307                case Study      :   (record.any {it.getClass()==mc.entity}) ? 0 : record.add(study)                                 
308                                    study.setFieldValue(mc.property, value)
309                                    break
310                case Subject    :   (record.any {it.getClass()==mc.entity}) ? 0 : record.add(subject)
311                                    subject.setFieldValue(mc.property, value)                               
312                                    break
313                case Event      :   (record.any {it.getClass()==mc.entity}) ? 0 : record.add(event)                                 
314                                    event.setFieldValue(mc.property, value)
315                                    break
316                case Sample     :   (record.any {it.getClass()==mc.entity}) ? 0 : record.add(sample)                               
317                                    sample.setFieldValue(mc.property, value)
318                                    break
319                case Object     :   // don't import
320                                    break
321            } // end switch
322        } // end for
323
324        return record
325    }
326
327    /**
328    * Method to parse a value conform a specific type
329    * @param value string containing the value
330    * @return object corresponding to the TemplateFieldType
331    */
332    def formatValue(String value, TemplateFieldType type) throws NumberFormatException {
333            switch (type) {
334                case TemplateFieldType.STRING       :   return value.trim()
335                case TemplateFieldType.TEXT         :   return value.trim()
336                case TemplateFieldType.INTEGER      :   return Integer.valueOf(value.replaceAll("[^0-9]",""))
337                case TemplateFieldType.FLOAT        :   return Float.valueOf(value.replace(",","."));
338                case TemplateFieldType.DOUBLE       :   return Double.valueOf(value.replace(",","."));
339                case TemplateFieldType.STRINGLIST   :   return value.trim()
340                case TemplateFieldType.ONTOLOGYTERM :   return value.trim()
341                case TemplateFieldType.DATE         :   return value
342                default                             :   return value
343            }
344    }
345}
Note: See TracBrowser for help on using the repository browser.