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

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

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

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

  • Building Hybrid Multi-Cloud Event Mesh With Apache Camel and Kubernetes
  • Streamlining Event Data in Event-Driven Ansible
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • APIs for Logistics Orchestration: Designing for Compliance, Exceptions, and Edge Cases

Trending

  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • AI, ML, and Data Science: Shaping the Future of Automation
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  1. DZone
  2. Coding
  3. Frameworks
  4. Event Notifier in Apache Camel Route

Event Notifier in Apache Camel Route

Apache Camel is an open-source, lightweight integration library. In this article, I will demonstrate the concept of events it allows and how to use them.

By 
Rogerio Santos user avatar
Rogerio Santos
·
Updated Feb. 19, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.1K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

Each step of an Apache Camel Application triggers an event that allows us to read or edit data while the message travels on the "Route." The provided mechanism to access these events is the EventNotifierSupport class.

Apache Camel's route is a sequence of steps, executed in order by Camel, that consumes and processes a message. The initial point of this sequence is represented by the method from(). A route may have many processing components that modify a message or send it to an endpoint. 

To send a message to an endpoint, we use the method to(), so the basic structure of an Apache Camel Route will be:

basic structure of an Apache Camel Route

Between two points, like a from()-> to() or to() -> to(), many other steps occur that we cannot avoid. We call these steps "events."

Events are essential for us because we can interact with them to enrich our application's behavior.

Interaction with events

Interaction With Events

To capture events in Apache Camel, we need to create a class that extends the abstract class EventNotifierSupport. In this class, we will specify a method called isEnabled to activate the event capture.

In the example below, there are two methods: the method isEnable tells Apache Camel that we will capture the events. If the isEnabled method returns true, the notify method receives the event, and then we can interact with them.

Java
 




xxxxxxxxxx
1
17


 
1
@Component
2
public class CamelEvents extends EventNotifierSupport {
3
    
4
    private Integer eventSequence = 1;
5
    
6
    @Override
7
    public void notify(EventObject event) throws Exception {
8
        
9
    }   
10

          
11
    @Override
12
    public boolean isEnabled(EventObject event) {       
13
        return true;
14
    }
15

          
16
}



The notify method receives an object of type EventObject that contains the event that occurred at the moment. We can verify what event was started by checking the instance of the object.

Java
 




xxxxxxxxxx
1


 
1
@Override
2
public void notify(EventObject event) throws Exception {
3
        
4
    if (event instanceof ExchangeCreatedEvent) {    
5
    
6
        ... 
7
    } 
8
    
9
...     



After capturing the event, we can interact with it to read or edit data in the message trafficked on the route. For example, we can implement an automatic log of all content trafficked on the route at each stage, or we can apply rules to validate the data or enrich it.

We can make life easier for developers by creating generic components that remove the need to develop repetitive or common block codes.

I posted an event capture example on GitHub.  Inspect the class com.consulting.fuse.poc.event.CamelEvents.java and notice the notify method capturing a lot of events.

Also notice the below route:

Java
 




xxxxxxxxxx
1


 
1
from("file:trigger/?fileName=test-a.txt&noop=false")
2
.routeId("route-a")     
3
.to("bean:processorA")          
4
.log("### :: The step to(\"bean:processorA\") was executed")



This route reads a file called "test-a.txt" in a specific folder and sends the content to a process named processorA using the to() method.

In this flow, the following events occur in sequence:

  1. ExchangeCreatedEvent
  2. ExchangeSendingEvent
  3. ExchangeSentEvent
  4. ExchangeCompletedEvent

When the route is executing, each event is sent to the Event Notifies implementation in the class CamelEvents.

In this example, we printed each event in the log with the sequence number of execution.

Print of each event in a log with the sequence number of execution

Exchange completed event

In each event, we can manipulate or only get the values of Exchange to use. The following block changes the content received from the file for an upper case value-added the prefix "EDITED:"

So if we include other steps in our route, the trafficked content will always be in capital letters. The programmer doesn't need to worry about it because the event does it for all routes.

Java
 




x
12


 
1
if (event instanceof ExchangeSentEvent) {   
2
            
3
    String body = ((ExchangeSentEvent) event).getExchange().getIn().getBody(String.class);
4
            
5
    body = "EDITED: " + body.toUpperCase();         
6
    ((ExchangeSentEvent) event).getExchange().getIn().setBody(body);
7
            
8
    LOGGER.info("### [EVENT] ExchangeSentEvent executed " + eventSequence + " :: Body content edited to UPPERCASE");
9

          
10
}



Something important to say is that Exceptions also launch events. Take, for example, the route-non-handled-exception route that exists in our sample. When we force an Exception, an event called ExchangeFailedEvent occurs regardless of whether we treat or not the Exception.

Java
 




xxxxxxxxxx
1
12


 
1
from("file:trigger/?fileName=test-b.txt&noop=false&moveFailed=failed")
2
    .routeId("route-non-handled-exception")
3
    .process(new Processor() {
4

          
5
     @Override
6
      public void process(Exchange exchange) throws Exception {         
7
         if (null == exchange.getIn().getHeader("fooHeader")) {             
8
        throw new NonHandledException("Exception throwed to test");                   }         
9
       }
10
                })
11
    .log("NonHandledException occur ")



ExchangeFailedEvent

Conclusion

Events are potent resources on our routes. As shown in our example, several events happen during the execution of our Camel routes. Explore our example application and watch the events occurring from the application's initialization to completing a route.

A complete Camel route

Unfortunately, there isn't extensive documentation on these events, but here we have a good starting point.

Event Apache Camel

Opinions expressed by DZone contributors are their own.

Related

  • Building Hybrid Multi-Cloud Event Mesh With Apache Camel and Kubernetes
  • Streamlining Event Data in Event-Driven Ansible
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • APIs for Logistics Orchestration: Designing for Compliance, Exceptions, and Edge Cases

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!