DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Introduction to JSON With Java
  • Generics in Java and Their Implementation
  • Creating Annotations in Java
  • Java String: A Complete Guide With Examples

Trending

  • Cognitive AI: The Road To AI That Thinks Like a Human Being
  • Send Your Logs to Loki
  • Java Parallel GC Tuning
  • Breaking Down Silos: The Importance of Collaboration in Solution Architecture
  1. DZone
  2. Coding
  3. Languages
  4. Lesson Learned on Groovy

Lesson Learned on Groovy

There are some of the key takeaways which I have encountered during the Jenkins pipeline Integration with API.

EBINEZAR GNANASEKARAN user avatar by
EBINEZAR GNANASEKARAN
·
Sep. 24, 20 · Analysis
Like (7)
Save
Tweet
Share
8.67K Views

Join the DZone community and get the full member experience.

Join For Free

Though I have worked on Java for more than a decade, I have not had a chance to work on Groovy. While working for API Integration into Jenkins CI/CD pipeline, I extensively used Groovy to invoke REST API, validate the user input parameters, and business logic for that. After that, I found that Groovy is a fascinating program language for Java developers.

Why Is Groovy Easy for Java Developers?

It allows to use the Java syntax liberally and tries to be as natural as possible for Java developers. It is an object-oriented dynamic programming language for Java Virtual Machine (JVM) and can be integrated smoothly with any Java Program. The groovy syntax is lucid, familiar, and direct that makes to develop projects faster and easier. It demands a shorter learning curve for Java Developer to develop, test, and integrate to make production-ready code in a short span.

What Is Groovy?

Apache Groovy is a powerful, optionally typed, and dynamic language, with static-typing and static compilation capabilities, and immediately delivers an application with powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.

There are some of the key takeaways which I have encountered during the Jenkins pipeline Integration with API. The key takeaways explained below in the form of questions, answers, program including the output.

1. How To Define the Global Variable in Groovy?

Assign the value to a variable without def to define Global variable.

def comments = 'Emergency build' // It is not accessible inside the display method.

planId = 'IMP2345667' // Since the planId declared without def, hence is considered as a global and accessible inside the display method.

Groovy
 




x


 
1
def display() {
2
println "The Global varible is ${planId}"
3
}
4
//call the display method as below
5
display()


 

Output: 

   The Global variable is IMP2345667

2. How To Interpolate String in Groovy?

 You can use either single quotes or double quotes to declare String.

For Example, You can declare planId as follows.

 def planId='IMP2356790'

 def planId="IMP2356790"

When you print the String by single quote, the String interpolation would not happen. The ${} placeholders printed as it is as shown below.

  println 'The Implementation planId is ${planId}’

Output:

   The Implementation planId is ${planId}

Use double quotes for String Interpolation. Now, the ${} placeholders transformed with planId value as shown below.

 println “The Implementation planId is ${planId}”

Output: 

   The Implementation planId is IMP2356790 

3. How To Check Not Null and Not Empty in Groovy?

The minimal code to check not null and not empty in groovy is to apply "?.trim()" on String as follows.

Groovy
 




xxxxxxxxxx
1
19


 
1
def validateString(String inputField) {
2

          
3
if (!inputField ?.trim()) {
4

          
5
println "The value you entered is -${inputField}. Enter Valid Input of not null and not empty."
6

          
7
return
8

          
9
}
10

          
11
}
12

          
13
//Assign Null value to check the validateString
14

          
15
def planId = null 
16

          
17
 //Call the validateString by passing the pladId to validate the String
18

          
19
validateString(planId)


 The output for validateString is as follows.

The value you entered is -null. Enter Valid Input of not null and not empty.

Note:

To check the Not Null for an object, do not use ?.trim() instead use obj !=null. Use ?.trim() only for Strings not for an object.

4. How to Transform Input Params as a JSON String?

Use a JSON data structure with the JsonBuilder class to transform into JSON data. The hierarchy of ImplementationPlan consists of planId, planStatus, and comments and that is converted to JSON String as shown below. 

Groovy
 




xxxxxxxxxx
1
13


 
1
{
2

          
3
 "ImplemenationPlan":{
4

          
5
 "planId":"IMP2345678",
6

          
7
 "planStatus":"Work in Progress",
8

          
9
 "comments":"Emergency build"
10

          
11
 }
12

          
13
}



