Groovy string comparison in Jenkins pipeline - groovy

I'm trying to compare two strings in Jenkins pipeline. The code more or less look like this:
script {
def str1 = 'test1.domainname-test.com'
def str2 = 'test1.domainname-test.com'
if ( str1 == str2 ) {
currentBuild.result = 'ABORT'
error("TENANT_NAME $TENANT_NAME.domainname-test.com is already defined in domainname-test.com record set. Please specify unique name. Exiting...")
}
}
str1 is fed by a preceeding command I skipped here due to simplicity. I am getting this error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field java.lang.String domainname
What am I doing wrong? I tried equals method too, same result. As if it stucked on those dots, thinking it's some kind of property. Thanks in advance

You're missing curly brackets surrounding the TENANT_NAME variable name. In your example:
error("TENANT_NAME $TENANT_NAME.domainname-test.com is already defined in domainname-test.com record set. Please specify unique name. Exiting...")
the $ sign gets applied to TENANT_NAME.domainname. And because TENANT_NAME is a string, Groovy interprets the following part as you were trying to access domainname property from a String class, and you get No such field found: field java.lang.String domainname exception.
To avoid such problems, wrap your variable name with {} and you will be fine.
error("TENANT_NAME ${TENANT_NAME}.domainname-test.com is already defined in domainname-test.com record set. Please specify unique name. Exiting...")

Related

nodejs skipping single quote from json key in output

I see a very weird problem when json when used in nodejs, it is skipping single quote from revision key . I want to pass this json as input to node request module and since single quote is missing from 'revision' key so it is not taking as valid json input. Could someone help how to retain it so that I can use it. I have tried multiple attempts but not able to get it correct.
What did I try ?
console.log(jsondata)
jsondata = {
'splits': {
'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
Expected :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
But in actual output single quote is missing from revision key :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
revision: 'master'
}
}
Run 2 :- Tried below code this also produce same thing.
data = JSON.stringify(jsondata)
result = JSON.parse(data)
console.log(result)
Run 3:- Used another way to achieve it
jsondata = {}
temp = {}
splits = []
temp['revision'] = 'master',
temp['os-name'] = 'ubuntu'
temp['platform-version'] = 'os'
temp['traffic-percent'] = 100
splits.push(temp)
jsondata['splits'] = splits
console.log(jsondata)
Run 4: tries replacing single quotes to double quotes
Run 5 : Change the order of revision line
This is what is supposed to happen. The quotes are kept only if the object key it’s not a valid JavaScript identifier. In your example, the 'splits' & 'revision' don't have a dash in their name, so they are the only ones with the quotes removed.
You shouldn't receive any error using this object - if you do, update this post mentioning the scenario and the error.
You should note that JSON and JavaScript are not the same things.
JSON is a format where all keys and values are surrounded by double quotes ("key" and "value"). A JSON string is produced by JSON.stringify, and is required by JSON.parse.
A JavaScript object has very similar syntax to the JSON file format, but is more flexible - the values can be surrounded by double quotes or single quotes, and the keys can have no quotes at all as long as they are valid JavaScript identifiers. If the keys have spaces, dashes, or other non-valid characters, then they need to be surrounded by single quotes or double quotes.
If you need your string to be valid JSON, generate it with JSON.stringify. If it's OK for it to be just valid JavaScript, then it's already fine - it does not matter whether the quotes are there or not.
If, for some reason, you need some imaginary third option (perhaps you are interacting with an API where someone has written their own custom string parser, and they are demanding that all keys are surrounded by single quotes?) you will probably need to write your own little string generator.

error with string variable

I'm trying to use a string variable as input to an xml function. When I use this command:
name2_node(i).setTextContent('truck');
there is no error. But when I replace it with:
name2_node(i).setTextContent(type(i,1));
an error occurs like this:
No method 'setTextContent' with matching signature found for class
'org.apache.xerces.dom.ElementImpl'.
The variable type is a string array. In fact when I type type(i,1) in command window the result is:
ans =
string
"truck"
What part am I doing wrong?
Two things:
use a different variable name, type is a built in function which tells you the variable type, hence why it shows "string" in the output.
Then access the cell array of strings with curly braces
vehicletypes = {'car'; 'truck'; 'van'};
name2_node(i).setTextContent(vehicletypes{i,1}); % For i=2, this passes 'truck'

how to get the data in url using groovy code?

i want to get defect id from the url using groovy code (To build custom code in tasktop).
for example: I will have an dynamic url generated say www.xyz.com/abc/defect_123/ now I want to retrieve that letter that always starts from 17th position. and return the string
Please help..
Thanks in advance
Here are two possibilities. Please note that the "substring" option is very strict and will always start from the 16th position (what happens if the domain changes from www.xyz.com to www.xyzw.com?)
def str = 'www.xyz.com/abc/defect_123/';
def pieces = str.tokenize('/'); // prints defect_123
def from16 = str.substring(16); // prints defect_123/
println from16;
println pieces.last();
You should define this as dynamic url in UrlMappings.groovy file:
"www.xyz.com/abc/$defect_id" (controller: 'YourController', action: 'method_name')
and you can access the defect_id variable from YourController using params.defect_id

as3, string to variable

I have array with variable names:
var subjectArray:Array=["subject0","subject1","subject2"];
I need to convert string to var, but following does not work: this[subjectArray[0]] throws an error.
Any thoughts?
That syntax should work. You can check if an object contains a property with a given name with the in keyword. The property does probably not exist.
if (subjectArray[0] in this) {
// do something with this[subjectArray[0]];
}

What do empty square brackets after a variable name mean in Groovy?

I'm fairly new to groovy, looking at some existing code, and I see this:
def timestamp = event.timestamp[]
I don't understand what the empty square brackets are doing on this line. Note that the timestamp being def'd here should receive a long value.
In this code, event is defined somewhere else in our huge code base, so I'm not sure what it is. I thought it was a map, but when I wrote some separate test code using this notation on a map, the square brackets result in an empty value being assigned to timestamp. In the code above, however, the brackets are necessary to get correct (non-null) values.
Some quick Googling didn't help much (hard to search on "[]").
EDIT: Turns out event and event.timestamp are both zero.core.groovysupport.GCAccessor objects, and as the answer below says, the [] must be calling getAt() on these objects and returning a value (in this case, a long).
The square brackets will invoke the underlying getAt(Object) method of that object, so that line is probably invoking that one.
I made a small script:
class A {
def getAt(p) {
println "getAt: $p"
p
}
}
def a = new A()
b = a[]
println b.getClass()
And it returned the value passed as a parameter. In this case, an ArrayList. Maybe that timestamp object has some metaprogramming on it. What does def timestamp contains after running the code?
Also check your groovy version.
Empty list, found this. Somewhat related/possibly helpful question here.
Not at a computer, but that looks like it's calling the method event.timestamp and passing an empty list as a parameter.
The same as:
def timestamp = event.timestamp( [] )

Resources