How to create method (function) in groovy with given params but not defined - groovy

I'm completly new to groovy, and to be honest I have real hard time with finding things in groovy. So i noticed that somethink like this can be achieve:
We have function
def static someMethod (params) {
...
}
and then you are able to call this one like this :
someMethod (param1 : value1, param2 : value2, param3 : value3....)
So my question is : how can I read those param1, param2 etc in my someMethod? I mean should I do something close to this ?
def static someMethod (params) {
def result = param1 + param2 + param3
}
And If someone let say dont give param3 will this function return nullPointerException?
Like I said I'm new, so any answer is probably best (some links meaby?)
Thanks in advance and sorry for my bad english.

When You declare such method:
def static someMethod (params) {
def result = params.param1 + params.param2 + params.param3
println result
}
and then invoke like this:
someMethod (param1 : 1, param2 : 2, param3 :3)
what You pass to method invocation is map, so in the method's body there's a need to prefix key names with map name in this case params.
When no value is present for key - null will be returned, unless You define a map using withDefault - then default value will be returned.

Related

How to pass multiple optional parameters and one mandatory parameter in groovy? [duplicate]

I would like to write a wrapper method for a webservice, the service accepts 2 mandatory and 3 optional parameters.
To have a shorter example, I would like to get the following code working
def myMethod(pParm1='1', pParm2='2') {
println "${pParm1}${pParm2}"
}
myMethod();
myMethod('a')
myMethod(pParm2:'a') // doesn't work as expected
myMethod('b','c')
The output is:
12
a2
[pParm2:a]2
a2
bc
What I would like to achieve is to give one parameter and get 1a as the result.
Is this possible (in the laziest way)?
Can't be done as it stands... The code
def myMethod(pParm1='1', pParm2='2'){
println "${pParm1}${pParm2}"
}
Basically makes groovy create the following methods:
Object myMethod( pParm1, pParm2 ) {
println "$pParm1$pParm2"
}
Object myMethod( pParm1 ) {
this.myMethod( pParm1, '2' )
}
Object myMethod() {
this.myMethod( '1', '2' )
}
One alternative would be to have an optional Map as the first param:
def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}
myMethod( 'a', 'b' ) // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd') // prints 'a b 1 2nd'
Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:
def someMethod(def args) {
println "MANDATORY1=${args.mandatory1}"
println "MANDATORY2=${args.mandatory2}"
println "OPTIONAL1=${args?.optional1}"
println "OPTIONAL2=${args?.optional2}"
}
someMethod mandatory1:1, mandatory2:2, optional1:3
with the output:
MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null
This looks nicer and the advantage of this is that you can change the order of the parameters as you like.
We can Deal with Optional parameters in 2 ways
Creating the method parameter with null values:
def generateReview(def id, def createDate=null) {
return new Review(id, createDate ?: new Date()) // ?: short hand of ternary operator
}
generateReview(id) // createDate is not passed
generateReview(id, createDate) // createDate is passed
Using Java Optional.of()
def generateReview(def id, Optional<Date> createDate) {
return new Review(id, createDate.isPresent() ? createDate.get() : new Date())
}
generateReview(id, Optional.empty()) // createDate is not passed
generateReview(id, Optional.of(createDate)) // createDate is passed

How can you do named parameters with a default value for closures

So basically I would like to do something like this:
execute = { String param1, String param2 = 'default' ->
echo "${param1}"
echo "${param2}"
}
execute(
param1: 'Test1',
param2: '123'
)
execute('Test2')
But that doesn't work, as it puts all the given parameters in param1. It would be possible with a map, but I would like to keep the functionality of default parameters.
Is there any way to do this?
Groovy has no named arguments. You can only allow a map and make it
look it would. So you have to allow for the map and deal with the
fall-back yourself. E.g. merge the incoming map with some default map
or pick the defaults where you need them. E.g.
def c = { Map args=[:] ->
def param1 = args.param1 ?: 'fallback'
println param1
}
c()
// ⇒ fallback
c(param1: "set")
// ⇒ set

Spock: check the query parameter count in URI

