Retrieve with groovy an Attribute value - groovy

I have the following data on groovy
Binding Variables: [ timing:After Create,
attributes:[LOCK_OUT:Attribute: { NAME:Attribute:
{Name=NAME, Value=[Bob]}, PASSWORD:Attribute:
{Name=PASSWORD,
Value=[org.identityconnectors.common.security.GuardedString#959e062c]}
]]
And I would like to retrieve the value of the password attribute (the GuardedString ) with groovy but I am stuck in the last part.
Until now I did the following:
if (binding.variables != null) {
System.out.println("Binding Variables: "+ binding.variables );
if(binding.variables.containsKey("attributes")){
System.out.println("Got Password binding variable" );
System.out.println (binding.variables.attributes.get("__PASSWORD__")); //here it prints Attribute: {Name=__PASSWORD__, Value=[org.identityconnectors.common.security.GuardedString#3a6f394]}
System.out.println (binding.variables.attributes.get("__PASSWORD__").getAttribute("__PASSWORD__")); //this is not working..
}
}
Can anyone help me? How can I retrieve this value?
Thanks

Related

Substitute values from property file in Jenkinsfile for dynamically set variables

I have a Jenkinsfile with multiple parameters that are environment-specific.
The values for those parameters are stored in a property file. I am trying to set the variables based upon the selected environment and then replace their values from the property files.
Jenkinsfile
ENVIRONMENT is a choice parameter having 2 values: ft, perf and pm as below in my Jenkinsfile
choice (
name: 'ENVIRONMENT',
choices: ['ft', 'perf','pm'],
description: 'please select the environment'
)
PROPERTY_FILE is another choice parameter as below
choice (
name: 'PROPERTY_FILE',
choices: ['jenkins/app.groovy'],
description: 'please select the property file'
)
app.groovy looks like:
Test_perf="Hello"
Test_ft="World"
Test_pm="Welcome"
Stages
stage('Load Environment Property File') {
steps {
script {
//sourcing user selected property file
load "${PROPERTY_FILE}"
def envName = "${PROPERTY_FILE}".tokenize(".")[0]
//it will set build description as description in Jenkins build history
env.envName=envName
currentBuild.description = "Env:${envName}"
}
}
}
//STAGE FOR WHICH I NEED HELP
stage('Set Variables Based upon environment name') {
steps {
script{
if ("${ENVIRONMENT}" == "perf" ){
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "HELLO", i.e.; replacing the variable "${Test_perf}" stuffed inside "var" from the property file. However, since the property file is already loaded, it will not replace the key by its value from the property file.
} else if ("${ENVIRONMENT}" == "ft" ){
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_ft} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "World"
} else {
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "Welcome"
}
}
}
}
Is there a way to further substitute the value from the property file. For e.g.; "${var}" expands to "${Test_pm}" and then "${Test_pm}" gets the value "Welcome" from the property file.
Please help.

Method return wrong type of value in Groovy

I'm working on a groovy method to look for a custom attribute and return the value if the key is found.
The problem is that the method is returning the type of value instead of the value.
// There is more code before, but its not involved with this issue.
def UUIDca = 'UUID'
String customAttributeValue = grabCustomAttribute(UUIDca, event_work)
appendLogfile("\n\nTest grabCustomAttribute: ${customAttributeValue}\n")
}
// Grab the Custom Message Attribute values by name
String grabCustomAttribute (String findElement, OprEvent event){
appendLogfile("""\nIN grabCustomAttribute\nElement to look: ${findElement}\n""")
def firstItem = true
if (event.customAttributes?.customAttributes?.size()) {
event.customAttributes.customAttributes.each { ca ->
// Define each CMA to catch here
appendLogfile("""\nElement: ${ca.name} - """)
appendLogfile("""Valor: ${ca.value}\n""")
if ("${ca.name}" == findElement) {
String customValue = ca.value
appendLogfile("""Custom Attribute Found\n""")
appendLogfile(customValue)
return customValue
}
}
}
}
appendLogfile is basically a print to a log file :)
This is the output I'm getting.
IN grabCustomAttribute Element to look: UUID
Element: UUID - Valor: c3bb9169-0ca3-4bcf-beb1-f94eda8ebf1a
Custom Attribute Found
c3bb9169-0ca3-4bcf-beb1-f94eda8ebf1a
Test grabCustomAttribute: [com.hp.opr.api.ws.model.event.OprCustomAttribute#940e503a]
Instead of returning the value, it returns the type of object. It's correct, but I'm looking for the value.
I believe the solution is really simple, but I'm very new to Groovy.
Any help will be appreciated.
Thanks.
In this case the return statement is for the closure, not for the method, so your method is actually returning the list that "each" is iterating over
The easiest approach you can take here is to use Groovy find method to find the element you are searching for. Something like this:
String grabCustomAttribute (String findElement, OprEvent event) {
return event.customAttributes.customAttributes?.find { ca -> ca.name == findElement }.value
}

Optional parameter in Groovy Script

I have a script that simply does
// TODO: assign default value if not defined
println optionalParameter
When I invoke it using:
new GroovyShell(new Binding([optionalParameter: 'text'])).evaluate(script)
it works fine. But if I run it without a parameter like below:
new GroovyShell().evaluate(script)
it fails with MissingPropertyException.
How can I assign default value for optionalParameter so that I don't get MissingPropertyException?
Adding this code to script works for me:
String value
if (binding.hasVariable('optionalParameter')) {
value = binding.getVariable('optionalParameter')
} else {
value = 'defaultValue'
}
println value

How to avoid MissingPropertyException

If an object does not have a property and I am accessing the property, we get a MissingPropertyException. Can I do something similar to safe null (?.) to guard against missing properties so it doesn't throw an exception?
One option would be:
def result = obj.hasProperty( 'b' ) ? obj.b : null
Which would return null if the object doesn't have the property...
Another would be to add propertyMissing to your class like so:
def propertyMissing( name ) {
null
}
This means that any missing properties would just result in null.
You can also use try/catch
try
{ env.GERRIT_TOPIC=GERRIT_TOPIC
}
catch (e_val)
{ echo 'missing GERRIT_TOPIC'
}

[HMVC??] Call Functions in another controller and get values

I am facing a situation where I need to call a function to check some status.
$lastupdate=Request::factory('user/getlastupdate/'.$userid.'')->execute();
My getlastupdate function looks like this:
public function action_getlastupdate($userid){
$status=array();
try{
$updatestatus= ORM::factory('updates')
->where('id', '=', $userid)
->where('deleted', '=',0)
->find_all();
//check if result returned values
$resultcount=count($updatestatus);
//if result has data
if($resultcount>0){
foreach($updatestatus as $status)
{
$stat="found";
$result= 'Profile Last Updated on'.$updatestatus->lastupdate;
}
}//end if result has data
//if record returned no values
else{
$stat="missing";
$result= 'Profile Data Missing';
}//end if resultcount>0
}//end try
catch(ORM_Validation_Exception $e)
{
$stat="error";
$result="Profile Update Search Error ".$e->errors('updates');
}///end catch
$status['result']=$result;
$status['stat']=$stat;
$this->response->body(View::factory('pages/updatestatus', $status));
}//end function
This works but I do not want to render the view. I want to return the array status and use it from within my controller which is calling this method. How can I implement this? Does the code change if I call from the same controller vis a vis calling from a different controller?
I am using kostache templates so I need to play with the status[values] before rendering final output to my view.
You could send an extra parameter for your subquery which will indicate whether to auto render the view or not.
$lastupdate=Request::factory('user/getlastupdate/'.$userid.'/off')->execute();
and in your action getlastupdate check the parameter
action_getlastupdate($userid, $renderView = '')
{
if( $renderView === 'off' )
{
$this->auto_render = FALSE;
}
[...]
}

Resources