Mapping function to manipulate URLs, groovyscript - groovy

I am trying to manipulate a number of URLs using groovyscript.
The URLs have been output in the form:
http://wiki.somecompany.com/FOLDER/file/attach/FOLDER/test/random.txt
where FOLDER is one of a list of different folder names.
These URLs actually need to be transformed to the following:
http://wiki.somecompany.com/pub/FOLDER/test/random.txt
I can change one folder at a time with this code:
def longFOLDERName = "FOLDER/file/attach/FOLDER";
def FOLDERName = "pub/FOLDER";
displayURL = url.replaceAll(longFOLDERName,FOLDERName);
Repeating it for each different folder name, but obviously this is time consuming and inefficient.
How do I select the text between .com/ and /file, compare it with the folder name after attach/, and then turn the whole thing into a function?
The string value of the URL is stored as displayURL.

I believe you can go with regular expressions.
def url = 'http://wiki.somecompany.com/MY_FOLDER/file/attach/MY_FOLDER/test/random.txt'
def regex = /^http:\/\/wiki\.somecompany\.com\/(.+)\/file\/attach\/(.+)\/test\/random\.txt$/
def matcher = (url =~ regex)
def folder = matcher[0][1] // here you get your "MY_FOLDER"
def resultUrl = "http://wiki.somecompany.com/pub/$folder/test/random.txt" // here you make string interpolation
As you may notice, the (.+) matches any string. The [0] gets you the list of matches ([http://wiki.somecompany.com/MY_FOLDER/file/attach/MY_FOLDER/test/random.txt, MY_FOLDER, MY_FOLDER]) and the [1] is the folder name you care about.
Hope it helps

def stringInput = "http://wiki.somecompany.com/FOLDER/file/attach/FOLDER/test/random.txt";
def stringSplit = stringInput.split("/");
i=0;
while (stringSplit[i] != "attach"){
i++;
}
if ( i+1 != stringSplit.length && stringSplit[i-2] ==stringSplit[i+1] && stringSplit[i-1]=="file"){
def stringOutput = stringInput.replaceAll(stringSplit[i+1]+"/file/attach","pub");
}

You can use a regexp to capture more than just FOLDER.
def urls = [
"http://wiki.somecompany.com/FOLDER/file/attach/FOLDER/test/random.txt",
"http://wiki.somecompany.com/OTHER/file/attach/OTHER/something/random.html",
]
def r = /(FOLDER|OTHER)\/file\/attach\/\1/
// ^ ^ ^
// | | +-- backref first group
// | +-- Stuff in between you want get rid off
// +-- All folder names, you want to change
assert [
"http://wiki.somecompany.com/pub/FOLDER/test/random.txt",
"http://wiki.somecompany.com/pub/OTHER/something/random.html",
] == urls.collect{
it.replaceAll(r, 'pub/$1') // replace the whole match with `/pub/`
// and the value of the first group
}

Related

How to use map in groovy

Here is how my script currently looks like -
baseList = readFile('text2.txt').split('\n') as List
def cleanList = []
for (i=0; i < baseList.size; i++) {
if (baseList[i].contains('=')){
cleanList += baseList[i]
}
}
print(cleanList)
This gives following output-
[Pipeline] echo
[version.build=874, version.maintenance=0, version.major=1, version.minor=37]
I want these values to go into another variable called "svnTag"
def svnTag="ccsmp_v_${version.major} ${version.minor} ${version.maintenance} ${version.build}"
So that when I print svnTag, it output something like this-
SVN_TAG=ccsmp_v_1.37.0.846
You are not using a Map, but a List of String, where each element is in the form of <key>=<value>
If you want to parse your file to a Map, you could use something like:
def baseList = readFile('text2.txt').split('\n') as List
def map = [:]
for (el in baseList) {
if (el.contains('=')) {
def parts = el.split('=')
map[parts[0]] = parts[1]
}
}
Then you can use the values from the map with:
def svnTag="ccsmp_v_${map['version.major']} ${map['version.minor']} ${map['version.maintenance']} ${map['version.build']}"
If your file is a valid property file (all lines are in form of key=value), you can use the readProperties step that will create a Properties object for you (that is in fact a Map):
def map = readProperties file: 'text2.txt'

Groovy script to split a file line at ',' and create a new XML file

I am very new to Groovy and trying to figure my way out.
I am trying to write a groovy to split the lines of a file on encountering ',' and then write a if condition based on the first two characters of the line. After that I wanted to create a XML file using the different data in the file. This is how far I have reached.
def Message processData(Message message) {
//Body
def body = message.getBody(java.lang.String)as String;
def varStringWriter = new StringWriter();
def varXMLBuilder = new MarkupBuilder(varStringWriter);
String newItem ;
body.eachLine{
line -> newItem = line ;
String newItem1 = newItem.substring(0,2).trim();
String newItem2 = newItem.substring(3,11).trim();
varXMLBuilder.RECORD{
node1(newItem1);
node2(newItem2);
}
}
def xml = varStringWriter.toString();
xml="<RECORDS>"+xml+"</RECORDS>" ;
message.setBody(xml);
return message;
}
In the above code I tried to use offset but, since each of my file lines are of different length it wont work.
Please help me handle this issue.
Regards,
Nisha
Splitting on a character can be done like this:
data = 'axaratgxrgc,rxregxsergcs'
def lines = data.split(/,/)
assert lines[0] == 'axaratgxrgc'
assert lines[1] == 'rxregxsergcs'
Welcome, first of all, to groovy and Stack Overflow :)
You can use tokenize() to split a string, as shown bellow.
And yeah, don't worry about ; in groovy ;)
def Message processData(Message message) {
//Body
def body = message.getBody(java.lang.String) as String;
def varStringWriter = new StringWriter()
def varXMLBuilder = new MarkupBuilder(varStringWriter)
body.eachLine { line ->
def newItems = line.tokenize(',') // input is a list of chars that will split your string, usually better than .split()
String newItem1 = newItems.first() // looks like you want just two items
String newItem2 = newItems.last() // but you can use as an array as well newItems[0] and newItems[1]
varXMLBuilder.RECORD {
node1(newItem1)
node2(newItem2)
}
}
def xml = varStringWriter.toString()
xml="<RECORDS>${xml}</RECORDS>" // you can use ${} to add a variable inside a string
message.setBody(xml)
return message
}

How I can remove extension from string in list (groovy)?

I have list def list = ['values.txt'] and I want to remove extension from filename and receive string . How I can do this ?
Expecting result is -- filename = 'values'.
If you happen to open ANY Groovy book or tutorial you would find a lot of solutions.
For example:
def list = ['values.txt']
def noExtensions = list.collect{ it.split( /\./ )[ 0 ] }
assert ['values'] == noExtensions

How to extract a numeric id from a string using groovy in SOAP UI

One of the service is returning a field with a value like this one below , I want to extract the number '2734427' from the below string using Groovy in SOAP UI
[[https%3a%2f%2fthis.is.a.sample.link%2fproduct-data-v1%2f/jobs/2734427]]
I have used the below lines of codes - which works , but it looks a bit hacky .Was wondering if anyone could suggest a better option.
//Get the value of the Job Id Link
def gtm2joblink = "[[https%3a%2f%2fthis.is.a.sample.link%2fproduct-data-v1%2f/jobs/2734427]]"
// split jobid full link for extracting the actual id
def sub1 = { it.split("jobs/")[1] }
def jobidwithbrackets = sub1(gtm2joblink)
// split jobid full link for extracting the actual id
def sub2 = { it.split("]]")[0] }
def jobid = sub2(jobidwithbracket)
log.info gtm2joblink
Sounds like a job for a regular expression. If the job ID always follows /jobs, and is always numeric, and there are always double brackets ]] at the end, then the following will extract the ID:
import java.util.regex.Matcher
//Get the value of the Job Id Link
def gtm2joblink = "[[https%3a%2f%2fthis.is.a.sample.link%2fproduct-data-v1%2f/jobs/2734427]]"
Matcher regexMatcher = gtm2joblink =~ /(?ix).*\\/jobs\\/([0-9]*)]]/
if (regexMatcher.find()) {
String jobId = regexMatcher.group(1);
log.info(jobId)
} else {
log.info('No job ID found')
}

Checking a value across multiple arrays

I have a context property named 'flights'. I want to check if there is no value for this property, then go to the 'Iteration' test step, else set the first value of the property as a test case property.
Now what I want to do is perform a compare using this test case property value with a couple of arrays. Below is the scenario;
Check if value is in the villas array, if so +1 to VillasCount, else check in hotels array, if in there then +1 to beachCount else +1 to noCount.
Code is below:
// define properties required for the script to run.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath
//Define an empty array list to load data from datasheet
def dataTable_properties = [];
int villasCount = context.getProperty("villasCount")
def lines = new File(dataFolder + "/Test.csv").readLines()
def villas = []
lines.eachWithIndex { line, index ->
if (index) {
def data = line.split(',')*.trim()
if (data[0]) villas << data[0]
}
}
log.info "Villas : ${villas}"
context.setProperty("villasCount", villasCount)
Maybe something like:
for(f in flights){
if(villas.contains(f)){
villasCount = villasCount + 1
}
}
Not 100% sure what you needed to compare, but you could easily expand this to check whatever you wanted.
If this is way off please provide more information on what you were trying to compare.

Resources