Groovy script is not working in Jenkins Active choice parameter - groovy

I am working a groovy script which is working perfectly on the Jenkins Scriptler but when I tried to run the same script from active choice parameter, it is not returning any values.
Could someone help me on this?
import java.time.format.DateTimeFormatter
exception_file = "test/10-01-2023/test"
String ex_date = exception_file.split('/')[1].toString()
println ex_date
cDate = java.time.LocalDate.now()
currentDate = cDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
expiry_date = Date.parse("dd-MM-yyyy", ex_date)
return expiry_date
But in parameters it is empty. AM i missing something?

I've reproduced the problem using your code. The only thing you are missing is the correct return type. It must be either java.util.List, Array, or java.util.Map.
In the following I'm returning an array.
import java.time.format.DateTimeFormatter
exception_file = "test/10-01-2023/test"
String ex_date = exception_file.split('/')[1].toString()
println ex_date
cDate = java.time.LocalDate.now()
currentDate = cDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
expiry_date = Date.parse("dd-MM-yyyy", ex_date)
return [ expiry_date ]
This renders like:

Related

Need to remove unwanted symbols from value using replaceAll method

I am getting the value of a field as ["value"]
I want to print only the value removing the [ "from the result value.
That looks like a JSON array of Strings? No idea, as you don't provide any context, but you could do:
import groovy.json.JsonSlurper
def valueField = '["value"]'
def result = new JsonSlurper().parseText(valueField).head()
println result
Prints value
The following script should be what you need
def str = '["value"]'
println(str.replaceAll(/\[|\]/,''))

how to pass complex string to pymongo for query by python?

I need to filter the webserver requests and setting a query for pymongo, its not so simple as I need to have "and", or "or" functionality for multiple fields.
I have filtered the get request, got the parameters, built the string to be passed to db..find. But it throws error. I have identified the error as because I am forming a string like this to passed to the function, now as its a string and not actually a dict, its throwing an error. What is the right way of doing it?
Actually, I have to get something like: {$and:[{Title:{"$regex":"Hong Kong"}},{Url:{"$regex":"hong"}}]}{'_id':0, 'Body':0}
The get request I am sending is: http://127.0.0.1:5000/getRequest?Title="Hong Kong protest"&Url="hong" Now the below thing gives the exact required string, but it throws an error as its not supposed to be string. Please help.
#app.route('/getRequest', methods=['GET'])
def request():
global connection
args = request.args
if len(args) > 1:
search_str = ""
for key, val in args.items():
search_str += '{'+key+':{"$regex":'+str(val)+'}},'
search_str = search_str[:-1]
display_dict={'id':0, 'Body':0}
final_search_str = "{$and:["+search_str+"]},{'_id':0, 'Body':0}"
#return(final_search_str)
# query_str = request.args.get('query_string')
db = connection['test']
collection = db['collect1']
output = []
for s in collection.find(final_search_str):
output.append({'Title' : s['Title'], 'Url' : s['Url']})
It should be dict which should be passed to the function. Any better way to do this complex query via pymongo?
You can do this using re and bson.regex.Regex module.
http://api.mongodb.com/python/current/api/bson/regex.html
import re
from bson.regex import Regex
query = {}
for key, val in args.items():
pattern = re.compile(val)
regex = Regex.from_native(regex)
query[key] = regex
for s in collection.find(query):
output.append({'Title' : s['Title'], 'Url' : s['Url']})

Groovy string interpolation when string is defined before the interpolated variables are defined

I have a similar question to this:
Groovy string interpolation with value only known at runtime
What can be done to make the following work:
def message = 'Today is ${date}, your id is: ${id}';
def date1 = '03/29/2019'
def id1 = '12345'
def result = {date, id -> "${message}"}
println(result(date1, id1))
So I want to take a string that has already been defined elsewhere (for simplicity I define it here as 'message'), having the interpolated ${date} and ${id} already embedded in it, and process it here using the closure, with definitions for the input fields.
I've tried this with various changes, defining message in the closure without the "${}", using single or double quotes, embedding double quotes around the interpolated vars in the string 'message', etc., I always get this result:
Today is ${date}, your id is: ${id}
But I want it to say:
Today is 03/29/2019, your id is: 12345
The following worked but I am not sure if it is the best way:
def message = '"Today is ${date}, your id is: ${id}"'
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
sharedData.setProperty('date', '03/29/2019')
sharedData.setProperty('id', '12345')
println(shell.evaluate(message))
http://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html
ernest_k is right, you can use the templating engine for exactly this:
import groovy.text.SimpleTemplateEngine
def templatedMessage = new SimpleTemplateEngine().createTemplate('Today is ${date}, your id is: ${id}')
def date1 = '03/29/2019'
def id1 = '12345'
def result = { date, id -> templatedMessage.make(date: date, id: id)}
println(result(date1, id1))

groovy extract value from string

I got a string from a server response:
responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"
then I do:
responseString[1..-2].tokenize(',')
got:
[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]
get(3) got:
""userid":"user_1""
what I need is the user_1, is there anyway I can actually get it? I have been stuck here, other json methods get similar result, how to remove the outside ""?
Thanks.
If you pull out the proper JSON from responseStr, then you can use JsonSlurper, as shown below:
def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'
def matcher = (s =~ /responseString:"(.*)"/)
assert matcher.matches()
def responseStr = matcher[0][1]
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(responseStr)
assert "user_1" == json.userid
This code can help you get you to the userid.
def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
def match = (str=~ /"userid":"(.*?)"/)
log.info match[0][1]
this pattern can help you getting any of the values you want from the string. Try replacing userid with age, you will get that
def match = (str=~ /"age":"(.*?)"/)
#Michael code is also correct. Its just that you have clarified that you want the user Name to be specific

Is there a way to declare a Groovy string format in a variable?

I currently have a fixed format for an asset management code, which uses the Groovy string format using the dollar sign:
def code = "ITN${departmentNumber}${randomString}"
Which will generate a code that looks like:
ITN120AHKXNMUHKL
However, I have a new requirement that the code format must be customizable. I'd like to expose this functionality by allowing the user to set a custom format string such as:
OCP${departmentNumber}XI${randomString}
PAN-${randomString}
Which will output:
OCP125XIBQHNKLAPICH
PAN-XJKLBPPJKLXHNJ
Which Groovy will then interpret and replace with the appropriate variable value. Is this possible, or do I have to manually parse the placeholders and manually do the string.replace?
I believe that GString lazy evaluation fits the bill:
deptNum = "C001"
randomStr = "wot"
def code = "ITN${deptNum}${->randomStr}"
assert code == "ITNC001wot"
randomStr = "qwop"
assert code == "ITNC001qwop"
I think the original poster wants to use a variable as the format string. The answer to this is that string interpolation only works if the format is a string literal. It seems it has to be translated to more low level String.format code at compile time. I ended up using sprintf
baseUrl is a String containing http://example.com/foo/%s/%s loaded from property file
def operation = "tickle"
def target = "dog"
def url = sprintf(baseUrl, operation, target)
url
===> http://example.com/foo/tickle/dog
I believe in this case you do not need to use lazy evaluation of GString, the normal String.format() of java would do the trick:
def format = 'ITN%sX%s'
def code = { def departmentNumber, def randomString -> String.format(format, departmentNumber, randomString) }
assert code('120AHK', 'NMUHKL') == 'ITN120AHKXNMUHKL'
format = 'OCP%sXI%s'
assert code('120AHK', 'NMUHKL') == 'OCP120AHKXINMUHKL'
Hope this helps.
for Triple double quoted string
def password = "30+"
def authRequestBody = """
<dto:authTokenRequestDto xmlns:dto="dto.client.auth.soft.com">
<login>support#soft.com</login>
<password>${password}</password>
</dto:authTokenRequestDto>
"""

Resources