Loading files in grails bootstrap

I've had to do this for two separate projects.

A web application always has weird ideas of where it is in the path. I tend to look for examples that work without assumptions. This works for the bootstrap scripts I use to start up grails apps. Locating stuff in /web-app in the deployment context is a different story.

I think the best way is as follows:
create a directory: grails-app/conf/resources

For a tab delimited-file I used the following routine to load and create domain objects


class BootStrap {

def init = {servletContext ->
//AC204211.3 c0189C22 ACTIVEFIN UNKNOWN 153071100 153252400 ctg708 9800 191100

def filePath = "resources/fpc_report.txt"

def text = ApplicationHolder.application.parentContext.getResource("classpath:$filePath").inputStream.text
text.eachLine {
println it
def BacFields = it.split("\t")
new Bacs(accession: BacFields[0],
cloneName: BacFields[1],
status: BacFields[2],
chr: BacFields[3],
chrStart: BacFields[4],
chrEnd: BacFields[5],
contig: BacFields[6],
contigStart: BacFields[7],
contigEnd: BacFields[8]).save()
}
}
}


For a CSV file I used the opencsv library
http://opencsv.sourceforge.net/
I added to my maven pom the following dependency


net.sf.opencsv
opencsv
1.8



and used something similar to get the grails appHolder object to give up a Java File


import org.codehaus.groovy.grails.commons.ApplicationHolder

class BootStrap {

def init = { servletContext ->

def filePath = "resources/E357Lims.CSV"
def appHolder=ApplicationHolder.application.parentContext.getResource("classpath:$filePath")

def reader = new CSVReader(new FileReader(appHolder.getFile()))
def header = true
reader.readAll().each{ csvrow ->
if(!header){
new FlatReport(name:csvrow[0].trim()).save()
}
header = false
}
}

Comments

  1. I also read a file in the boot strap in the same way.

    But I would like to read it from a service class. And Grails cannot find that file.

    I described my issue at the Grails Nabble forum.

    http://n4.nabble.com/Read-a-text-file-td1836925.html#a1836925

    ReplyDelete

Post a Comment

Popular Posts