Select All Choices in Jenkins Groovy - jenkins

I want to select all the choices in my Groovy script so it defaults to all. I am using the Active Choices Reactive Parameter because I am reading in the previous option. How do I make my "output" variable so it is all selected without having the user select them all?
def output = []
def line
def release = RELEASE_NUMBER
releaseNumber = release.replaceAll("\\n", "");
String[] number = releaseNumber.split("\\.");
def list = "cmd /c e:\\tools\\wget --no-check-certificate --http-user=username--http-password=password-qO- \"https://1.1.1.1:443/svn/Instructions/trunk/${number[0]}.${number[1]}.${number[2]}/ICAN/EI_${releaseNumber}.txt\"".execute().text
list.eachLine {
if (it.contains("- LH")) {
String newName = it.replaceAll("\\s", "");
String newName2 = newName.replaceAll("-", "");
output.add(newName2)
}
}
return output

I don't know anything about Jenkins, but reading the documentation for the plugin you mention you should be able to simply use output.add("${newName2}:selected").

Related

How to fetch jenkins log between two timestamp using groovy?

My jenkins log is too big and often consoleFull did not load it completely.
So using groovy script fetching logs between timestamp like below.
JOBNAME = 'My_Jenkins_job'
BUILDID = '34'
def start = 23
def end = 25
def time_prefix = '2021-11-30T08:'
for (job in Jenkins.instance.getAllItems(Job.class)) {
if (job.name == JOBNAME) {
for (build in job.builds) {
if (build.id == BUILDID) {
def lines = build.logFile.readLines()
println '===================================================='
println "Log summary between ${time_prefix}${start}..${end}"
println '======================================================='
for (int i in start..end) {
def logmsg = lines.findAll {
it.contains("${time_prefix}${i}")
}
logmsg.each {
println it
}
}
}
}
}
}
But here I am using string and contains to parse the timings ,But if I can use datetime in range it will be good. How to convert the date time format in Jenkins to groovy and put it in a range.
I am trying to convert time and it fails.
String log_time="2021-12-01T09:19:54-07:00"
String timestamp = Date.parse("yyyy-MM-dd'T'HH:mm-ss':00'", log_time)
println(timestamp)
If I can convert the jenkins timestamp and put it in range operator I can extract the log between timestamp. How to do it?
This is working for me:
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
def log_time='2021-12-01T09:19:54-07:00'
def timestamp = LocalDateTime.parse(log_time, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz"))
println timestamp

Jenkins groovy - how to separate url path and filename

$url = "http://bus00cyb.ind.testserver.com:8080/job/IOTF-7.4.x-BITBUCKET-REPO/51/artifact/output.txt"
I have a Jenkins job parameter which has takes 'url' value as an user input. I want to separate the param as below:
$url_path = "http://bus00cyb.ind.testserver.com:8080/job/IOTF-7.4.x-BITBUCKET-REPO/51/artifact"
$filename = "output.txt"
How to do this using jenkins pipeline groovy script? Pls suggest.
Don't know if I'm understanding your question correctly but in groovy you will have something like this:
url = "http://bus00cyb.ind.testserver.com:8080/job/IOTF-7.4.x-BITBUCKET-REPO/51/artifact/output.txt"
urlsplitted = url.split('/')
filename = urlsplitted[urlsplitted.length-1]
shorturl = url-filename
println(shorturl)
println(filename)
U can use regexp (.*)\/(\w*\..*)$
Pattern p = Pattern.compile("(.*)\/(\w*\..*)$");
Matcher m = p.matcher("http://bus00cyb.ind.testserver.com:8080/job/IOTF-7.4.x-BITBUCKET-REPO/51/artifact/output.txt");
If (m.find()){
filename= m.group(2)
url=m.group(1)
}

How to fix java.io.NotSerializable exception when pushing each stage data from jenkins pipeline to influx db?

I’m trying to push stage data from Jenkins pipeline to influx db and I get issue as below
Issue: In jenkin builds console output, after each stage, I see : java.io.NotSerializableException: sun.net.www.protocol.http.HttpURLConnection
Jenkins pipeline 2.150.2
InfluxDB 1.6.2
Any suggestions would be helpful. I'm new to this topic.
Note: I have commented #NonCPS annotation. If I uncomment then it sends only first stage data and exits and fails to iterate for loop which has 20 stages data.
//Maps for Field type columns
myDataField1 = [:]
myDataField2 = [:]
myDataField3 = [:]
//Maps for Custom Field measurements
myCustomDataFields1 = [:]
myCustomDataFields2 = [:]
myCustomDataFields3 = [:]
//Maps for Tag type columns
myDataTag1 = [:]
myDataTag2 = [:]
myDataTag3 = [:]
//Maps for Custom Tag measurements
myCustomDataTags1 = [:]
myCustomDataTags2 = [:]
myCustomDataTags3 = [:]
//#NonCPS
def pushStageData() {
def url_string = "${JENKINS_URL}job/ENO_ENG_TP/job/R421/13/wfapi/describe"
def get = new URL(url_string).openConnection();
get.addRequestProperty ("User-Agent","Mozilla/4.0");
get.addRequestProperty("Authorization", "Basic dZXZvceDIwMTk=");
//fetching the contents of the endpoint URL
def jsonText = get.getInputStream().getText();
//converting the text into JSON object using
JsonSlurperClassic
def jsonObject = new JsonSlurperClassic().parseText(jsonText)
// Extracting the details of all the stages present in that particular build number
for (int i=0; i<jsonObject.stages.size()-1; i++){ //size-1 to ignore the post stage
//populating the field type columns of InfluxDB measurements and pushing them to the map called myDataField1
def size = jsonObject.stages.size()-1
myDataField1['result'] = jsonObject.stages[i].status
myDataField1['duration'] =
jsonObject.stages[i].durationMillis
myDataField1['stage_name'] = jsonObject.stages[i].name
//populating the tag type columns of InfluxDB
measurements and pushing them to the map called
myDataTag1
myDataTag1['result_tag'] = jsonObject.stages[i].status
myDataTag1['stage_name_tag'] = jsonObject.stages[i].name
//assigning field type columns to the measurement called CustomData
myCustomDataFields1['CustomData'] = myDataField1
//assigning tag type columns to the measurement called CustomData
myCustomDataTags1['CustomData'] = myDataTag1
//Push the data into influx instance
try
{ step([$class: 'InfluxDbPublisher', target: 'jenkins_data', customPrefix: null, customDataMapTags: myCustomDataTags1]) }
catch (err)
{ println ("pushStagData exception: " + err) }
}
}
Expected: I want to push each stages of jenkins pipeline data to influx db.
Try to use jenkins' standard methods instead of creating objects manually. You can use httpRequest instead of URL. This should fix exception you are getting. You can also use readJson instead of JsonSlurperClassic (latter is optional since classic slurper is actually serializable).
you just need to explicitly set get to null to make sure there's none non serializable object being instantiated.
def jsonText = get.getInputStream().getText();
get = null;

Groovy script from Jenkins Job to populate data as combo box from oracle DB is taking lot of time

I am using Groovy script to pull the data from oracle DB from Jenkins Job/Combo Box. It is taking lot of time to pull the data.
How to improve the performance?
import groovy.sql.Sql
Properties properties = new Properties()
File propertiesFile = new File('/opt/groovy/db.properties')
propertiesFile.withInputStream {
properties.load(it)
}
def Param = []
def arg = []
args.each{ arg.push(it)}
def dbUrl = 'jdbc:oracle:thin:#' + properties.dbServer + ':52000/' +
properties.dbSchema
sql = Sql.newInstance( dbUrl, properties.dbUser, properties.dbPassword,
properties.dbDriver )
switch (arg[0]) {
case { it == 'APP' }:
Param.push('Select')
query = "SELECT DISTINCT APP FROM INV ORDER BY APP"
sql.eachRow(query) { row ->
Param.push(row[0])
}
def App_array_final = Param.collect{ '"' + it + '"'}
print App_array_final
break;

WLST Ant Task white space within arguments

I am using the WLST Ant task which allows a list of space delimited arguments to be passed in under the arguments attribute.
The issue is when I pass a file directory which contains a space. For instance "Program Files" which becomes two arguments of Program and Files.
Is there any suggestions to get around this?
My suggestion below would only work with one value.
For example append the "Program Files" argument to the end and loop from the known end argument to the actual end of sys.argv.
IE If we want "Program Files" to be the 4th system argument then inside the WLST script we append sys.argv[4],[5]...[end].
Short answer for WLST 11.1.1.9.0: You can't get around this.
I have the same problem and debugged a bit.
My findings:
The class WLSTTask in weblogic-11.1.1.9.jar calls via command line WLSTInterpreterInvoker which parses the args:
private void parseArgs(String[] arg) {
for (int i = 0; i < arg.length; i++) {
this.arguments = (this.arguments + " " + arg[i]);
}
[...]
For reasons I don't know these args are parsed again, before the python script is invoked:
private void executePyScript() {
[...]
if (this.arguments != null) {
String[] args = StringUtils.splitCompletely(this.arguments, " ");
[...]
public static String[] splitCompletely(String paramString1, String paramString2)
{
return splitCompletely(new StringTokenizer(paramString1, paramString2));
}
private static String[] splitCompletely(StringTokenizer paramStringTokenizer) {
int i = paramStringTokenizer.countTokens();
String[] arrayOfString = new String[i];
for (int j = 0; j < i; j++) arrayOfString[j] = paramStringTokenizer.nextToken();
return arrayOfString;
}
Unfortunately the StringTokenizer method does not distinguish quoted strings and so sys.argv in Python gets separate arguments, even if you quote the parameter
There are two possible alternatives:
Replace spaces in Ant with something else (eg %20) and 'decode' them in Python.
Write a property file in Ant and read from that in Pyhton.
The code for executePyScript() in 12.2.1 has changed a lot and it seems that the problem may be gone there (I haven't checked)
if ((this.arguments.indexOf("\"") == -1) && (this.arguments.indexOf("'") == -1))
args = StringUtils.splitCompletely(this.arguments, " ");
else {
args = splitQuotedString(this.arguments);
}

Resources