Velocity check if Map has a key with null value - velocity

I'm creating a velocity template to which I pass a map, and I want to get only the keys with values.
It is my code:
#set ($value = $map.get($key))
#if($value != "")
"$key": "$value",
#end
map.get(parameter) != null
map.get(parameter) != ''
It prints: $value

Just try:
#if($value)
"$key": "$value",
#end
It will filter out null and empty values.

Related

way to Check null objects in json api array

I'm trying a lot of things but i still can not figure out a way to Check if an object is null.
This is the Api response
Api response
The problem sometimes the object shortname Doesn't exist in the teamInfo
so there will be just "name" and "img" . i want to show some other text if shortname Doesn't exist in teaminfo.
I've tried something like:
Text(
text = if(data.teamInfo[1].shortname != null){data.teamInfo[1].shortname}
else{data.teams[1]},
modifier = Modifier
.weight(1f)
.padding(5.dp)
.align(Alignment.CenterVertically),
fontWeight = FontWeight.Bold,
maxLines = 1
)
Firstly, I see you are hardcoding the array index always to be 1. Is that right for your case?
The relevant part is this
text = if (data.teamInfo[1].shortname != null) {
data.teamInfo[1].shortname
} else {
data.teams[1]
},
Your null check is valid, the fragment of the JSON response you gave doesn't seem to have a teams array so the second part may not work/compile/produce a non-null. You do say each teaminfo will have a name so try this first
text = if (data.teamInfo[1].shortname != null) {
data.teamInfo[1].shortname
} else {
data.teamInfo[1].name
},
And you can simply this with the "Elvis" operator
text = data.teamInfo[1].shortname ?: data.teamInfo[1].name

How to assign a new list to a nullable field if null or else just add an element to the existing list in Kotlin?

I have an object media that holds descriptions which is a list. I'd love to see some elegant logic in Kotlin to add an element to that descriptions if the field is not null or add a fresh new list (with an initial element) to that field if it is null.
Pseudo:
if (media.descriptions == null) { media.descriptions = listOf("myValue")}
else { media.descriptions.add("myValue") }
I would probably do it the other way around, except you need to alter media itself (see below), i.e. creating your list first and add all the other entries to that list if media.descriptions isn't null:
val myDescriptions = mutableListOf("myValue") // and maybe others
media.descriptions?.forEach(myDescriptions::add)
If you need to manipulate descriptions of media, there is not so much you can do to make it more readable...:
if (media.descriptions == null) {
media.descriptions = mutableListOf("myValue") // just using mutable to make it clear
} else {
media.descriptions += "myValue"
}
or maybe:
if (media.descriptions == null) {
media.descriptions = mutableListOf<String>()
}
media.descriptions?.add("myValue")
You can use the elvis ?: operator to assign the list.
The simplest way I can think of is
media.descriptions = media.descriptions ?: listOf("myValue")
media.descriptions.add("myValue")

Check if a list contains at least one variable non null

I'm making my first app in Kotlin and there is a lot of syntax I don't know, and I was wondering if there is a better way to check if a list contains at least one non null entry.
For now my solution is:
var atLeastOneValue: Boolean
var i = 0
for (x in list) {
if (x != null) atLeastOneValue = true
else i++
}
if (list.size == i) atLeastOneValue = false
return atLeastOneValue
I'm working with MutableList<String>.
You can use contains function for that:
val hasNull = list.contains(null)
contains can also be called in the operator form, it corresponds to the operator in:
val hasNull = null in list
val hasNoNull = null !in list

Can't invoke remove() method on a list of Strings in groovy

I am trying to remove a String at a certain index in my list of Strings however I can't seem to invoke the list.remove() method in groovy.
public List getCassetteTypes(socket, numOfSlots){
//get the cassettes layout
sendCommand(socket, 'syst:layout? ')
String systLayoutStr = readCommand(socket)
//this String looks like: '1 ABC, 2 DEF, 3 SPN, ....'
List listOfCassetteTypes = new ArrayList<String>()
//I split the String at ',' because for each cassetteName, I want to remove the number before it
listOfCassetteTypes = systLayoutStr.split(',')
for(int i = 0; i < numOfSlots; i++){
//remove any white spaces
listOfCassetteTypes[i] = listOfCassetteTypes[i].trim()
//remove the numerical value
listOfCassetteTypes[i] = listOfCassetteTypes[i].replace((i + 1) + ' ', '')
/* if the cassette name is 'SPN',
I want to remove it and append '-EXT' to the cassetteName before it,
because 'SPN' means the previous slot is extended,
'SPN' itself isn't a cassette */
if(listOfCassetteTypes[i].equalsIgnoreCase('spn')){
listOfCassetteTypes[i - 1] = listOfCassetteTypes[i - 1].concat('-EXT')
//this is what is not working for me, everything else is fine.
listOfCassetteTypes = listOfCassetteTypes.remove(i)
}
}
return listOfCassetteTypes
}
I've tried several different ways but none of them seem to work.
Instead of manipulating the list, you could process each entry in a pair with it's successor... I believe this does what you're after?
def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'
def splitted = layoutStr.split(',')
*.trim() // remove white space from all the entries (note *)
*.dropWhile { it ==~ /[0-9 ]/ } // drop until you hit a char that isn't a number or space
.collate(2, 1, true) // group them with the next element in the list
.findAll { it[0] != 'SPN' } // if a group starts with SPN, drop it
.collect {
// If the successor is SPN add -EXT, otherwise, just return the element
it[1] == 'SPN' ? "${it[0]}-EXT" : it[0]
}
assert splitted == ['ABC', 'DEF-EXT', 'GHI']
Followup question
To just get the numbers of the ones not SPN:
def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'
def splitted = layoutStr.split(',')
*.trim() // remove white space from all the entries (note *)
*.split(/\s+/) // Split all the entries on whitespace
.findResults { it[1] == 'SPN' ? null : it[0] } // Only keep those that don't have SPN
Note that this is a list of Strings, not Integers... If you need integers then:
.findResults { it[1] == 'SPN' ? null : it[0] as Integer }

how to put in a param even if the value of param is null

so my code is as follows:
* def value = newMP.response.data[randomizer].phoneNumber
* def nullvalue = 'null'
* def filter = (value == '#null' ? nullvalue : value)
* print filter
And param filter[phoneNumber] = filter
The result of this code is
Thing is that my application allows a search for null as well. therefore im looking if its possible to put in a filter that is null based on the conditional logic
Additionally if i go like this
And param filter[phoneNumber] = 'null'
the null value is in the GET call
Yes by default Karate ignores null-valued params and this is what most users expect.
You have not been clear as to what you are expecting but I'm guessing you need a param with an empty value.
Try this:
And param filter = ''
Also read this example for more ideas: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/search/dynamic-params.feature
What i required was to put in the value of the parameter as either null or "null", and the validate in response that the value is null, not the string form of it. below is the workaround for it.
And def value = newMP.response.data[randomizer].phoneNumber
And eval if (value == null) karate.set('value', 'null')
And param filter[phoneNumber] = value
When method GET
Then status 200
* eval if (value == 'null') karate.set('value', null)
Then match response.data[0].attributes.phoneNumber contains value