How to get sub content after running readFile in Jenkins - jenkins

I have a question about how to get sub content after running readFile in Jenkins.
I print the content after readFile method of groovy in Jenkins
the content looks like this
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: asdfasdf
Team: {org=org1, team=team1}
ABCD: {org=org2, team=team2}
ABCDE: {org=org3, team=team3}
Bundle-Vendor: xxxxx
I just want to get this line in the content
Team: {org=org1, team=team1}
ABCD: {org=org2, team=team2}
ABCDE: {org=org3, team=team3}
but how??
any Solutions?

The content of your file looks like it is a properties file, so you can use the readProperties keyword which is part of the Pipeline Utility Steps to read the file into a map, allowing you easy access to all the values:
readProperties: Read properties from files in the workspace or text.
Reads a file in the current working directory or a String as a plain text Java Properties file. The returned object is a normal Map with String keys. The map can also be pre loaded with default values before reading/parsing the data.
You now have easy access to the keys and values.
In your case it can look like:
def props = readProperties file: 'YOUR_FILE_PATH'
// You can now access all values from the props map
def content = "Team: ${props.Team}"
If you just want the line based on parsing the file content you can read the file, split the content by new lines and use something like the following:
def lines = readFile('YOUR_FILE_PATH').split("\n").trim()
// Get a constant line
def content = lines[4]
// Get a line by prefix
def content = lines.find{ it.startsWith('Team')}

Related

How to change new File method in Groovy?

How do I replace the new File method with a secure one? Is it possible to create a python script and connect it?
Part of the code where I have a problem:
def template Name = new File(file: "${template}").normalize.name.replace(".html", "").replace(".yaml", "")
But when I run my pipeline, I get the error
java.lang.SecurityException: Unable to find constructor: new java.io .File java.util.LinkedHashMap
This method is prohibited and is blacklisted. How do I replace it and with what?
If you're reading the contents of the file, you can replace that "new File" with "readFile".
See https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#readfile-read-file-from-workspace
readFile: Read file from workspace
Reads a file from a relative path (with root in current directory, usually > workspace) and returns its content as a plain string.
file : String
Relative (/-separated) path to file within a workspace to read.
encoding : String (optional)
The encoding to use when reading the file. If left blank, the platform default encoding will be used. Binary files can be read into a Base64-encoded string by specifying "Base64" as the encoding.

Cannot replace line after string match in jenkins pipeline using variables

I need to replace a line in a file. If the line starts with the term "url", I need to replace the value.
file.txt --
...
url : http://www.google.com
..
I need to change this value to
url : http://www.facebook.com
I tried the following code but it did not work -
FACEBOOK_URL = "http://www.facebook.com"
sh("sed -i \\"s?^url.*\\$?url: ${FACEBOOK_URL}?\\" file.txt")
I'm using a Jenkins Pipeline. I need to replace the string using a variable.
Jenkins 2 Pipeline builds use Groovy and it is very easy to read the file using readfile and then we can do the changes
def text = readFile "file.txt"
text.replaceAll("url.*", "url: ${FACEBOOK_URL}")
The above code will help in replacing the text in the file, if you want to write the content to file, you can use writeFile
You can use this for replacing a string in a file in Jenkins 2 Pipeline builds:
def text = readFile file: "file.txt"
text = text.replaceAll("%version%", "${VERSION}")
writeFile file: "file.txt", text: text

Jenkins...Modify XML Tag value in xml file using Groovy in Jenkins