Look at the Groovy code for the JSON Transformation using JsonBuilder as below.

Groovy
 




xxxxxxxxxx
1
27


 
1
import groovy.json.JsonBuilder
2

          
3
def planId = "IMP2345678"
4

          
5
def planStatus = "Work in Progress"
6

          
7
def comments = "Emergency build"
8

          
9
println transformToJSON(planId, planStatus, comments)
10

          
11
def transformToJSON(String planId, String planStatus, String comments) 
12

          
13
def jsonBuilder = new JsonBuilder()
14

          
15
jsonBuilder.ImplemenationPlan(
16

          
17
planId: planId,
18

          
19
planStatus: planStatus,
20

          
21
comments: comments
22

          
23
)
24

          
25
return jsonBuilder.toString()
26

          
27
}



The Output of transformJSON is as follows.

{"ImplemenationPlan":{"planId":"IMP2345678","planStatus":"Work in Progress","comments":"Emergency build"}} 

5. How to Convert Object to JSON in Groovy?

Use the JsonBuilder to transform the Object to JSON String in groovy as described below.

Groovy
 




xxxxxxxxxx
1
66


 
1
import groovy.json.JsonBuilder
2

          
3
class ImplementationPlan {
4

          
5
String planId
6

          
7
String planStatus
8

          
9
String createdBy
10

          
11
String dateOfInitiation
12

          
13
String comments
14

          
15
String leadName
16

          
17
String managerName
18

          
19
String implementationDate
20

          
21
String systemForInitiation
22

          
23

          
24

          
25
ImplementationPlan(String planId,
26

          
27
String planStatus,
28

          
29
String createdBy,
30

          
31
String dateOfInitiation,
32

          
33
String comments,
34

          
35
String leadName,
36

          
37
String managerName,
38

          
39
String implementationDate,
40

          
41
String systemForInitiation) {
42

          
43
this.planId = planId
44

          
45
this.planStatus = planStatus
46

          
47
this.createdBy = createdBy
48

          
49
this.dateOfInitiation = dateOfInitiation
50

          
51
this.comments = comments
52

          
53
this.leadName = leadName
54

          
55
this.managerName = managerName
56

          
57
this.implementationDate = implementationDate
58

          
59
this.systemForInitiation = systemForInitiation
60

          
61
}
62

          
63

          
64

          
65
}
66

          



def implementationPlan = new ImplementationPlan('IMP2345679', 'Work in Progress', 'KevinMatthew', '2020-09-20', 'Emergency Build', 'Benny Benjamin', 'Merryln Fedora', '2020-10-01', 'wsp')

println new JsonBuilder(implementationPlan).toPrettyString()


The Output for the above code would be:

Groovy
 




xxxxxxxxxx
1
21


 
1
{
2

          
3
    "leadName": "Benny Benjamin",
4

          
5
    "comments": "Emergency Build",
6

          
7
    "planStatus": "Work in Progress",
8

          
9
    "planId": "IMP2345679",
10

          
11
    "dateOfInitiation": "2020-09-20",
12

          
13
    "createdBy": "KevinMatthew",
14

          
15
    "managerName": "Merryln Fedora",
16

          
17
    "implementationDate": "2020-10-01",
18

          
19
    "systemForInitiation": "wsp"
20

          
21
}


  

6. How to Customize JSON Output to Exclude Null and Particular Fields?

Let us say that I do not want to get printed the null values and Fields such as leadName,managerName, and createdBy. To achieve this, use JsonGenerator to excludeNulls and excludeFieldsByName as described below code.

Groovy
 




xxxxxxxxxx
1
70


 
1
import groovy.json.JsonGenerator
2

          
3
import groovy.json.JsonGenerator.Converter
4

          
5

          
6

          
7
class ImplementationPlan {
8

          
9
String planId
10

          
11
String planStatus
12

          
13
String createdBy
14

          
15
String dateOfInitiation
16

          
17
String comments
18

          
19
String leadName
20

          
21
String managerName
22

          
23
String implementationDate
24

          
25
String systemForInitiation
26

          
27

          
28

          
29
ImplementationPlan(String planId,
30

          
31
String planStatus,
32

          
33
String createdBy,
34

          
35
String dateOfInitiation,
36

          
37
String comments,
38

          
39
String leadName,
40

          
41
String managerName,
42

          
43
String implementationDate,
44

          
45
String systemForInitiation) {
46

          
47
this.planId = planId
48

          
49
this.planStatus = planStatus
50

          
51
this.createdBy = createdBy
52

          
53
this.dateOfInitiation = dateOfInitiation
54

          
55
this.comments = comments
56

          
57
this.leadName = leadName
58

          
59
this.managerName = managerName
60

          
61
this.implementationDate = implementationDate
62

          
63
this.systemForInitiation = systemForInitiation
64

          
65
}
66

          
67

          
68

          
69
}
70

          



