Jenkins Customize Editable Email Content - jenkins

In my Jenkins step I have windows batch command which runs a java jar file (java -Dfile.encoding=UTF-8 -jar C:\Test1\Test.jar C:\Test\test.log) and output of which is a String value (verified Jenkins console the string is getting printed) . How will I use this string content and insert in the editable email content body so I can send this content as an email . I wouldn't want the whole Jenkins console in the email only this String. I would assume the string has to be set as an environment variable after the script runs . Not sure how exactly I can use EnvInjPlugin for my scenario if at all it can be.

Try to use pre-send script.
For example You have in log the string like: "this random integer should be in email content: 3432805"
and want to add randomly generated integer to email content.
Set the Default Content with whatever you want but add some
value which will be replaced. For example:
This is the random int from build.log: TO_REPLACE
Then click "Advanced Settings" and add Pre-send Script:
String addThisStringToContent = "";
build.getLog(1000).each() { line ->
java.util.regex.Pattern p = java.util.regex.Pattern.compile("random\\sinteger.+\\:\\s(\\d+)");
java.util.regex.Matcher m = p.matcher(line);
if (m.find()) {
addThisStringToContent = m.group(1);
}
}
if (addThisStringToContent == "") {
logger.println("Proper string not found. Email content has not been updated.");
} else {
String contentToSet = ((javax.mail.Multipart)msg.getContent()).getBodyPart(0).getContent().toString().replace("TO_REPLACE", addThisStringToContent);
msg.setContent(contentToSet, "text/plain");
}
where:
build.getLog(1000) - retrieves the last 1000 lines of build output.
Pattern.compile("random\\sinteger.+\\:\\s(\\d+)") - regex to find the proper string
"text/plain" - Content Type
String contentToSet = ((javax.mail.Multipart)msg.getContent()).getBodyPart(0).getContent().toString().replace("TO_REPLACE", addThisStringToContent); - replaces the string TO_REPLACE with your value
Hope it will help you.

Unfortunately I have not enough reputation to comment Alex' great answer, so I write a new answer. The call
msg.setContent(contentToSet, "text/plain")
has two disadvantages:
Special characters are garbled
An attachment gets lost
So I use the following call to set the modified text
((javax.mail.Multipart)msg.getContent()).getBodyPart(0).setContent(contentToSet, "text/plain;charset=UTF-8")

Related

How to print a line only if it contains a specific string using groovy?

I have a Jenkins log file and I want to print the lines that contain the string "FOUND" on it.
How to achieve that using Groovy?
You could do something like this and comments in-line.
//Change log file name in below statement
def lines = new File('/tmp/test123.txt').readLines()
//Get the list of matching lines
def result = lines.findAll { it.contains('FOUND') }
println result*.toString()

How can I convert GPathResult to text without pretty format

I'm trying to use groovy to update Jenkins job config.xml by the following code
def updateParameter(String key, String value){
println "changing defult value as $value for key $key"
def xml = new XmlSlurper().parseText(jobConfig)
xml.properties.'hudson.model.ParametersDefinitionProperty'.'parameterDefinitions'.'hudson.model.StringParameterDefinition'.each {
println 'found parameter: ' + it.name
if(it.name.text() == key){
println('default value changed')
it.defaultValue=value
}
}
jobConfig = XmlUtil.serialize(xml)
}
When running jobConfig = XmlUtil.serialize(xml), it changes the format, which is pretty, but I lost link break in pipeline plugin, so pipeline script doesn't work anymore. Is there a way to convert GPathResult to String without format changing?
Best Regards,
Eric
It is all my fault, the line breaks were removed when I read the xml. It seems XmlUtil.serialize(xml) doen't format the text of a xml tag, which is good :)
Best Regards,
Eric

URL Mapping - Replacing characters in a parameter pulled from a database

I am currently trying to figure out, how to modify the parameter being integrated into the URL Mapping I am using.
static mappings =
{
"/$controller/$action?/$id?/(.$format)?"
{
constraints {
// apply constraints here
}
}
name test1: "/.../$title/..."{
controller = "study"
action = "st_show"
}
name test2: "/.../$title/..."{
controller = "search"
action = "se_show"
}
The parameter $title is pretty much a dataset, which is pulled from a database and which will get transmitted in the following format [ this is a title ]. So there are square brackets in front and behind the string and words are seperated through blanks.
If I am creating a link through g:link now with the params nested in, it gets put into the url as it is pulled from the database. What I am attempting is to create SEO-URLs, which will present a certain title of a publication devided by hyphens instead of url-encoded "%20".
Until now, I was able to generate dynamic urls looking like this:
http://localhost:8080/projectname/show/%5BAllgemeine%20Bevölkerungs[...]/782/...PARAMS...
Furthermore I already implemented it through JQuery, though it should be static and users should be able to copy the link to open up the page themselves - that wouldn't be possible when changing the url client-side while loading up the page.
Is there a way to define a function with something like replaceAll.(' ', '-'), which can be invoked onto the parameter in the mapping to replace blanks with hyphens and f.e. square brackets with an empty character?
That's pretty much, what I wasn't able to come by through the documentation.
Thank you already in advance for your help!
I managed to solve my problem by creating a service with a function containing a regex and executing this function onto the parameter title in my g:link, which I firstly converted to a string, which gets passed to the function.
<g:link controller="study" action="st_show" params="[data: data, ... title: ConversionService.convert(fieldValue(bean: path).toString(), ... data: data)]"></g:link>
And the function in the ConversionService
public static String convert(String title){
title = title.replaceAll("\\s", "-").replaceAll("[^0-9a-zA-Z\\-]", "");
return title;
}

How to show String new lines on gsp grails file?

I've stored a string in the database. When I save and retrieve the string and the result I'm getting is as following:
This is my new object
Testing multiple lines
-- Test 1
-- Test 2
-- Test 3
That is what I get from a println command when I call the save and index methods.
But when I show it on screen. It's being shown like:
This is my object Testing multiple lines -- Test 1 -- Test 2 -- Test 3
Already tried to show it like the following:
${adviceInstance.advice?.encodeAsHTML()}
But still the same thing.
Do I need to replace \n to or something like that? Is there any easier way to show it properly?
Common problems have a variety of solutions
1> could be you that you replace \n with <br>
so either in your controller/service or if you like in gsp:
${adviceInstance.advice?.replace('\n','<br>')}
2> display the content in a read-only textarea
<g:textArea name="something" readonly="true">
${adviceInstance.advice}
</g:textArea>
3> Use the <pre> tag
<pre>
${adviceInstance.advice}
</pre>
4> Use css white-space http://www.w3schools.com/cssref/pr_text_white-space.asp:
<div class="space">
</div>
//css code:
.space {
white-space:pre
}
Also make a note if you have a strict configuration for the storage of such fields that when you submit it via a form, there are additional elements I didn't delve into what it actually was, it may have actually be the return carriages or \r, anyhow explained in comments below. About the good rule to set a setter that trims the element each time it is received. i.e.:
Class Advice {
String advice
static constraints = {
advice(nullable:false, minSize:1, maxSize:255)
}
/*
* In this scenario with a a maxSize value, ensure you
* set your own setter to trim any hidden \r
* that may be posted back as part of the form request
* by end user. Trust me I got to know the hard way.
*/
void setAdvice(String adv) {
advice=adv.trim()
}
}
${raw(adviceInstance.advice?.encodeAsHTML().replace("\n", "<br>"))}
This is how i solve the problem.
Firstly make sure the string contains \n to denote line break.
For example :
String test = "This is first line. \n This is second line";
Then in gsp page use:
${raw(test?.replace("\n", "<br>"))}
The output will be as:
This is first line.
This is second line.

How to avoid "Path Manipulation" error in Fortify? [duplicate]

I have path Manipulation problem. The following code is placed in Page_load method of ASPx page.
String rName = Request.QueryString["reportName"];
string path = "C:\\hari" + rName;
if (File.Exists(path))
{
File.Delete(path);
}
But Fortify scan report for the above sample code shows ‘Path Manipulation’ issue as high
Need help to modify above code so that it can pass fortify scan
Jackson is right, this is a direct File Path Manipulation vulnerability that can be fixed through indirect selection.
From your known directory, list all the files. Use the value coming from your own directory list, not the user-supplied value.
String rName = Request.QueryString["reportName"];
String knownPath = "C:\\hari";
DirectoryInfo di = new DirectoryInfo(knownPath);
FileInfo[] files = di.GetFiles(rName);
if (files.length > 0)
{
files[0].Delete();
}
I think the problem is that someone could spoof a request with reportName = "..\\Windows\\Something important" which is clearly a security flaw. You need to change your code so that it doesn't read a partial filename from the request query string.

Resources