• Skip to primary navigation
  • Skip to main content
  • Skip to footer

JH Tech Services

A knowledgebase

  • Portfolio
  • Knowledgebase
  • About

Importing text file from bootstrap.groovy in Grails 2.4.2

October 7, 2014 by jer0dh

This supposedly simple task ended up causing hours of work for me. See this post on some of the problems I had before finding this solution.

I want to populate, import mock data into my domain class (stored in SQL database). I obtained a csv file with mock data from a great web service called Mockaroo. Next I needed to determine where to put it. I found the following posts that were very helpful, though, both did this in different ways and I found the the best way for me was a combination of their solutions.

http://stackoverflow.com/questions/4784226/parse-csv-and-export-into-mysql-database-in-grails
http://sbglasius.tumblr.com/post/16858716230/grails-read-from-filesystem
http://jermdemo.blogspot.com/2009/05/loading-files-in-grails-bootstrap.html

I stored my MOCK_DATA.csv file under \grails-app\conf\resources (I had to create the directory ‘resources’)
I created the domain class, ImportDetail, that matched the fields in the MOCK_DATA.csv file and added my validation rules under the domain class’s constraints.
In my bootstrap.groovy, I wrote the following code ( be sure to add the ‘def grailsApplication’ line under the bootstrap class to inject this service )


		if (ImportDetail.count() == 0 ){
			log.debug("ImportDetail.count is zero")
			def filePath = "resources/MOCK_DATA.csv"
			def myFile = grailsApplication.mainContext.getResource("classpath:$filePath").file
			def i = 1
			myFile.splitEachLine(',') {fields ->
				def importDetail = new ImportDetail(
					id			:		fields[0],
					billedQuantity		:		fields[1],
					bolNumber		:		fields[3],
					buyerName		:		fields[4],
					consignorName		:		fields[5],
					diverted		:		fields[6],
					destinationState	:		fields[7]
					)
				importDetail.validate()
				if (importDetail.hasErrors()){
					log.debug("Could not import line ${i} due to ${importDetail.errors}")
				} else {
					log.debug("Importing line ${i}: ${importDetail.toString()}")
					importDetail.save(failOnError: true, flush: true)
				}
                                ++i
			}
		}
  • Grails
  • Knowledgebase

Footer

  • Portfolio
  • Knowledgebase
  • About

© 2023