def implementationPlan = new ImplementationPlan('IMP2345679', 'Work in Progress', 'KevinMatthew', '2020-09-20', null, 'Benny Benjamin', 'Merryln Fedora', '2020-10-01', null)

def jsonOutputDefault = new JsonGenerator.Options().build()


Groovy
 




xxxxxxxxxx
1
23


 
1
// Print all by default
2

          
3
def jsonResult = jsonOutputDefault.toJson(implementationPlan)
4

          
5

          
6

          
7
println "Default JSON output include null and all Fields - ${jsonResult }"
8

          
9

          
10

          
11
// Exlude null ,leadName,managerName, and createdBy
12

          
13
def jsonOutput =
14

          
15
new JsonGenerator.Options()
16

          
17
 .excludeNulls().excludeFieldsByName('leadName').excludeFieldsByName('managerName').excludeFieldsByName('createdBy').build()
18

          
19

          
20

          
21
def jsonCustomizedResult = jsonOutput.toJson(implementationPlan)
22

          
23
println "The customizing output after exclude null and fields - ${jsonCustomizedResult}"



The output for the above Groovy code would be

Default JSON output include null and all Fields –

Groovy
 




xxxxxxxxxx
1


 
1
 {"leadName":"Benny Benjamin","comments":null,"planStatus":"Work in Progress","planId":"IMP2345679","dateOfInitiation":"2020-09-20","createdBy":"KevinMatthew","managerName":"Merryln Fedora","implementationDate":"2020-10-01","systemForInitiation":null}
2

          


 

The customizing output after exclude null and fields - {"planStatus":"Work in Progress","planId":"IMP2345679","dateOfInitiation":"2020-09-20","implementationDate":"2020-10-01"}

7. How to Parse the String and Convert Into Corresponding Objects?

When you make a REST API call, you will get the JSON text as an output. Let say you that want to retrieve the specific field from the JSON text, you no longer needed to search from the JSON response to fetch from it. Groovy comes to rescue for JSON text parsing by JsonSlurper andJsonSlurperClassic that parses JSON text or reader content and recursively converts into objects(Such as maps, lists, and object of class type). 

For Example, you have JSON text of planId, planStatus, createdBy, and more fields, but response populated with planId, and planStatus. So, use JsonSlurper andJsonSlurperClassic to parse JSON text , convert them into an object, and fetch the particular field from that object.

Note: It is prudent to use JsonSlurperClassic rather than JsonSlurper to come out from Jenkins pipeline Error -"NotSerializableException: groovy.json.internal.LazyMap"

Groovy
 




xxxxxxxxxx
1
96


 
1
import groovy.json.JsonBuilder
2

          
3
import groovy.json.JsonSlurperClassic
4

          
5
public class ImplementationPlan {
6

          
7
String planId
8

          
9
String planStatus
10

          
11
String createdBy
12

          
13
String dateOfInitiation
14

          
15
String comments
16

          
17
String leadName
18

          
19
String managerName
20

          
21
String implementationDate
22

          
23
String systemForInitiation
24

          
25
ImplementationPlan() {}
26

          
27
ImplementationPlan(String planId,
28

          
29
String planStatus,
30

          
31
String createdBy,
32

          
33
String dateOfInitiation,
34

          
35
String comments,
36

          
37
String leadName,
38

          
39
String managerName,
40

          
41
String implementationDate,
42

          
43
String systemForInitiation) {
44

          
45
this.planId = planId
46

          
47
this.planStatus = planStatus
48

          
49
this.createdBy = createdBy
50

          
51
this.dateOfInitiation = dateOfInitiation
52

          
53
this.comments = comments
54

          
55
this.leadName = leadName
56

          
57
this.managerName = managerName
58

          
59
this.implementationDate = implementationDate
60

          
61
this.systemForInitiation = systemForInitiation
62

          
63
}
64

          
65

          
66

          
67
}
68

          
69

          
70

          
71

          
72

          
73
//JSON slurper that parses text and convert into corresponding Object type
74

          
75
def parseJSON(String planData) {
76

          
77
def slurper = new JsonSlurperClassic()
78

          
79
def obj = slurper.parseText(planData)
80

          
81
return obj
82

          
83

          
84
}
85

          
86
def implementationPlan = new ImplementationPlan('IMP2345679', 'Work in Progress', 'KevinMatthew', '2020-09-20', 'Emergency Build', 'Benny Benjamin', 'Merryln Fedora', '2020-10-01', 'wsp')
87

          
88
String planData = new JsonBuilder(implementationPlan).toString()
89

          
90
ImplementationPlan result = parseJSON(planData)
91

          
92
println "planId is ${result.planId } planStatus is ${result.planStatus}"
93

          
94
The output of above code would be
95

          
96
planId is IMP2345679 planStatus is Work in Progress


 