I have just started with spock. I have one functionality. where the java function makes an http call. As per functionality, the URI used in http call, must contain "loc" parameter and it should be only once.
I am writing Spock test case. I have written below snippet.
def "prepareURI" () {
given: "Search Object"
URI uri = new URI();
when:
uri = handler.prepareURI( properties) // it will return URI like http://example.com?query=abc&loc=US
then:
with(uri)
{
def map = uri.getQuery().split('&').inject([:]) {map, kv-> def (key, value) = kv.split('=').toList(); map[key] = value != null ? URLDecoder.decode(value) : null; map }
assert map.loc != null
}
}
From above snippet, my 2 tests got passed like
It should be exists
It should not be null
I want to check the count of "loc" query parameter. It should be passed exactly once. With map as above, If I pass "loc" parameter twice, map overrides the old value with 2nd one.
Does any one knows, how to access the query parameters as list, and in list I want to search the count of Strings which starts with "loc"
Thanks in advance.
Perhaps an example would be the best start:
def uri = new URI('http://example.com?query=abc&loc=US')
def parsed = uri.query.tokenize('&').collect { it.tokenize('=') }
println "parsed to list: $parsed"
println "count of 'loc' params: " + parsed.count { it.first() == 'loc' }
println "count of 'bob' params: " + parsed.count { it.first() == 'bob' }
println "count of params with value 'abc': " + parsed.count { it.last() == 'abc' }
prints:
$ groovy test.groovy
parsed to list: [[query, abc], [loc, US]]
count of 'loc' params: 1
count of 'bob' params: 0
count of params with value 'abc': 1
the problem, as you correctly noted, is that you can not put your params into a map if your intent is to count the number of params with a certain name.
In the above, we parse the params in to a list of lists where the inner lists are key, value pairs. This way we can call it.first() to get the param names and it.last() to get the param values. The groovy List.count { } method lets us count the occurences of a certain item in the list of params.
As for your code, there is no need to call new URI() at the beginning of your test as you set the value anyway a few lines down.
Also the with(uri) call is unnecessary as you don't use any of the uri methods without prefixing them with uri. anyway. I.e. you can either write:
def uri = new URI('http://example.com?query=abc&loc=US')
def parsed = uri.query.tokenize('&').collect { it.tokenize('=') }
or:
def uri = new URI('http://example.com?query=abc&loc=US')
uri.with {
def parsed = query.tokenize('&').collect { it.tokenize('=') }
}
(note that we are using query directly in the second example)
but there is not much point in using with if you are still prefixing with uri..
The resulting test case might look something like:
def "prepareURI"() {
given: "Search Object"
def uri = handler.prepareURI( properties) // it will return URI like http://example.com?query=abc&loc=US
when:
def parsed = query.tokenize('&').collect { it.tokenize('=') }
then:
assert parsed.count { it.first() == 'loc' } == 1
}

Twig custom function with parameters

I read twig documentation, but I am little confused about custom functions and filters. I understand how to add custom functions. But I don't understand how to write a function that accepts some parameters, may be also some optional parameters.
For example, I have following pseudo code for function named sqare.
$twig = new Twig_Environment($loader);
$function = new Twig_SimpleFunction('square', function () {
if param2 present?
return param1*param2;
else
return param1;
});
$twig->addFunction($function);
Now what I want is that, param1 should have a default value 1 and param2 should be optional. The square function will return the product of the two parameters. I also want that if user do not pass the second parameter then param1 will be returned, that is the first parameter will be returned. How can I implement this? Also, should I call the function in the twig template as {{ square(5, 10) }}?
You need to define the parameters in your closure.
Twig will pass the parameters accordingly
$function = new Twig_SimpleFunction('square', function ($param1, $param2 = null) {
return isset($param2) ? $param1 * $param2 : $param1;
});
Then you call this function in Twig with :
Only one param : {{ square(5) }}
Two params : {{ square(5, 2) }}

How to pass variable parameters to an XPages SSJS function?

If I have a function in SSJS and I want to pass one "firm" parameter and a list of others that can change, what's the best way to do that? With some kind of hashMap or JSON or something else?
for example given something like:
myfunction( code:string, paramList:??) {
// do stuff here
}
Basically the function will create a document. And sometimes I'll have certain fields I'll want to pass in right away and populate and other times I'll have different fields I will want to populate.
How would you pass them in and then parse out in the function?
Thanks!
Use the arguments parameter... In JavaScript you are not required to define any of your parameters in the function block itself. So, for example, the following call:
myFunction(arg1, arg2, arg3, arg4);
can legally be passed to the following function:
myFunction () {
// do stuff here...
}
when I do this, I usually place a comment in the parens to indicate I am expecting variable arguments:
myFunction (/* I am expecting variable arguments to be passed here */) {
// do stuff here...
}
Then, you can access those arguments like this:
myFunction (/* I am expecting variable arguments to be passed here */) {
if (arguments.length == 0) {
// naughty naughty, you were supposed to send me things...
return null;
}
myExpectedFirstArgument = arguments[0];
// maybe do something here with myExpectedFirstArgument
var whatEvah:String = myExpectedFirstArgument + ": "
for (i=1;i<arguments.length;i++) {
// now do something with the rest of the arguments, one
// at a time using arguments[i]
whatEvah = whatEvah + " and " + arguments[i];
}
// peace.
return whatEvah;
}
Wallah, variable arguments.
But, more to the point of your question, I don't think you need to actually send variable arguments, nor go through the hassle of creating actual JSON (which is really a string interpretation of a javascript object), just create and send the actual object then reference as an associative array to get your field names and field values:
var x = {};
x.fieldName1 = value1;
x.fieldName2 = value2;
// ... etc ...
then in your function, which now needs only two parameters:
myFunction(arg1, arg2) {
// do whatever with arg1
for (name in arg2) {
// name is now "fieldName1" or "fieldName2"
alert(name + ": " + x[name]);
}
}
Hope this helps.
I would do this with a JSON object as the second parameter...
function myfunction(code:String, data) {
// do stuff here...
var doc:NotesDocument = database.CreateDocument();
if(data) {
for (x in data) {
doc.replaceItemValue(x, data[x]);
}
}
// do more stuff
doc.save(true, false);
}
Then you call the function like this:
nyfunction("somecode", {form:"SomeForm", subject:"Whatever",uname:#UserName()});
Happy coding.
/Newbs
I don't think that is possible in SSJS. I think the best option you have is to pass a hashmap or your own (java) object. I think a custom java object would be the nicest option because you can define some 'structure' on how your function can process it. A hashmap can be easily extended but it is not easy if you have a lot of code that create a lot of different hashmap structures...

Resources