Top Groovy Interview Questions and Answers (2024)
What is Groovy?
What is the significance of Groovy?
What is Groovy- Closures?
How to execute PL/SQL function using groovy?
How to use the Notifications Endpoint section of the Jenkins job configuration in a Jenkinsfile using groovy script?
In Groovy, what does groovy.json do?
How to parse json using groovy?
How can we set variables in a Jenkins Groovy multi-line shell script?
How can we access the value of a Shell variable into a Groovy pipeline script?
Q: What is Groovy?
Ans:
Apache Groovy is a scripting language (Java-syntax-compatible) for the Java platform. It has both a static and dynamic language with features same as those of Python, Ruby, and Smalltalk.
Q: What is the significance of Groovy?
Ans:
Here are some of the most compelling reasons to learn and utilise Groovy:
- Simple: Groovy syntax is easy and straightforward. It saves a lot of code and work, allowing the developer to be more productive than if they had to accomplish the same thing in Java.
In Java
for(int i = 0; i < 4; i++) { System.out.println("Welcome TechGeekNext User..." ) }
In Groovy
4.times { println "Welcome TechGeekNext User..." }
- This is one of the reasons why coding has become easier, and ideas like polymorphism and callback patterns have become more accessible.
Checkout our related posts :
Q: What is Groovy- Closures?
Ans:
A groovy closure is a piece of code that has been wrapped around an object. It performs the functions of a method or a function.
def myClosure = {
a,b,c->
y = a+b+c
println y
}
myClosure(1,2,3)
-----------
Output
-----------
6
Parameters can be passed to a closure. The list of identities is separated by commas.
The end of the parameter list is indicated by an arrow (->).
Q: How to execute PL/SQL function using groovy?
Ans:
The call to dbms_output
is the most critical portion.
Without get_lines
, there will be no output.
We call it with (simple) JDBC because it appears that some GroovySQL extensions are required to pass typed ARRAY as an OUT parameter.
Below is the example of how to read the DBMS OUTPUT in JDBC.
def stmt = """begin
dbms_output.enable();
dbms_output.put_line('line 1');
dbms_output.put_line('line 2');
end;"""
sql.execute(stmt)
int arraySize = 100;
def stmt2 = """begin
dbms_output.get_lines(?, ?); /* output array, array size */
end;
"""
def cs = con.prepareCall(stmt2)
cs.registerOutParameter(1, Types.ARRAY, "DBMSOUTPUT_LINESARRAY");
cs.registerOutParameter(2, Types.INTEGER);
cs.setInt(2, arraySize);
cs.execute()
def array = cs.getArray(1);
println array.dump()
array.getArray().each {
println(it)
}
array.free();
cs.close();
Q: Which dependency is needed for using Groovy RestClient?
Ans:
We will need below dependency for using Groovy RestClient in Maven:
<dependency>
<groupId>org.codehaus.groovy.modules.http-builder</groupId>
<artifactId>http-builder</artifactId>
<version>0.7.1</version>
<scope>test</scope>
</dependency>
In Gradle:
testImplementation 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
Above library contains groovyx.net.http.RESTClient
.
Q: How to use the Notifications Endpoint section of the Jenkins job configuration in a Jenkinsfile using groovy script?
Ans:
Can write below code in jenkins pipeline:
pipeline {
// ..
stages {
stage('Notify') {
script {
// global variable in pipeline -> https://opensource.triology.de/jenkins/pipeline-syntax/globals#currentBuild
def build = currentBuild
def targetUrl = "http://some-url?{some-query-params}"
def buildUrl = build.absoluteUrl
def buildNumber = build.number
def buildStatus = build.currentResult
httpRequest url: targetUrl, contentType: 'APPLICATION_JSON', httpMode: 'POST', responseHandle: 'NONE', timeout: 30, requestBody: """
{
"name": "",
"build": {
"full_url": "",
"number": "",
"phase": "FINISHED",
"status": ""
}
}
"""
}
}
Q: In Groovy, what does groovy.json do?
Ans:
Groovy already has built-in support for converting Groovy objects to JSON. The groovy.json
package contains the classes for JSON serialisation and parsing.
Q: How to parse json using groovy?
Ans:
JsonSlurper is a class which parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer, Double, Boolean and String. The class includes a number of overloaded parse methods as well as some unique methods like parseText, parseFile, and others. We'll use the parseText method in the below example. It parses a JSON String and turns it to a list or map of objects in a recursive manner.
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText('{ "name": "Barry Matt" }')
assert object instanceof Map
assert object.name == 'Barry Matt'
JsonSlurper can also convert JSON arrays to lists.
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText('{ "myListExample": [3, 55, 1, 12] }')
assert object instanceof Map
assert object.myListExample instanceof List
assert object.myListExample == [3, 55, 1, 12]
Q: How can we set variables in a Jenkins Groovy multi-line shell script?
Ans:
We will put a '\' on the end of line.
sh script: """\
foo='bar' \
echo $foo \
""", returnStdout: true
Q: How can we access the value of a Shell variable into a Groovy pipeline script?
Ans:
We can utilize a shell step and return the standard out.
pipeline {
agent any
stages {
stage('example') {
steps {
script {
def readVal = sh label: '', returnStdout: true, script: 'echo "READ_VAL_VALUE"'
echo readVal
println readVal
}
}
}
}
}