8. Why Should You Annotate @NonCPS for Groovy Methods? 

When you use JsonObject, JsonSlurper, and JsonSlurperClassic into Jenkins pipeline, you will come across "org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException" 

When you run the pipeline scripts, the scripts are executed in sandbox security by default.

 The sandbox security executes the scripts with the Common Serializable Types(Such as All primitive types, Strings, ArrayLists and normal Groovy Lists, Sets: HashSet, Maps: normal Groovy Map, HashMap, TreeMap..etc) without any RejectedAccessException.

 When your scripts consist of Common non-Serializable Types such as Regex Matchers or JsonObject, JsonSlurper, and JsonSlurperClassic, always annotate your method with @NonCPS to come out of RejectedAccessException Error.

For Example, annotate your method with @NonCPS as follows.

Groovy
 




xxxxxxxxxx
1
20


 
1
import groovy.json.JsonSlurperClassic
2

          
3
import com.cloudbees.groovy.cps.NonCPS
4

          
5
 
6

          
7
@NonCPS
8

          
9
def parsePayLoad(String planStatus) {
10

          
11
 def slurper = new JsonSlurperClassic()
12

          
13
 def obj = slurper.parseText(planStatus)
14

          
15
 
16

          
17
 return obj
18

          
19
}
20

          


 

Note:

Continuation-passing(CPS) style is code execution in the form of a continuation that allows executing Serializable types without blocking to pass control onto a continuation.

9. Points to Ponder

Groovy statements need not be terminated with a semicolon.

If you want to return any data type or object, declare the Method with "def" that means it can return anything-regardless of the data type you return for a Method. The below processRecharge Method will return either a string or boolean depends on the parameter passed as below.

Groovy
 




xxxxxxxxxx
1
17


 
1
def processRecharge(String status) {
2

          
3
 if (status?.trim() && status.equalsIgnoreCase('success')) {
4

          
5
 return "Your Mobile Number is eligible for recharge "
6

          
7
 } else {
8

          
9
 return false
10

          
11
 }
12

          
13
}
14

          
15
println processRecharge('success') //This returns the String value
16

          
17
println processRecharge() //This returns boolean


 

If you do not know the data type, define with "def ". The keyword " def " defines an untyped variable or a function in Groovy, as it is an optionally-typed language.

When writing your beans in Groovy, often called POGOs (Plain Old Groovy Objects), you don’t have to create the field and getter/setter yourself, but let the Groovy compiler do it for you.

By default, Groovy considers classes and methods public. So you don’t have to use the public modifier everywhere something is public. Only if it’s not public, you should put a visibility modifier.

10. Conclusion 

Groovy is a scripting language with Java-like syntax for the Java platform. You can play around the Groovy scripts with online web consoles such as https://groovyconsole.appspot.com/ and https://www.tutorialspoint.com/execute_groovy_online.php. Please refer to the Groovy code to explore more from GitHub — https://github.com/ebinezargnan/Groovy-Code.git.

Groovy (programming language) Data Types JSON Strings code style Java (programming language) Object (computer science) Data structure

Opinions expressed by DZone contributors are their own.

Related

  • Introduction to JSON With Java
  • Generics in Java and Their Implementation
  • Creating Annotations in Java
  • Java String: A Complete Guide With Examples

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: