Reputation: 3678
The below Java code gives errors in Groovy..
private String getSignature() {
String timestamp = getUTCTimestamp();
String nonce = getNonce();
String digest = getPasswordDigest(nonce, timestamp);
return String.format(
"UsernameToken Username=\\"%s\\", PasswordDigest=\\"%s\\", Nonce=\\"%s\\", Created=\\"%s\\"", apiUsername, digest, nonce, timestamp);
}
Specifically the String.format line, how to re-write in Groovy?
Upvotes: 2
Views: 3382
Reputation: 96434
You can use GroovyStrings in preference to String.format or string concatenation; GroovyStrings let you interpolate variables into the body of the string, as described in the documentation:
Any Groovy expression can be interpolated in all string literals, apart from single and triple single quoted strings. Interpolation is the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${} or prefixed with $ for dotted expressions. The expression value inside the placeholder is evaluated to its string representation when the GString is passed to a method taking a String as argument by calling toString() on that expression.
There are multiple ways to delimit string literals, you can avoid having to escape the double-quotes by picking a different delimiting syntax, such as dollar-slashy, slashy, or triple-double-quoted.
Btw in Groovy you don't need the semicolons, and you need to use return explicitly only if you're returning early from the method:
String getSignature() {
String timestamp = getUTCTimestamp()
String nonce = getNonce()
String digest = getPasswordDigest(nonce, timestamp)
$/UsernameToken Username="${apiUsername}", PasswordDigest="${digest}", Nonce="${nonce}", Created="${timestamp}"/$
}
Upvotes: 1
Reputation: 171154
Should be able to do
private String getSignature() {
String timestamp = getUTCTimestamp();
String nonce = getNonce();
String digest = getPasswordDigest(nonce, timestamp);
"UsernameToken Username=\"$apiUsername\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$timestamp\""
}
Upvotes: 1