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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Connect to Splunk Through Anypoint Studio in 10 Steps
  • Effective Java Collection Framework: Best Practices and Tips
  • How To Create a Stub in 5 Minutes
  • How To Validate Names Using Java

Trending

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • My LLM Journey as a Software Engineer Exploring a New Domain
  1. DZone
  2. Coding
  3. Languages
  4. Implement a Counter in Dataweave 2.x and Above

Implement a Counter in Dataweave 2.x and Above

In this article, see how to implement a counter in DataWeave.

By 
Rahul Kumar user avatar
Rahul Kumar
·
Dec. 11, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
21.8K Views

Join the DZone community and get the full member experience.

Join For Free

Implement a Counter in Dataweave

These days, I see quite a few posts that require using Counter in DataWeave. The problem faced is that users require a Sequence Number that is consistent throughout the different sections of data. Consider the below JSON:

JSON
 




xxxxxxxxxx
1
17


 
1
[{
2
"Item" : "ItemXYZ",
3
  "SequenceNo" : 1,
4
  "Parts": [
5
{ "Part" : "A1", "SequenceNo" : 2 }, { "Part" : "B1", "SequenceNo" : 3 },
6
{ "Part" : "A2", "SequenceNo" : 4 }, { "Part" : "B2", "SequenceNo" : 5 }
7
  ]
8
},
9
 {
10
"Item" : "ItemRTY",
11
  "SequenceNo" : 6,
12
  "Parts": [
13
{ "Part" : "A1", "SequenceNo" : 7 }, { "Part" : "B1", "SequenceNo" : 8 },
14
{ "Part" : "A2", "SequenceNo" : 9 }, { "Part" : "B2", "SequenceNo" : 10 }
15
  ]
16
}
17
]



As you can see here, we have "SequenceNo," which increases every time, irrespective of the structure of JSON. If we have to add a SequenceNo in any data, we have limited options. There are workarounds like using a recursive function or calculating the counters using Complex logic to achieve a counter, but it hampers the performance. DataWeave is developed for transformations mostly, and it doesn't have built-in counters, which would save its last stored value throughout the execution.

So I have come up with a DataWeave solution that uses the Java Module. Java Module comes with an Invoke function for DataWeave, which I will be using in DataWeave. To include Java Module, add the below dependency in the pom.xml:

XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
  <groupId>org.mule.module</groupId>
3
  <artifactId>mule-java-module</artifactId>
4
  <version>1.2.5</version> <!-- or newer -->
5
  <classifier>mule-plugin</classifier>
6
</dependency>



We will use AtomicInteger for this example. Since it comes with a built-in increment function and is present under Java Util package, there is no need to add any extra dependencies. You can use any other implementation as well, but you would need to add a utility class and a function to use it inside the DataWeave.

Below is a simple usage example:

Java
 




xxxxxxxxxx
1
20


 
1
%dw 2.0
2
import java!java::util::concurrent::atomic::AtomicInteger
3
var counter = AtomicInteger::new(0)
4
fun increment() = Java::invoke('java.util.concurrent.atomic.AtomicInteger', 'incrementAndGet()', counter, {})
5
output application/json
6
---
7
{
8
"field1" : "Field1Value",
9
"SNo" : increment(),
10
"Attributes" : {
11
"Field1" : "Field1Value",
12
"Field2" : "Field2Value",
13
"SNo" : increment(),
14
"Attributes" : {
15
"Field1" : "Field1Value",
16
"Field2" : "Field2Value",
17
"SNo" : increment()
18
}
19
}
20
}



This will produce an output like below:;

Image title

Used a counter variable to create an Instance of AtomicInteger and initialized to 0, increment() function will use Java invoke to increment the counter DataWeave variable. So we can use the increment() function anywhere without worrying about any other logic independently.

Below is another usage example:

Java
 




xxxxxxxxxx
1
23


 
1
%dw 2.0
2
import java!java::util::concurrent::atomic::AtomicInteger
3
var counter = AtomicInteger::new(0)
4
fun increment() = Java::invoke('java.util.concurrent.atomic.AtomicInteger', 'incrementAndGet()', counter, {})
5
output application/json
6
---
7
[{
8
"Item" : "ItemXYZ",
9
  "SNo" : increment(),
10
  "Parts": [
11
{ "Part" : "A1", "SNo" : increment() }, { "Part" : "B1", "SNo" : increment() },
12
{ "Part" : "A2", "SNo" : increment() }, { "Part" : "B2", "SNo" : increment() }
13
  ]
14
},
15
 {
16
"Item" : "ItemRTY",
17
  "SNo" : increment(),
18
  "Parts": [
19
{ "Part" : "A1", "SNo" : increment() }, { "Part" : "B1", "SNo" : increment() },
20
{ "Part" : "A2", "SNo" : increment() }, { "Part" : "B2", "SNo" : increment() }
21
  ]
22
}
23
]



Using the above script, we will get an output like below:

Image title

I will come up with some more utilities in the next post.

Stay tuned!

Further Reading

Mule 4 DataWeave Functions: Part 1

DataWeave 1.0 to DataWeave 2.0 Migration – Part 1

Java (programming language) JSON Data (computing) POST (HTTP) Dependency Execution (computing) XML Workaround Implementation

Opinions expressed by DZone contributors are their own.

Related

  • How to Connect to Splunk Through Anypoint Studio in 10 Steps
  • Effective Java Collection Framework: Best Practices and Tips
  • How To Create a Stub in 5 Minutes
  • How To Validate Names Using Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!