Different results when setting/getting System properties with GStrings in Groovy - groovy

I'm perplexed by Groovy's behavior here. I've run through the debugger some to try to determine where in the dynamic mixins these code paths may be getting crossed but wondered if anyone could set me straight here.
Basically, in setting a system property with a GString for a value, depending on how I set the property, the property is not always readable back via certain methods.
I have seen Why Map does not work for GString in Groovy? and Why groovy does not see some values in dictionary? but my question specifically applies to map values so not sure those apply or not?
Snippet :
def tdollar='dollar'
System.setProperty('key1', 'value1')
System.setProperty('key2', "value2$tdollar")
// Replace the below with any property setting method other than
// the above with the same results
System.properties['key4']='value4'
System.properties['key5']="value5$tdollar"
println System.hasProperty('key1')
println System.hasProperty('key2')
println System.hasProperty('key4')
println System.hasProperty('key5')
println
println System.getProperty('key1')
println System.getProperty('key2')
println System.getProperty('key4')
println System.getProperty('key5')
println
println System.properties.keySet()
println
println System.properties['key1']
println System.properties['key2']
println System.properties['key4']
println System.properties['key5']
Output:
null
null
null
null
value1
value2dollar
value4
null
[java.runtime.name, sun.boot.library.path, java.vm.version, gopherProxySet, java.vm.vendor, java.vendor.url, path.separator, java.vm.name, file.encoding.pkg, user.country, sun.java.launcher, sun.os.patch.level, program.name, key5, key4, java.vm.specification.name, user.dir, key2, java.runtime.version, key1, java.awt.graphicsenv, java.endorsed.dirs, os.arch, java.io.tmpdir, line.separator, java.vm.specification.vendor, os.name, tools.jar, sun.jnu.encoding, script.name, java.library.path, java.specification.name, java.class.version, sun.management.compiler, os.version, user.home, user.timezone, java.awt.printerjob, file.encoding, java.specification.version, java.class.path, user.name, java.vm.specification.version, sun.java.command, java.home, sun.arch.data.model, user.language, java.specification.vendor, awt.toolkit, java.vm.info, java.version, java.ext.dirs, sun.boot.class.path, java.vendor, file.separator, java.vendor.url.bug, sun.io.unicode.encoding, sun.cpu.endian, groovy.starter.conf, groovy.home, sun.cpu.isalist]
value1
value2dollar
value4
value5dollar
Why, if I don't use System.setProperty(key, value) syntax, is the property not readable via System.getProperty(key), but is still readable via any other method?
Given this behavior, is there a best practice documented regarding System properties in Groovy.
Writing this, I wonder if this is just a general map question. Will test.

System.setProperty('key2', "value2$tdollar")
When you operate using this above method, the second argument is implicitly cast to a String from a GString
System.properties['key5']="value5$tdollar"
this use the underlying setProperties method in the System class (not setProperty), and hence gets resolved differently, causing issues. The GString might not be getting cast correctly or not getting converted to a string before being sent to the underlying java class. If you change the value from a GString to a string like this:
System.properties['key5']="value5" + tdollar
the issue disappears

Related

Is it possible to get the name of variable in Groovy?

I would like to know if it is possible to retrieve the name of a variable.
For example if I have a method:
def printSomething(def something){
//instead of having the literal String something, I want to be able to use the name of the variable that was passed
println('something is: ' + something)
}
If I call this method as follows:
def ordinary = 58
printSomething(ordinary)
I want to get:
ordinary is 58
On the other hand if I call this method like this:
def extraOrdinary = 67
printSomething(extraOrdinary)
I want to get:
extraOrdinary is 67
Edit
I need the variable name because I have this snippet of code which runs before each TestSuite in Katalon Studio, basically it gives you the flexibility of passing GlobalVariables using a katalon.features file. The idea is from: kazurayam/KatalonPropertiesDemo
#BeforeTestSuite
def sampleBeforeTestSuite(TestSuiteContext testSuiteContext) {
KatalonProperties props = new KatalonProperties()
// get appropriate value for GlobalVariable.hostname loaded from katalon.properties files
WebUI.comment(">>> GlobalVariable.G_Url default value: \'${GlobalVariable.G_Url}\'");
//gets the internal value of GlobalVariable.G_Url, if it's empty then use the one from katalon.features file
String preferedHostname = props.getProperty('GlobalVariable.G_Url')
if (preferedHostname != null) {
GlobalVariable.G_Url = preferedHostname;
WebUI.comment(">>> GlobalVariable.G_Url new value: \'${preferedHostname}\'");
} else {
WebUI.comment(">>> GlobalVariable.G_Url stays unchanged");
}
//doing the same for other variables is a lot of duplicate code
}
Now this only handles 1 variable value, if I do this for say 20 variables, that is a lot of duplicate code, so I wanted to create a helper function:
def setProperty(KatalonProperties props, GlobalVariable var){
WebUI.comment(">>> " + var.getName()" + default value: \'${var}\'");
//gets the internal value of var, if it's null then use the one from katalon.features file
GlobalVariable preferedVar = props.getProperty(var.getName())
if (preferedVar != null) {
var = preferedVar;
WebUI.comment(">>> " + var.getName() + " new value: \'${preferedVar}\'");
} else {
WebUI.comment(">>> " + var.getName() + " stays unchanged");
}
}
Here I just put var.getName() to explain what I am looking for, that is just a method I assume.
Yes, this is possible with ASTTransformations or with Macros (Groovy 2.5+).
I currently don't have a proper dev environment, but here are some pointers:
Not that both options are not trivial, are not what I would recommend a Groovy novice and you'll have to do some research. If I remember correctly either option requires a separate build/project from your calling code to work reliable. Also either of them might give you obscure and hard to debug compile time errors, for example when your code expects a variable as parameter but a literal or a method call is passed. So: there be dragons. That being said: I have worked a lot with these things and they can be really fun ;)
Groovy Documentation for Macros
If you are on Groovy 2.5+ you can use Macros. For your use-case take a look at the #Macro methods section. Your Method will have two parameters: MacroContext macroContext, MethodCallExpression callExpression the latter being the interesting one. The MethodCallExpression has the getArguments()-Methods, which allows you to access the Abstract Syntax Tree Nodes that where passed to the method as parameter. In your case that should be a VariableExpression which has the getName() method to give you the name that you're looking for.
Developing AST transformations
This is the more complicated version. You'll still get to the same VariableExpression as with the Macro-Method, but it'll be tedious to get there as you'll have to identify the correct MethodCallExpression yourself. You start from a ClassNode and work your way to the VariableExpression yourself. I would recommend to use a local transformation and create an Annotation. But identifying the correct MethodCallExpression is not trivial.
no. it's not possible.
however think about using map as a parameter and passing name and value of the property:
def printSomething(Map m){
println m
}
printSomething(ordinary:58)
printSomething(extraOrdinary:67)
printSomething(ordinary:11,extraOrdinary:22)
this will output
[ordinary:58]
[extraOrdinary:67]
[ordinary:11, extraOrdinary:22]

Is there some way of using the safe null operator for an object that doesn't exist?

Is there something like "?" that can return null or false if an object doesn't exist.
This throws an error:
println doesntExist['sdfsd'​]​
This doesn't work but is there a way to use "?" somehow to get a boolean?
println doesntExist?['sdfsd'​]​
println doesntExist['sdfsd'​]​?
println ?doesntExist['sdfsd'​]​
Is there a groovyier way to do this:
if (doesntExist && doesntExist['sdfsd'​]​ ){}
You can use get() or getAt() method which is equivalent of array index access operator:
def doesntExist = null
println doesntExist?.getAt('sdfsd')
println doesntExist?.get('sdfsd')
Output:
null
null
Explanation
If you compile the code containing:
doesntExist['sdfsd']
and open its decompiled version (e.g. in IntelliJ IDEA) you will see that this part compiles to
DefaultGroovyMethods.getAt(doesntExist, "sdfsd")
That is why if you want to use null safe operator you have to call
doesntExist?.getAt('sdfsd')
directly.

Parameterizing Objects in spock

I have a problem with parameterizations of list of object by using spock where block. It seems the ListInput value is not taking from the where clause and always coming null value. I have verified the same feature for string and other primitive types and it is working fine.
Does Spock support parameterizations objects ? If yes what is the issue here .
def "check Param Of List of Objects"()
{
expect:
def a= hasflag(ListInput);
a== flag
where:
ListInput | flag
BOList1 | true
BOList2 | false
}
Here the type of BOList1 is an java ArrayList contains the object
You haven't really provided enough information for a definitive answer but I'll try to help.
The where block isn't exactly just a block of code, it's more like a number of parameters passed to a method. It can do a lot, but sometimes you need to pass your code a little differently.
Of note:
- Void methods aren't allowed (but you can get around this using .with{} )
- An iterative parameter cannot also be a derived parameter (constructed from other parameters)
- If you're referencing class level variables (defined within the class but outside this test) they need to be given the #Shared annotation for your tests to have access.
Given more information about where your lists are coming from will help me give better advice.
Final tip; explicitly typecast your parameters to see if that gives you anymore information
def "check Param Of List of Objects"(ArrayList listInput, boolean flag) {
expect:
flag == hasflag(ListInput);
where:
listInput | flag
BOList1 | true
BOList2 | false
}

This code looks like, groovy will result in bad performance? Is it so?

I have been reading Groovy for a month or so. Recently i have came across the following code:
class MyBean implements Serializable {
def untyped
String typed
def item1, item2
def assigned = 'default value'
}
And when I do this :
def bean = new MyBean()
assert 'default value' == bean.getAssigned()
However the above code makes GroovyBeans very very impressive, but still my question is this:
Even though we haven't created the getter function(getAssigned()), groovy does for us. So is that groovy produce this for all class's even though we are not intended to work in GRoovyBeans? This means that for all class's it creates the setter and getter, even though we wont want? Is this is not the performance issue? Or else my view is worng?
Adding a method to a class won't cause a performance issue, as it doesn't have to be called.
If you want direct access to the property, you can use the Java field operator:
bean.#assigned

Can I redefine String#length?

I'd like to re-implement a method of a Java class. For example, for "hi".length() to return 4. (How) Can I do that?
I know using SomeClass.metaClass I can get a reference to an existing method and define new (or overriding) method, but I can't seem to be able to do that for existing Java methods.
Using Groovy, you can replace any method (even those of final classes) with your own implementation. Method replacement in Groovy uses the meta-object protocol, not inheritance.
Here's the example you requested, i.e. how to make String.length() always return 4
// Redefine the method
String.metaClass.invokeMethod = { name, args ->
def metaMethod = delegate.metaClass.getMetaMethod(name, args)
def result = metaMethod.invoke(delegate, args)
name == 'length' ? 4 : result
}
// Test it
assert "i_do_not_have_4_chars".length() == 4
Seems like it could be possible by abusing String metaClass. But the attempt I've done so far in groovy console didn't led to the expected result :
def oldLength = String.metaClass.length
String.metaClass.length = { ->
return oldLength+10;
}
println "hi".length()
outputs the sad 2
I think you could take a look at Proxy MetaClass or Delegating metaClass.
If you did redefine it, it would only work in Groovy code. Groovy can't change the way Java code executes.
In Groovy, "hi".length() is roughly equivalent to this Java:
stringMetaClass.invokeMethod("hi","length");
Because Groovy doesn't actually call length directly, metaClass tricks work in Groovy code. But Java doesn't know about MetaClasses, so there is no way to make this work.
Although this question is very old I like to point out another way (at least for newer Groovy versions) .
The length() method in java.lang.String is implemented from java.lang.CharSequence interface. In order to reimplement the method using the String-metaClass you need to "override" the method in the metaClass of the interface first.
CharSequence.metaClass.length = { -> -1}
String.metaClass.length = { -> 4 }
assert "i_do_not_have_4_chars".length() == 4
The solution using String.metaClass.invokeMethod changes the behaviour of all String-methods and is problematic. For instance, simply invoking "asdf".size() leads to an exception on my setup.

Resources