radicaled
radicaled

Reputation: 2689

Method return wrong type of value in Groovy

I'm working on a groovy method to look for a custom attribute and return the value if the key is found.
The problem is that the method is returning the type of value instead of the value.

    // There is more code before, but its not involved with this issue.

    def UUIDca = 'UUID'
    String customAttributeValue = grabCustomAttribute(UUIDca, event_work)
    appendLogfile("\n\nTest grabCustomAttribute: ${customAttributeValue}\n")  
  }

  // Grab the Custom Message Attribute values by name
  String grabCustomAttribute (String findElement, OprEvent event){

    appendLogfile("""\nIN grabCustomAttribute\nElement to look: ${findElement}\n""")

    def firstItem = true
    if (event.customAttributes?.customAttributes?.size()) {
      event.customAttributes.customAttributes.each { ca ->
        // Define each CMA to catch here

        appendLogfile("""\nElement: ${ca.name} - """)
        appendLogfile("""Valor: ${ca.value}\n""")

        if ("${ca.name}" == findElement) {
          String customValue = ca.value

          appendLogfile("""Custom Attribute Found\n""")
          appendLogfile(customValue)

          return customValue
        }
      }
    }
  }

appendLogfile is basically a print to a log file :)
This is the output I'm getting.

IN grabCustomAttribute Element to look: UUID

Element: UUID - Valor: c3bb9169-0ca3-4bcf-beb1-f94eda8ebf1a
Custom Attribute Found
c3bb9169-0ca3-4bcf-beb1-f94eda8ebf1a

Test grabCustomAttribute: [com.hp.opr.api.ws.model.event.OprCustomAttribute@940e503a]

Instead of returning the value, it returns the type of object. It's correct, but I'm looking for the value.
I believe the solution is really simple, but I'm very new to Groovy.

Any help will be appreciated. Thanks.

Upvotes: 0

Views: 254

Answers (1)

Rodrigo Villalba Zayas
Rodrigo Villalba Zayas

Reputation: 5636

In this case the return statement is for the closure, not for the method, so your method is actually returning the list that "each" is iterating over

The easiest approach you can take here is to use Groovy find method to find the element you are searching for. Something like this:

String grabCustomAttribute (String findElement, OprEvent event) {
    return event.customAttributes.customAttributes?.find { ca -> ca.name == findElement }.value
}

Upvotes: 1

Related Questions