Unable to split the list of files - jenkins

I am having list of files in a directory.
For Ex:
sample1.properties
sample2.properties
sample3.properties
I am trying to use the groovy code to push these values in the Jenkins Active Choices parameter. How can I populate this list without ".properties" at the end. My list of Active choices parameters needs to be like this:
sample1
sample2
sample3
Code I am using is:
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
def results = new JsonSlurper().parseText(reader.getText());
reader.close()
data= results.tree.path
data.each {
it -> if(it.endsWith(".properties"))
choices.push(it.replace("/","") )
}
choices=choices.sort()
choices.add(0,"SELECT")
return choices

Simply replacing the .properties part will not work?
choices.push(it.replace("/","").replace(".properties", ""))

If my assumption regarding your results.tree.path content is correct, then you should probably use something like that:
def data = [
'some/complex/path/sample1.properties',
'some/complex/path/some_irrelevant_file.txt',
'some/complex/path/sample2.properties',
'some/complex/path/sample3.properties'
]
data.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { println it }
so, in your case, you need to do:
results.tree.path.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { choices.push(it) }

Related

How to list a windows share folder by active choices parameter or extened choice parameter in jenkins

I tryed to write a groovy script with extened choice parameter:
import jcifs.smb.*
try {
def source = "smb://192.168.1.xx/build/"
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("mydc", "jenkins", "*****");
def dir = new SmbFile(source, auth)
// def dir = new SmbFile(source)
def files = dir.listFiles()
return ["xx"]
def list = []
for (SmbFile f : files)
{
list << f.getName()
}
list << "xx"
return list
} catch (Exception e1) {
return [e1.getMessage()]
}
but then I get the exception:
Failed to connect: 0.0.0.0<00>/192.168.1.xx .
I have open the server's smb1 support.
How can I list the smb folder or file with jenkins parameter choice?
I find the solution my self:
import groovy.io.FileType
try {
def source = "\\\\192.168.xx.xx\\xx\\xx"
def dir = new File(source)
def list = []
dir.eachFile(FileType.DIRECTORIES) {
list << it.name
}
return list
} catch (Exception e1) {
return [e1.getMessage()]
}
maybe I have saw the answer some place, but my java is so poor, I didn't understand. I tried many times to get the solution.

Want to Delete and Insert in same Action

I have one action in my controller that upload csv file with list of numbers.
Now the process is first I need to delete existing data from the table on certain condition then insert fresh data.
My snippet code is as follows..
Controller:
#Transactional
def uploadFile() {
if(!params?.updateExisting){
println "Going to call service to delete records"
myService.deleteNumbers()
def newList = Number.findAllByDeleted(false)
println "NEW LS:"+newList
//HERE I'm GETTING BLANK
}
def file = request.getFile("fileCsv")
file.inputStream
.splitEachLine(',') { fields ->
Number.withNewTransaction {
def number = fields[0]?.toString().replaceAll(" ","").replaceAll("-","")
Number numberInstance = new Number()
def numberExist = Number.findAllByNumberAndDeleted(number, false)
//HERE NUMBER IS STILL EXIST
if(!numberExist){
numberInstance.number = number
numberInstance.save(flush:true)
count++
}else{
println "Number exist: "+number
}
}
}
redirect(uri:'/number/list')
}
myService:
#Transactional
def deleteNumbers(){
Number.findAll().each {
it.deleted = true
it.save(flush: true)
}
}
After calling service method deleteNumbers I'm getting blank list NEW LS:[], But then def numberExist = Number.findAllByNumberAndDeleted(number, false) returns me a number means already exist.
Thanks..
Try removing Number.withNewTransaction closure. Your code should work..

extract parameters from a jenkins previous build

I am working on Jenkins version 2.32.1 pipeline. I want to extract the parameters that were chosen in the previous build of my job.
In our previous Jenkins instance ( 1.627 ) we were using jenkins.model.Jenkins.instance.getItem(job).lastBuild.getBuildVariables().get(param);
For some reason this is not working in this version (I also tried disabling the sandbox).
Any pointers on how to accomplish it?
Simplified version of the previous script:
def build = Jenkins.get().getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).find {it.displayName == 'YOUR_JOB_NAME_HERE'}?.getLastBuild()
build.actions.find{ it instanceof ParametersAction }?.parameters.each {echo "${it.name}=${it.value}"}
Actually a little bit shorter version for those who want to get the params for the current build from the previous run and is working on new 2+ Jenkins versions.
To get 1 particular parameter:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters.find{it.name == 'cls'}?.value
Get all params respectfully:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters
Something like this might work, based on https://stackoverflow.com/a/19564602/3920342:
def h = hudson.model.Hudson.instance
def r = null
h.getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).each {project ->
if (project.displayName.equals('YOUR_JOB_NAME')) {
r = project
}
}
r.getBuilds().findAll { b -> // here we loop over all past builds, apply some filter if necessary
def p = b?.actions.find{ it instanceof ParametersAction }?.parameters
p.each {
echo "parameter ${it.name}: ${it.value}"
}
}
For those who are not able to access getActions() due to admin permissions i.e. facing the following error:
Scripts not permitted to use method hudson.model.Actionable getActions
They can copy the parameter variables to the env and get them using build.previousBuild.buildVariables
stage('Prepare environment') {
steps {
script {
env.MY_PARAM_COPY = "${MY_PARAM}"
}
}
}
println("MY_PARAM in previous build: ${currentBuild.previousBuild.buildVariables["MY_PARAM_COPY"]}")
That's how I made it works, answer from #dan.goriaynov and #jherb caused some CPS closure issues for me.
(the gist of the code is to allow only greater TAG number than the previous one to be deployed)
stage('Validate build number') {
def previous_build = currentBuild.getPreviousBuild().getRawBuild();
def PREVIOUS_TAG = '';
for (int i = 0; i < previous_build.allActions.size(); i++) {
if (previous_build.allActions[i] in hudson.model.ParametersAction) {
PREVIOUS_TAG = previous_build.allActions[i].getParameter("TAG").value
}
}
if (PREVIOUS_TAG.toInteger() > TAG.toInteger()) {
echo PREVIOUS_TAG
error('TAG number needs to be greater than the previous one')
}
}

