How to convert input to uppercase in groovy - groovy

I am taking a JSON input and I want it to convert it to uppercase. Can someone please help me with my code
int synchronizeSingleUnit(ApiResultDTO apiResultDTO, def inputJSON, int totalUpdates) {
def sql = synchronizationApiSqlHelperService.getUnitsSql()
String unit = getEmptyIfValueNull(inputJSON.unit)
def session = sessionFactory_apiDb.openSession() as SessionImpl
def connection = session.connection()
def sqlConnection = new Sql(connection)
try {
sqlConnection.execute(sql, [unit:unit])
} catch (Exception ex) {
// Preload result with statement to be executed
apiResultDTO.setJsonFailingPart(inputJSON)
apiResultDTO.setFailedSql(sql, [unit:unit])
throw new ExceptionWrapper(apiResultDTO, ex)
} finally {
session.close()
connection.close()
}

You can use java String.toUpperCase() as in:
String unit = getEmptyIfValueNull(inputJSON.unit)
String uCaseUnit = unit.toUpperCase()
< -- edit -- >
As a comment and addition, I don't know the specifics of method getEmptyIfValueNull but judging from the name you just want to return an empty string when the expression inputJSON.unit returns null.
Groovy has two special operators which make expressions like these easier to write.
the safe navigation operator ?. and
the elvis operator ?: (see how that looks like an Elvis smiley?)
using these two you could rewrite your code somewhat more concisely as:
String unit = inputJSON.unit?.toUpperCase() ?: ''
explanation:
inputJSON.unit?.toUpperCase() - evaluate inputJSON.unit and if that expression returns null, just return null from the entire expression (never executing the toUpperCase method). If inputJSON.unit returns a non-null value, things work as they would just by using inputJSON.unit.toUpperCase().
... ?: '' - take an expression and if it is not empty string or null,return it, otherwise return the empty string.
Where the first operator .? is specifically for handling null values and the second operator ?: uses groovy truth which includes, but is more inclusive than just null values.
There are a few ways of writing the above, for example:
String unit = (inputJSON.unit ?: '').toUpperCase()
but to my mind the first version "flows" better. To each his own.

Related

Groovy Gotcha: String interpolation does not always execute, e.g. in `<list>.contains()`

Answer: it has to do with GString type and "lazy evaluation."
See http://docs.groovy-lang.org/latest/html/documentation/index.html#_string_interpolation for the formal documentation.
See https://blog.mrhaki.com/2009/08/groovy-goodness-string-strings-strings.html for someone's write-up on this.
Firm solution in the code below as commenter said is to explicitly cast it on creation using String targ = "${TARGET_DATA}"
I'm seeing what seems on the surface to be a delayed string interpolation or something in Groovy. I've figured out workarounds for my immediate needs, but the behaviour is a real gotcha, and a potential source for serious bugs...
I strongly suspect it arises from Groovy being a meta-language for Java, and some objects not using the usual string-matching routines.
This was discovered when we were trying to use a string interpolation on some parameter in Jenkins, and checking it against a list of pre-approved values - hence the resulting example below.
Consider this code:
TARGET_DATA= "hello"
data = ["hello"]
targ = "${TARGET_DATA}"
// Case 1: Check for basic interpolated string
if( data.contains(targ) ) {
println "Contained interpolated string"
} else {
println "Interpolation failed"
}
// Case 2: Check to see if using something that actively forces its interpolation changes the variable
println "interpolating targ = ${targ}"
if( data.contains(targ) ) {
println "Contained re-interpolated string"
} else {
println "re-Interpolation failed"
}
// Case 3: Use direct variable assignment
targ = TARGET_DATA
if( data.contains(targ) ) {
println "Contained assigned variable"
} else {
println "Assignment failed"
}
Its output is this:
Interpolation failed
interpolating targ = message: hello
re-Interpolation failed
Contained assigned variable
This indicates that:
In case 1 , the placeholder string is checked for in the list, and fails, as it hasn't been interpolated
In case 2, after forcing the interpreter to perform an interpolation against targ, the content of that variable isn't updated. At this stage, targ still contains a literal placeholder string
In case 3, after assigning the initial variable directly to the target variable, we get a successful match
My guess is that targ literally contains a string starting with a dollar sign, curly brace, and a variable name, etc. This only resolves under certain conditions, like the use of a println , but not in the case of a <list>.contains() which just gets the uninterpolated variable as-is, and does not know during check, to interpolate it.
Using targ = new String("${TARGET_DATA}") does actively interpolate the string however, as the call to function somehow registers as something active.
However this code does interpolate correctly:
TARGET_DATA= "hello"
targ = "${TARGET_DATA}"
def eq(var1) { return var1 == "hello" }
basic_check = eq(targ)
println "${basic_check}" // resolves as true
which means that at some point, the string is interpolated - possibly the == operation has been reimplemented by Groovy to call String's equality function always:
Such that, Groovy re-implemented the String object - and its equality check - but the <list>.contains() function doesn't use that comparator (or it is not caught during script interpretation, due to being compiled code in the Java standard library) and so fails to trigger the interpolation substitution...
Can someone shed some light here please?
targ is of type Gstring, rather than a java String. GString retains the information for how to build itself from the interpolated form.
Because targ isn't a String, it will never pass the equality check required by List.contains, where the List contrains a String.

Find if key contains value in a map and return a boolean

I have a map within an object in Groovy. The map has keys made from long strings, I want to see if a key in my map contains a certain value within the string and return a boolean.
For example if my map key is 'X1234_RANDOM_STRING', if my parameter is X1234 I want to look in my map and see if the a key with that value exists and return true of false.
Currently I am using .find however this doesn't return a boolean, I thought I could use .containsKey() but this won't work when my parameter may only contain a portion of the string.
map.find {
it.key.toString().contains(code)
}
If you need boolean output, use collect instead of find.
Here you go:
def code = 'X1234'
def map = [X1234_RANDOM_STRING: 1]
print map.collect { it.key.toString().contains(code) }
Consider the following (very close to your attempt):
def map = ['X1234_RANDOM_STRING': 5150]
def code = 'X1234'
def found = map.find { it.toString().contains(code) } as Boolean
assert found
def notFound = map.find { it.toString().contains('foo') } as Boolean
assert ! notFound
The cast works because of Groovy Truth.

How to convert String to int in Groovy the right way

First of all, I am aware of question 'Groovy String to int' and it's responses. I am a newbe to Groovy language and right now playing around some basics. The most straightforward ways to convert String to int seem to be:
int value = "99".toInteger()
or:
int value = Integer.parseInt("99")
These both work, but comments to these answers got me confused. The first methodString.toInteger() is deprecated, as stated in groovy documentation. I also assume that
Integer.parseInt() makes use of the core Java feature.
So my question is: is there any legal, pure groovy way to perform such a simple task as converting String to an int?
I might be wrong, but I think most Grooviest way would be using a safe cast "123" as int.
Really you have a lot of ways with slightly different behaviour, and all are correct.
"100" as Integer // can throw NumberFormatException
"100" as int // throws error when string is null. can throw NumberFormatException
"10".toInteger() // can throw NumberFormatException and NullPointerException
Integer.parseInt("10") // can throw NumberFormatException (for null too)
If you want to get null instead of exception, use recipe from answer you have linked.
def toIntOrNull = { it?.isInteger() ? it.toInteger() : null }
assert 100 == toIntOrNull("100")
assert null == toIntOrNull(null)
assert null == toIntOrNull("abcd")
If you want to convert a String which is a math expression, not just a single number, try groovy.lang.Script.evaluate(String expression):
print evaluate("1+1"); // note that evalute can throw CompilationFailedException

how can i append to each line in scala and why is it saying unit?

im doing something stupid to try to send html email and not really understanding what im doing but I want to send a multiline string to a function and get the same string back with something appended to each line - what am i doing wrong?
def htmlizetext(intext: String) {
for(line <- intext.linesWithSeparators) {
<br>line<br/>
}
}
def htmlizetext(intext: String): String = {
for(line <- intext.linesWithSeparators) {
line + "<br/>"
}
}
Neither of the above work
You need yield, = (without = the method will still return Unit) and some form of concatenation:
def htmlizetext(intext: String) = {
for (line <- intext.linesWithSeparators) yield {
line + "<br/>
}
}.mkString
or the shorter equivalent:
def htmlizetext(intext: String) =
intext.linesWithSeparators.map(_ + "<br/>").mkString
Have a look at yield, that is probably what you are looking for.
def htmlizetext(intext: String) = {
for(line <- intext.linesWithSeparators) yield {
<br>line<br/>
}
}
You might additionally want to join all the elements from the returning list for returning a single String instead of a list of such strings
You are currently not returning a thing from your method as you do not return anything from your for statement which is the last method of your statement. Therefore, the Scala compiler infers that you are returning Unit.
Because for does't have a return value, unless you use yield...
A better solution would be to "map" your collection as follows:
intext.linesWithSeparators.map(line=> s"$line<br/>").mkString("")
this will turn your string in the desired format and then join all of them using mkString. If you need it, you can specify a separator instead of empty string

EachWithIndex groovy statement

I am new to groovy and I've been facing some issues understanding the each{} and eachwithindex{} statements in groovy.
Are each and eachWithIndex actually methods? If so what are the arguments that they take?
In the groovy documentation there is this certain example:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } //prints each index and number
Well, I see that numbers is an array. What are num and idx in the above statement? What does the -> operator do?
I do know that $idx and $num prints the value, but how is it that idx and num are automatically being associated with the index and contents of the array? What is the logic behind this? Please help.
These are plain methods but they follow quite a specific pattern - they take a Closure as their last argument. A Closure is a piece of functionality that you can pass around and call when applicable.
For example, method eachWithIndex might look like this (roughly):
void eachWithIndex(Closure operation) {
for (int i = 0; this.hasNext(); i++) {
operation(this.next(), i); // Here closure passed as parameter is being called
}
}
This approach allows one to build generic algorithms (like iteration over items) and change the concrete processing logic at runtime by passing different closures.
Regarding the parameters part, as you see in the example above we call the closure (operation) with two parameters - the current element and current index. This means that the eachWithIndex method expects to receive not just any closure but one which would accept these two parameters. From a syntax prospective one defines the parameters during closure definition like this:
{ elem, index ->
// logic
}
So -> is used to separate arguments part of closure definition from its logic. When a closure takes only one argument, its parameter definition can be omitted and then the parameter will be accessible within the closure's scope with the name it (implicit name for the first argument). For example:
[1,2,3].each {
println it
}
It could be rewritten like this:
[1,2,3].each({ elem ->
println elem
})
As you see the Groovy language adds some syntax sugar to make such constructions look prettier.
each and eachWithIndex are, amongst many others, taking so called Closure as an argument. The closure is just a piece of Groovy code wrapped in {} braces. In the code with array:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" }
there is only one argument (closure, or more precisely: function), please note that in Groovy () braces are sometime optional. num and idx are just an optional aliases for closure (function) arguments, when we need just one argument, this is equivalent (it is implicit name of the first closure argument, very convenient):
def numbers = [ 5, 7, 9, 12 ]
numbers.each {println "$it" }
References:
http://groovy.codehaus.org/Closures
http://en.wikipedia.org/wiki/First-class_function
Normally, if you are using a functional programing language such as Groovy, you would want to avoid using each and eachWithIndex since they encourage you to modify state within the closure or do things that have side effects.
If possible, you may want to do your operations using other groovy collection methods such as .collect or .inject or findResult etc.
However, to use these for your problem, i.e print the list elements with their index, you will need to use the withIndex method on the original collection which will transform the collection to a collection of pairs of [element, index]
For example,
println(['a', 'b', 'c'].withIndex())
EachWithIndex can be used as follows:
package json
import groovy.json.*
import com.eviware.soapui.support.XmlHolder
def project = testRunner.testCase.testSuite.project
def testCase = testRunner.testCase;
def strArray = new String[200]
//Response for a step you want the json from
def response = context.expand('${Offers#Response#$[\'Data\']}').toString()
def json = new JsonSlurper().parseText(response)
//Value you want to compare with in your array
def offername = project.getPropertyValue("Offername")
log.info(offername)
Boolean flagpresent = false
Boolean flagnotpresent = false
strArray = json.Name
def id = 0;
//To find the offername in the array of offers displayed
strArray.eachWithIndex
{
name, index ->
if("${name}" != offername)
{
flagnotpresent= false;
}
else
{
id = "${index}";
flagpresent = true;
log.info("${index}.${name}")
log.info(id)
}
}

Resources