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
Related
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")
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.
I want little help which I suspect is due to my lack of understanding for Groovy syntax. So, here's the thing:
On the GSP page I want to set a field's value from the params map which is
["id":"107901", "Field_10.value":"2", "Field_10":["value":"2"],"Field_11.value":"", "Field_11":["value":""],action:'abc']
On the gsp page, I want to find the value against the key Field_{some-id}.value
So I am calling a tag like, g.testTag(id:field.id) with its implementation as
def testTag = { attrs,body->
println "params are ${params}"
def result = ""
def keyRequired = "Field_${attrs.id}.value"
println "keyRequired >>>>> ${keyRequired.toString()}"
params.each { key,value->
println "key is ${key}"
println "Value is ${value}"
if (key.equals(keyRequired.toString())) {
result = params.value
}
}
println "Final result is >>>>>> ${result}"
}
The value passed in id is 10 and with my params printed as above, I was expecting a value
of 2 which is corresponding to the key in the params to show up. But apparently I see the
result as null..
What am I doing wrong ? Can anyone help please...
Thanks
Not result = params.value, but result = value.
You have to change the line:
result = params.value
to:
result = value
At the each loop, you're basically saying that inside the params iteration, you're naming every key "key" and every value "value". So, params.value will actually look for the key value inside your params map, which is null.
Funny that you do that right with key but not with value. Probably just got distracted.
it is likely what you want to do, the groovy way (no need to loop over the keys of the map) to access "Field_10.value":"2"
result=params["Field_${attrs.id}.value"]
Alternatively, this also works because you have "Field_10":["value":"2"] in your map
result=params["Field_${attrs.id}"].value
I want to print my xml which is coming from an external feed on the console.
When I do
log.debug "${xml}"
I get xml values on the console but not the starting and end tags. For example
<fruits>
<fruit1>apple</fruit1>
<fruit2>orange</fruit2>
</fruits>
Just prints appleorange
Just the values concatenated one after other. What is the best value to handle it. I tried this Best way to pretty print XML response in grails but I get exception at parseText(). I don't know why, because I think the incoming xml is valid.
Update: The type of variable xml is Groovy's NodeChild.
You can do the following, if your xml is simple it should satisfy your needs:
`
def xml = new XmlSlurper().parseText(xmlString)
def result = new StreamingMarkupBuilder().bind{
mkp.yield xml
}
log.debug result as String
`
try this
def writer = new StringWriter()
xml.writeTo(writer)
log.debug writer.toString()
I want to parse a random website, modify the content so that every word is a link (for a dictionary tooltip) and then display the website in an iframe.
I'm not looking for a complete solution, but for a hint or a possible strategy. The linking is my problem, parsing the website and displaying it in an iframe is quite simple. So basically I have a String with all the html content. I'm not even sure if it's better to do it serverside or after the page is loaded with JS.
I'm working with Ruby on Rails, jQuery, jRails.
Note: The content of the href tag depends on the word.
Clarification:
I tried a regexp and it already kind of works:
#site.gsub!(/[A-Za-z]+(?:['-][A-Za-z]+)?|\\d+(?:[,.]\\d+)?/) {|word| '' + word + ''}
But the problem is to only replace words in the text and leave the HTML as it is. So I guess it is a regex problem...
Thanks for any ideas.
I don't think a regexp is going to work for this - or, at least, it will always be brittle. A better way is to parse the page using Hpricot or Nokogiri, then go through it and modify the nodes that are plain text.
It sounds like you have it mostly planned out already.
Split the content into words and then for each word, create a link, such as whatever
EDIT (based on your comment):
Ahh ... I recommend you search around for screen scraping techniques. Most of them should start with removing anything between < and > characters, and replacing <br> and <p> with newlines.
I would use Nokogiri to remove the HTML structure before you use the regex.
no_html = Nokogiri::HTML(html_as_string).text
Simple. Hash the HTML, run your regex, then unhash the HTML.
<?php
class ht
{
static $hashes = array();
# hashes everything that matches $pattern and saves matches for later unhashing
function hash($text, $pattern) {
return preg_replace_callback($pattern, array(self,'push'), $text);
}
# hashes all html tags and saves them
function hash_html($html) {
return self::hash($html, '`<[^>]+>`');
}
# hashes and saves $value, returns key
function push($value) {
if(is_array($value)) $value = $value[0];
static $i = 0;
$key = "\x05".++$i."\x06";
self::$hashes[$key] = $value;
return $key;
}
# unhashes all saved values found in $text
function unhash($text) {
return str_replace(array_keys(self::$hashes), self::$hashes, $text);
}
function get($key) {
return self::$hashes[$key];
}
function clear() {
self::$hashes = array();
}
}
?>
Example usage:
ht::hash_html($your_html);
// your word->href converter here
ht::unhash($your_formatted_html);
Oh... right, I wrote this in PHP. Guess you'll have to convert it to ruby or js, but the idea is the same.