Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy read a file, resolve variables in file content

Tags:

groovy

I am new to Groovy and I could not get around this issue. I appreciate any help.

I want to read a file from Groovy. While I am reading the content, for each line I want to substitute the string '${random_id}' and '${entryAuthor}' with different string values.

protected def doPost(String url, URL bodyFile, Map headers = new HashMap() ) {
    StringBuffer sb = new StringBuffer()
    def randomId = getRandomId()
    bodyFile.eachLine { line ->
        sb.append( line.replace("\u0024\u007Brandom_id\u007D", randomId)
                     .replace("\u0024\u007BentryAuthor\u007D", entryAuthor) )
        sb.append("\n")
    }
    return doPost(url, sb.toString())
}

But I got the following error:

groovy.lang.MissingPropertyException: 
No such property: random_id for class: tests.SimplePostTest
Possible solutions: randomId
    at foo.test.framework.FooTest.doPost_closure1(FooTest.groovy:85)
    at groovy.lang.Closure.call(Closure.java:411)
    at groovy.lang.Closure.call(Closure.java:427)
    at foo.test.framework.FooTest.doPost(FooTest.groovy:83)
    at foo.test.framework.FooTest.doPost(FooTest.groovy:80)
    at tests.SimplePostTest.Post & check Entry ID(SimplePostTest.groovy:42)

Why would it complain about a property, when I am not doing anything? I also tried "\$\{random_id\}", which works in Java String.replace(), but not in Groovy.

like image 528
Shinta Smith Avatar asked Mar 22 '23 13:03

Shinta Smith


2 Answers

You are doing it the hard way. Just evaluate your file's contents with Groovy's SimpleTemplateEngine.

import groovy.text.SimpleTemplateEngine

def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}'

def binding = ["firstname":"Sam", "lastname":"Pullara", "city":"San Francisco", "month":"December", "signed":"Groovy-Dev"]

def engine = new SimpleTemplateEngine()
template = engine.createTemplate(text).make(binding)

def result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in December,\nGroovy-Dev'

assert result == template.toString()
like image 101
Matthew Payne Avatar answered Apr 26 '23 19:04

Matthew Payne


you better use groovy.text.SimpleTemplateEngine class; check this for more details http://groovy.codehaus.org/Groovy+Templates

like image 44
Lucas Oliveira Avatar answered Apr 26 '23 19:04

Lucas Oliveira