I am using jenkins for automated deployment.
I needs to modify xml tag value in xml file using groovy script. I am using below groovy code. When I try to edit xml tag value I am receiving error unclassified field xml.uti.node error.
Node xml = xmlParser.parse(new File("c:/abc/test.xml"))
xml.DeployerServer.host[0] = '172.20.204.49:7100'
FileWriter fileWriter = new FileWriter("c:/abc/test.xml")
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(fileWriter))
nodePrinter.setPreserveWhitespace(true)
nodePrinter.print(xml)
I need to modify host tag value and host is available inside DeployerServer tag.
Any help will be much appreciated.
Here is the script, comments in-line:
//Create file object
def file = new File('c:/abc/test.xml')
//Parse it with XmlSlurper
def xml = new XmlSlurper().parse(file)
//Update the node value using replaceBody
xml.DeployerServer.host[0].replaceBody '172.20.204.49:7100'
//Create the update xml string
def updatedXml = groovy.xml.XmlUtil.serialize(xml)
//Write the content back
file.write(updatedXml)
I was wanting to read / manipulate the CSProj file and NUSPEC files in a Pipeline script. I could not get passed the parseText() without the dreaded "SAXParseException: Content is not allowed in prolog".
There are quite a few threads about this error message. What wasn't clear is that both CSProj and NUSPEC files are UTF-8 with BOM - BUT this is invisible!
To make it worse I've been trying to automate the NUSPEC file creation, and there is no way I can tell the tools to change file encoding.
The answers above helped solve my issue, and once I added code to look for 65279 as the first character (and deleted it). I could then parse the XML and carry out the above.
There didn't seem to be good thread to put this summary on, so added it to a thread about Jenkins, Groovy & XML files which is where I found this "known Java" issue.
I used powershell to do this change in app.config file.
My problem was with passwords. So, I created a Credential, in jenkins, to store the password.
If you do not need to work with credential, just remove the withCredentials section
Here is part of my jenkinsfile:
def appConfigPath = "\\server\folder\app.config"
stage('Change App.Config'){
steps{
withCredentials([string(credentialsId: 'CREDENTIAL_NAME', variable: 'PWD')]) {
powershell(returnStdout: true, script: '''
Function swapAppSetting {
param([string]$key,[string]$value )
$obj = $doc.configuration.appSettings.add | where {$_.Key -eq $key }
$obj.value = $value
}
$webConfig = "'''+appConfigPath+'''"
$doc = [Xml](Get-Content $webConfig)
swapAppSetting 'TAG_TO_MODIFY' 'VALUE_TO_CHANGE'
$doc.Save($webConfig)
''')
}
}
}
Don`t forget to update your powershell. (minimum version 3)

How do I batch extract metadata from DM3 files using ImageJ?

How can you extract metadata for a batch of images? My first thought was to record a macro and then modify it to operate on a list of file names.
In that vein, I tried recording a macro doing something like this:
Ctrl-o # Open a file
12.dm3Enter # Select file to open
Ctrl-i # Open metadata in a new window
Ctrl-s # Save file
Info for 12.txtEnter# Name of file being saved
Ctrl-w# Close current window
Ctrl-w# Close current window
These steps work when I do them manually. This results in the following macro, which seems to be missing most of what I tried to record:
open("/path/to/file/12.dm3");
run("Show Info...");
run("Close");
run("Close");
Modifying a Jython script that is supposed to extract dimension metadata from an image:
from java.io import File
from loci.formats import ImageReader
from loci.formats import MetadataTools
import glob
# Create output file
outFile = open('./pixel_sizes.txt','w')
# Get list of DM3 files
filenames = glob.glob('*.dm3')
for filename in filenames:
# Open file
file = File('.', filename)
# parse file header
imageReader = ImageReader()
meta = MetadataTools.createOMEXMLMetadata()
imageReader.setMetadataStore(meta)
imageReader.setId(file.getAbsolutePath())
# get pixel size
pSizeX = meta.getPixelsPhysicalSizeX(0)
# close the image reader
imageReader.close()
outFile.write(filename + "\t" + str(pSizeX) + "\n")
# Close the output file
outFile.close()
(Gist).
You could use getImageInfo() instead of run("Show Info..."). This will create a string in the macro containing the run("Show Info...") output, but can then be modified as you like. See http://rsb.info.nih.gov/ij/developer/macro/functions.html#getImageInfo for more information.

Save current document as .html with same name and path

I'm working on a script for FoldingText which will convert a FoldingText outline (basically a Markdown Text file) into a Remark presentation (an HTML script which makes slideshows from Markdown files). The script works, but I'd like to make the following improvement:
Instead of asking for the name and location to save the HTML file, I'd like to grab the name of the current document and save it as an HTML file (with the same name) in the current folder. The script should fail nicely if there is already a document with that name (offering to either write-over the document or save as a new document with a different name).
The script I'm using for writing to the file was from these forums. The first part is:
on write_to_file(this_data, target_file, append_data) -- (string, file path as string, boolean)
try
set the target_file to the target_file as text
set the open_target_file to ¬
open for access file target_file with write permission
if append_data is false then ¬
set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof as «class utf8»
close access the open_target_file
return true
on error
try
close access file target_file
end try
return false
end try
end write_to_file
And the second part is:
set theFile to choose file name with prompt "Set file name and location:"
my write_to_file(finalText, theFile, true)
Thanks.
FoldingText should have some way of retrieveng the path of the document. I've not found any free dowonload fo the application, so I've not benn able to check by myself, but you should be able to find it if you view the dictionary of the application.
My guess is that there's a property like 'path of', or 'file of' for the FoldingText document:
You will probably end up with something like this:
set theDocPath to file of front document of application "FoldingText"
tell application "Finder"
set theContainer to container of theFile
end tell
set newPath to (theContainer & "export.html) as string
repeat while (file newPath exists)
set newPath to choose file name with prompt "Set file name and location:"
end repeat
my write_to_file(finalText, newPath, true)

Resources