Jenkins pipeline: join file / URL paths - jenkins

How can I join strings nicely into a path when programming Jenkins Groovy pipeline? So that I can join('http://example.com/', '/r', 'some.html') -> 'http://example.com/r/some.html'
This note suggests using new File(dir1, dir2) or Paths.get(dir1, dir2) in "pure" Groovy.
However in Jenkins pipeline, import java.nio.file.Paths gives me
No such static method found: staticMethod java.nio.file.Paths get java.lang.String org.codehaus.groovy.runtime.GStringImpl.
and with new File I get
Scripts not permitted to use new java.io.File java.lang.String java.lang.String. Administrators can decide whether to approve or reject this signature.
and I kinda agree with Jenkins on this do not want to allow this. Is there another way?

bad idea to build url with Paths or File objects because under windows you'll get wrong result.
you can build url with simple string concatenation and use URI.normalize() to remove extra slashes:
def u = new URI(['http://example.com/', '/r', 'some.html'].join('/')).normalize().toString()

Try this:
def join_two_urls(url1, url2) {
if (url1 == "" || url2 == "") {
println "Error: must provde two invalid urls."
return ""
}
println "Joining ${url1} and ${url2} ..."
if (url1 ==~ /.*\/$/) {
url1 = url1.substring(0, url1.length() - 1)
}
if (url2 ==~ /^\/.*/) {
url2 = url2.substring(1, url2.length())
}
return url1 + "/" + url2
}
def join_paths(String[] urls) {
if (urls.size() <= 1) {
println "Error: invalid urls."
return ""
}
conbined_url = ""
pre_url = ""
for (url in urls) {
if (pre_url == "") {
pre_url = url
continue
}
conbined_url += join_two_urls(pre_url, url)
}
return conbined_url
}
println join_paths("xx/", "xxx/" , "/fsdsdfsdf")

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.

How to Jenkins Groovy scripting for live fetching of Docker image + authentication

I have a script groovy, this script for live fetching of docker image,
I want to add the authentication function with the private repository, but I am not familiar with groovy, who can help me, thanks
import groovy.json.JsonSlurper
// Set the URL we want to read from, it is MySQL from official Library for this example, limited to 20 results only.
docker_image_tags_url = "https://registry.adx.abc/v2/mysql/tags/list"
try {
// Set requirements for the HTTP GET request, you can add Content-Type headers and so on...
def http_client = new URL(docker_image_tags_url).openConnection() as HttpURLConnection
http_client.setRequestMethod('GET')
// Run the HTTP request
http_client.connect()
// Prepare a variable where we save parsed JSON as a HashMap, it's good for our use case, as we just need the 'name' of each tag.
def dockerhub_response = [:]
// Check if we got HTTP 200, otherwise exit
if (http_client.responseCode == 200) {
dockerhub_response = new JsonSlurper().parseText(http_client.inputStream.getText('UTF-8'))
} else {
println("HTTP response error")
System.exit(0)
}
// Prepare a List to collect the tag names into
def image_tag_list = []
// Iterate the HashMap of all Tags and grab only their "names" into our List
dockerhub_response.results.each { tag_metadata ->
image_tag_list.add(tag_metadata.name)
}
// The returned value MUST be a Groovy type of List or a related type (inherited from List)
// It is necessary for the Active Choice plugin to display results in a combo-box
return image_tag_list.sort()
} catch (Exception e) {
// handle exceptions like timeout, connection errors, etc.
println(e)
}
The problem has been resolved, thank you everyone for your help
// Import the JsonSlurper class to parse Dockerhub API response
import groovy.json.JsonSlurper
// Set the URL we want to read from, it is MySQL from official Library for this example, limited to 20 results only.
docker_image_tags_url = "https://registry.adx.vn/v2/form-be/tags/list"
try {
// Set requirements for the HTTP GET request, you can add Content-Type headers and so on...
def http_client = new URL(docker_image_tags_url).openConnection() as HttpURLConnection
http_client.setRequestMethod('GET')
String userCredentials = "your_user:your_passwd";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
http_client.setRequestProperty ("Authorization", basicAuth);
// Run the HTTP request
http_client.connect()
// Prepare a variable where we save parsed JSON as a HashMap, it's good for our use case, as we just need the 'name' of each tag.
def dockerhub_response = [:]
// Check if we got HTTP 200, otherwise exit
if (http_client.responseCode == 200) {
dockerhub_response = new JsonSlurper().parseText(http_client.inputStream.getText('UTF-8'))
} else {
println("HTTP response error")
System.exit(0)
}
// Prepare a List to collect the tag names into
def image_tag_list = []
// Iterate the HashMap of all Tags and grab only their "names" into our List
dockerhub_response.tags.each { tag_metadata ->
image_tag_list.add(tag_metadata)
}
// The returned value MUST be a Groovy type of List or a related type (inherited from List)
// It is necessary for the Active Choice plugin to display results in a combo-box
return image_tag_list.sort()
} catch (Exception e) {
// handle exceptions like timeout, connection errors, etc.
println(e)
}
here is the result