How to modify an URL in a view in CakePHP 2.x

It seems quite simple but there is something I am not able to figure out. I hope someone can help me fast.
I have an url, something like http://host/controller/action/argument/named:1/?query1=1. I want to add another query param to look it like http://host/controller/action/argument1/argument2/named:1/?query1=1&query2=2. I fact I want to add query2=2 to all URLs on a particular page, through some callback or something.
An URL may or may not have query params in the existing page URL.
How do I do it?
Example url : http://www.example.com/myController/myAction/param1:val1/param2:val2
You can use :
$this->redirect(array("controller" => "myController",
"action" => "myAction",
"param1" => "val1",
"param2" => "val2",
$data_can_be_passed_here),
$status,
$exit);
Hope it helps you.
May be I am thinking too much of it but here is how it came out. I put it in a UtilityHelper.
function urlmodify($params = array(), $baseurl = true) {
$top_level_1 = array('plugin', 'controller', 'action'); //top level vars
$top_level_2 = array('pass', 'named'); //top level vars
//for integrated use
$top_level = array_merge($top_level_1, $top_level_2);
$urlparams = array();
//get top level vars
foreach($top_level as $k) {
if(in_array($k, $top_level_1)) {
$urlparams[$k] = $this->request->params[$k];
}
if(in_array($k, $top_level_2)) {
$$k = $this->request->params[$k]; //create $pass & $named
}
}
//get query vars
if($this->request->query) {
$urlparams['?'] = $this->request->query;
}
//check for custom pass vars
if(isset($params['pass'])) {
$pass = array_merge($pass, $params['pass']);
}
//pass var has to be in numarical index
foreach($pass as $v) {
array_push($urlparams, $v);
}
//check for custom named vars
if(isset($params['named'])) {
$named = array_merge($named, $params['named']);
}
//pass var has to be in key=>value pair
foreach($named as $k=>$v) {
$urlparams[$k] = $v;
}
//check for custom query vars
if(isset($params['?'])) {
$urlparams['?'] = array_merge($urlparams['?'], $params['?']);
}
return Router::url($urlparams, $baseurl);
}
}
I have an URL: http://localhost/project/exlplugin/logs/manage_columns/1/a:1/n:1/?b=1. On some links I want to add some certain parameters. Here is the result when i call
echo $this->Utility->urlmodify(array('pass'=>array(2), 'named'=>array('m'=>2), '?'=>array('c'=>2)));*
It gives: http://localhost/thecontrolist/spreadsheet/logs/manage_columns/1/2/a:1/n:1/m:2?b=1&c=2
I just wanted to add just a query parameter to all my listing urls deleted=0 or deleted=1 for the SoftDelete thing :)
Thank you #u2460470 for the answer but it's just about modifying (not removing or creating anything but just adding some params to) current URL on a view page.

How do I get the Grails Export plugin to work correctly with criteria queries?

I'm trying to get a Criteria query to be exported to CSV, Excel, what have you. The issue I'm running into is that the categories code runs cleanly (as in, doesn't throw any errors), but it doesn't generate any data. I know for a fact that data is an ArrayList of List. Anyone have a workaround for this, or tell me if I'm doing something wrong?
Here's my domain object:
class Machine {
String name,
category
// constraints, etc
}
Here's my controller action (taken mostly from the plugin page):
def categories = {
if(params?.format && params.format != "html"){
response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
response.setHeader("Content-disposition", "attachment; filename=categories.${params.extension}")
def data = Machine.createCriteria().list {
projections {
groupProperty("category")
countDistinct("id")
}
}
exportService.export(params.format, response.outputStream, data, [:], [:])
}
Here's one possible solution that I thought of as soon as I submitted the question: Expando. Here's the changes to the controller method:
// response stuff above
def fields = ["category", "count"]
def labels = ["category": "Category", "count": "# of machines" ]
def data = Machine.createCriteria().list {
projections {
groupProperty("category")
countDistinct("id")
}
}.collect { l -> new Expando("category": l[0], "count": l[1]) }
exportService.export(params.format, response.outputStream, data, fields, labels, [:], [:])
I'm exploiting the fact that the Export plugin tries to get a value from an object. So, I give it an object.
If there's a better solution, I'll be more than happy to see it.

Resources