Ask Your Question
1

Define a method in Groovy evaluator

asked 2019-01-09 09:29:06 -0600

srinath_222 gravatar image

updated 2019-01-09 10:13:52 -0600

metadaddy gravatar image

Hi ,

I am trying to parse field values using the below code in Groovy evaluator for field field1 :

for (record in records) {
  try {     
    StringBuilder ret = new StringBuilder(record.value['field1'].length());
    for (String word : record.value['field1'].split(" ")) {
            if (!word.isEmpty()) {
                ret.append(word.substring(0, 1).toUpperCase())
                ret.append(word.substring(1).toLowerCase())}
            if (!(ret.length()==record.value['field1'].length()))
                ret.append(" ")
        }

    record.value['field1'] = ret.toString()

    output.write(record)
  } catch (e) {
    log.error(e.toString(), e)
    error.write(record, e.toString())
  }
}

I want to apply the same code to multiple fields from the incoming data.

Can you please suggest on how to define a method in Groovy evaluator so that we can pass the incoming required fields to the method ??

edit retag flag offensive close merge delete

Comments

@metadaddy any suggestions on how to define a method in Groovy evaluator which can be used for required fields

srinath_222 gravatar imagesrinath_222 ( 2019-01-09 13:36:34 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2019-01-09 14:15:29 -0600

iamontheinet gravatar image

Hi!

Replace your code with the following and it should work:

def upperCaseFirstLetter(fieldValue)    {
  StringBuilder ret = new StringBuilder(fieldValue.length());
  for (String word : fieldValue.split(" ")) {
    if (!word.isEmpty()) {
        ret.append(word.substring(0, 1).toUpperCase())
        ret.append(word.substring(1).toLowerCase())}
    if (!(ret.length()==fieldValue.length()))
        ret.append(" ")
  }
  return ret.toString()
}

for (record in records) {
  try {     

    //Uncomment to process ALL fields
    //for ( item in record.value ) {
    //  record.value[item.key] = upperCaseFirstLetter(record.value[item.key])
    //}

    //Process individual fields
    record.value['field1'] = upperCaseFirstLetter(record.value['field1'])
    record.value['field2'] = upperCaseFirstLetter(record.value['field2'])    

    output.write(record)
  } catch (e) {
    log.error(e.toString(), e)
    error.write(record, e.toString())
  }
}

Cheers, Dash

edit flag offensive delete link more

Comments

Thanks Dash....It worked

srinath_222 gravatar imagesrinath_222 ( 2019-01-09 14:22:05 -0600 )edit

You're welcome!

iamontheinet gravatar imageiamontheinet ( 2019-01-09 14:22:49 -0600 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2019-01-09 09:29:06 -0600

Seen: 22 times

Last updated: Jan 09