Saturday 12 January 2019

Camel: Custom UUID Generator


By implementing 'org.apache.camel.spi.UuidGenerator' interface, you can create custom UUID generator.

Step 1: Create Custom UUID generator.
public class MyUUIDGenerator implements UuidGenerator {
         AtomicInteger atomicInt = new AtomicInteger(1);

         @Override
         public String generateUuid() {
                  return String.valueOf(atomicInt.getAndIncrement());
         }

}

Step 2: Register custom UUID generator to context.
CamelContext context = new DefaultCamelContext();
context.setUuidGenerator(new MyUUIDGenerator());

Find the below working application.

MyUUIDGenerator.java
package com.sample.app.generators;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.camel.spi.UuidGenerator;

public class MyUUIDGenerator implements UuidGenerator {
	AtomicInteger atomicInt = new AtomicInteger(1);

	@Override
	public String generateUuid() {
		return String.valueOf(atomicInt.getAndIncrement());
	}

}

Application.java
package com.sample.app;

import java.util.concurrent.TimeUnit;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

import com.sample.app.generators.MyUUIDGenerator;

public class Application {

	public static class FileCopyRoute extends RouteBuilder {

		@Override
		public void configure() throws Exception {
			from("file:C:\\Users\\Public\\demo?noop=true").process(new Processor() {

				@Override
				public void process(Exchange exchange) throws Exception {
					String exchangeId = exchange.getExchangeId();
					String messageId = exchange.getIn().getMessageId();
					
					System.out.println("Exchange Id : " + exchangeId);
					System.out.println("Message Id : " + messageId);
				}

			}).to("file:C:\\Users\\Public\\demoCopy");
		}

	}

	public static void main(String args[]) throws Exception {
		CamelContext context = new DefaultCamelContext();
		
		context.setUuidGenerator(new MyUUIDGenerator());

		context.addRoutes(new FileCopyRoute());

		context.start();

		TimeUnit.MINUTES.sleep(1);

		context.stop();
	}
}


Run Application.java, you can see below messages in console.
Exchange Id : 1
Message Id : 2

Previous                                                 Next                                                 Home<

No comments:

Post a Comment