What is the meaning of this script field in Groovy? - groovy

What parameters.script means in the following Groovy code:
example.groovy
class Example {
def call(Map parameters) {
def script = parameters.script
...
}
}

It retrieves a value from a Map with the key 'script'. The following are all equivalent
def script = parameters.script
script = parameters['script']
script = parameters.get('script')

from https://www.timroes.de/2015/06/28/groovy-tutorial-for-java-developers-part3-collections/:
Beside using brackets you can also use dot notation to access entries

Related

Camunda: Use in an external Groovy script a provided Class

I want to use for scripting external Groovy Scripts.
To not copy a lot of code, I want to share classes.
I have:
- external_test.groovy
- Input.groovy
Running the external_test.groovy in Intellij works.
Input is a simple class:
package helpers
class Input {
String serviceConfig
String httpMethod
String path
LinkedHashMap headers = [:]
String payload
Boolean hasResponseJson
}
When the script is executed by Camunda, it cannot find the class:
import helpers.Input
...
And throws an Exception:
unable to resolve class helpers.Input # line 16, column 9. new helpers.Input(serviceConfig: "camundaService", ^ 1 error
It is listed in the Deployment:
Do I miss something or is this not supported?
I found a post in the Camunda forum, that helped me to solve this:
https://forum.camunda.org/t/groovy-files-cant-invoke-methods-in-other-groovy-files-which-are-part-of-same-deployment/7750/5
Here is the solution (that is not really satisfying - as it needs a lot of boilerplate code):
static def getScript(fileName, execution) {
def processDefinitionId = execution.getProcessDefinitionId()
def deploymentId = execution.getProcessEngineServices().getRepositoryService().getProcessDefinition(processDefinitionId).getDeploymentId()
def resource = execution.getProcessEngineServices().getRepositoryService().getResourceAsStream(deploymentId, fileName)
def scannerResource = new Scanner(resource, 'UTF-8')
def resourceAsString = scannerResource.useDelimiter('\\Z').next()
scannerResource.close()
GroovyShell shell = new GroovyShell()
return shell.parse(resourceAsString)
}
def helper = getScript("helpers/helper_classes.groovy", execution)
helper.myFunction("hello")

Find a value in a collection and assign top an variable using groovy

Hello Groovy Experts,
I am using the below command to get all the ODI Dataservers.
def PSchema=DServer.getPhysicalSchemas();
When I print the PSchema variable I getting the following values.
[oracle.odi.domain.topology.OdiPhysicalSchema ABC.X1, oracle.odi.domain.topology.OdiPhysicalSchema ABC.X2]
What I am trying to achieve here I will be passing X1 or X2 during runtime...
And then I want to validate this value with the PSchema result and the print the following value:
oracle.odi.domain.topology.OdiPhysicalSchema ABC.X2
I tried using the following options:
def PSchema44 = PSchema11.findIndexValues { it =~ /(X1)/ }
def pl=PSchema11.collect{if(it.contains ('X1)){return it}}
I tried for loop to check whether values are getting printed properly ..result is fine:
for (item in PSchema11 )
{
println item
}
Assuming 'X1' and 'X2' are the names for the physical schemas, you should be able to do something like this:
def phys = "X1"
def pSchemas = dServer.getPhysicalSchemas()
def schema = pSchemas.find{it.schemaName == phys}
also I guess you are new to Groovy, I suggest you read up on syntax and naming conventions. For example, variable names should always start with a lower case letter

How to make snakeyaml and GStrings work together

When I'm trying to use snakeyaml to dump out Yaml out of Groovy interpolated strings, it ends up printing a class name instead.
For example:
#Grab(group='org.yaml', module='snakeyaml', version='1.16')
import org.yaml.snakeyaml.Yaml
Yaml yaml = new Yaml();
def a = "a"
def list = ["$a"]
def s = yaml.dump(list)
Prints:
- !!org.codehaus.groovy.runtime.GStringImpl
metaClass: !!groovy.lang.MetaClassImpl {}
I'm guessing it has something to do with the fact that GStrings get transformed to Strings when they used and I suspect snakeyaml uses some sort of introspection to determine the class of the object.
Is there a better solution than calling toString() on all GStrings?
Try to create a new Representer :
public class GroovyRepresenter extends Representer {
public GroovyRepresenter() {
this.representers.put(GString.class, new StringRepresenter());
}
}
Yaml yaml = new Yaml(new GroovyRepresenter())
...
You could add type info to your variables
Yaml yaml = new Yaml();
def a = "a"
String aStr = "$a"
def list = [aStr]
def s = yaml.dump(list)

Using a variable to extract value of property of an element in groovy using xmlSlurper

I am using SoapUI to test webservices. The following string (in xml format) is my request:
<Request>
<AC>
<AssetID>1</AssetID>
<Asset_Name>ABC</Asset_Name>
<Asset_Number>1</Asset_Number>
</AC>
<AC>
<AssetID>2</AssetID>
<Asset_Name>XYZ</Asset_Name>
<Asset_Number>2</Asset_Number>
</Ac>
</Request>
I am using the following code in a groovy script to extract value of Asset_Number for each AC (The above xml string is stored in variable strRequest):
def x = new XmlSlurper().parseText("$strRequest")
x.AC.each { AC ->
assetNum = AC."Asset_Number"
<<do something with the assetNum>>
}
However, I wish to parameterize the above code to pick up Asset_Number for various types of assets (e.g. AC, Peripheral etc). The request xml for each asset is in the same format as above. If I replace 'AC' with variable name 'requestName' in above code:
//strRequest = xml request
def requestName //I will pick up value for this from a test case property
def x = new XmlSlurper().parseText("$strRequest")
x.(requestName.toString()).each { requestName ->
assetNum = requestName."Asset_Number"
<<do something with the assetNum>>
}
it shows the following error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script166.groovy: 35: The current scope already contains a variable of the name requestName # line 35, column 2. { ^ org.codehaus.groovy.syntax.SyntaxException: The current scope already contains a variable of the name requestName
I have tried a solution mentioned in another post Using a String as code with Groovy XML Parser, but it doesn't serve my purpose.
Any other ideas?
You can use
x."$requestName".each
Why XmlSlurper? In SoapUI you can use XmlHolder
import com.eviware.soapui.support.XmlHolder
def responseHolder = new XmlHolder(messageExchange.getResponseContentAsXml())
def resultFromResponse = responseHolder["here_is_your_xpath"]
assert someExpectedResult == resultFromResponse
And if you need to iterate via multiple xml nodes
resultFromResponse.each
{
assert result == resultFromResponse
}

Groovy Dynamic arguments

I wonder how is this possible in groovy to start an array from the n element.
Look at the snippet :
static void main(args){
if (args.length < 2){
println "Not enough parameters"
return;
}
def tools = new BoTools(args[0])
def action = args[1]
tools."$action"(*args)
System.exit(1)
}
As you see am doing here a dynamic method invocation. The first 2 arguments are taken as some config and method name , the others I would like to use as method paramerts.
So how can I do something like this :
tools."$action"(*(args+2))
Edited : If not possilbe in native groovy Java syntax will do it :
def newArgs = Arrays.copyOfRange(args,2,args.length);
tools."$action"(*newArgs)
To remove items from the beginning of the args you can use the drop() method. The original args list is not changed:
tools."$action"(*args.drop(2))
Other option, like you are trying is to access from N element:
tools."$action"(*args[2..-1])

Resources