function lines after httpRequest are not executed in groovy jenkins pipeline

None of the lines after making httpRequest are getting executed. Everything else works fine in this function. What could be going wrong here?
However, network request is going fine and I am able to see the response in the console. httpRequest is being made via plugin
I've even tried CURL - but lines after curl are not executed.
#NonCPS
def doPRCommentBasedTesting() {
def causes = currentBuild.rawBuild.getCauses()
def commentURL
for(cause in causes) {
if (cause.class.toString().contains("GitHubPullRequestCommentCause")) {
commentURL = cause.getCommentUrl()
commentURL = commentURL.substring(commentURL.lastIndexOf("-") + 1)
println "This job was caused by job " + commentURL
def url1 = "https://<git_url>/api/v3/repos/<owner>/<repo>/issues/comments/" + commentURL
def commentText = httpRequest authentication: '<auth_cred>', url: url1, consoleLogResponseBody: true
println commentText
println commentText.getClass()
println "hello world, how are you doing today?"
}
else {
println "Root cause : " + cause.toString()
}
}
println "==============================="
return 0
}
A non cps function does not have the ability to pause in between because it runs in a go. You need to put network call into a different function that is not marked as nonCPS and then it will work. In general the nonCPS block should be very small and limited to code that cannot be serialised

How to get the file extension in grails?

I recently started working on grails and i want to know how to get the
extension of a file. Ex: test.txt. I want to check extension(txt)?
any clue?
Here's another way. Using a regular expression.
def fileName = 'something.ext'
def matcher = (fileName =~ /.*\.(.*)$/)
if(matcher.matches()) {
def extension = matcher[0][1]
if(extension in ['jpg', 'jpeg', 'png']) {
// Good to go
println 'ok'
} else {
println 'not ok'
}
} else {
println 'No file extension found'
}
The question asks how to get the file extension.
With groovy, the following operation will give you the file extension of any file name:
def fileName = ...
def fileExt = fileName - ~/.*(?<=\.)/
The accepted answer goes a bit further and tries to check for specific file extensions. You can use the match operator ==~ to do this as well:
assert fileName ==~ ~/.*(?<=\.)(txt|jpe?g|png)/
This assertion will work provided the file name ends with one of the supplied extensions.
Also noticed that groovy can do positive lookbehind using (<?\.)
Hope i found the answer of my Question. How to find the extension
of a file.
String fileName = "something.ext";
int a = fileName.lastIndexOf(".");
String extName = fileName.substring(a);
System.out.println(fileName.substring(a));
ArrayList<String> extList = new ArrayList<String>();
extList.add("jpg");
extList.add("jpeg");
extList.add("png");
if(extList.contains(extName))
{
System.out.println("proceed");
}
else{
System.out.println("throw exception");
}
Lsat comment at this post

Logic block in Grails URLMappings

My site has urls like 'http://someRandomUsername.mysite.com'.
Sometimes users will try urls like
'http://www.someRandomeUsername.mysite.com'. I'd like to have some
logic in my url mappings to deal with this.
With the mappings below when I hit the page , with or without the
unneeded www, I get:
2012-03-01 14:52:16,014 [http-8080-5] ERROR [localhost].[/ambit] -
Unhandled exception occurred whilst decorating page
java.lang.IllegalArgumentException: URL mapping must either provide a
controller or view name to map to!
Any idea how to accomplish this? The mapping is below.
Thanks!
Jason
static mappings = {
name publicMap: "/$action?/$id?" {
def ret = UrlMappings.check(request)
controller = ret.controller
userName = ret.userName
}
}
static check =
{ request ->
def tokens = request?.serverName?.split(/\./) as List ?: []
def ret = [controller:'info']
if(tokens.size() > 3 && token[0] == 'www')
{
ret.userName = tokens[1]
ret.controller = 'redirect'
ret.action = 'removeWWW'
}
else if(tokens.size() == 3)
{
ret.userName = tokens[0]
ret.controller = 'info'
}
return ret
}
Honestly, like DmitryB said, the best way to do this is via the web server, whether it's IIS, Apache, or Tomcat.
Having said that, I feel the best way to accomplish this in Grails would be using filters.
You could create something like this in your ~/conf directory:
public class StripFilters {
def filters = {
stripWWWFilter(controller: '*', action: '*') {
before = {
def tokens = request.serverName.tokenize(/\./) ?: []
if(tokens.size() > 3 && tokens[0] == 'www') {
def url = request.request.requestURL.toString().replace('www.', '')
redirect([url:url, params: [userName: tokens[1]], permanent: true])
return false
}
}
}
}
}
This should do the trick.

Resources