Camel Jetty Component Example

The jetty component provides HTTP-based endpoints for consuming and producing HTTP requests. Here is one simple example to expose a jetty end point and serving the http request from REST client.

1. Create Maven project with below dependencies.

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <version>2.12.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. Create a Simple Route to expose Jetty endpoint.

package com.vinod.test;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class CamelJettyExample {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyCamelJettyBuilder());
        main.run(args);
    }
}

class MyCamelJettyBuilder extends RouteBuilder {
    public void configure() {
        from("jetty:http://localhost:8181/mytestservice").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                String message = exchange.getIn().getBody(String.class);
                System.out.println("Hello Mr :" + message);
                exchange.getOut().setBody("Hello world Mr " + message);
            }
        });
    }
}

3. Run it
Run the application and hit the service
http://localhost:8181/mytestservice


4. Done !! Download application
https://github.com/kkvinodkumaran/camel

Java Thread Join() Example

1. ThreadJoinExample.java

package threading;
/**
 * <b>This class helps to understand the how Thread join() will work. I have a
 * scenario to execute the threads in order . Here i am creating 3 threads and
 * below are the execution order required</b>
 * 
 * <li>Thread 2 will start only after completion of thread 1</li> <li>Thread 3
 * will start only after completion of thread 2</li> <li></li> <li></li>
 * 
 * <li></li>
 * 
 * </ul>
 * 
 * @author vinod
 * 
 */
public class ThreadJoinExample {
	public static void main(String[] args) {
		Thread t1 = new Thread(new myThread1());
		Thread t2 = new Thread(new myThread2());
		Thread t3 = new Thread(new myThread3());
		try {
			t1.start();
			//Thread t2 will start only after completion of t1
			t1.join();
			t2.start();
			//Thread t3 will start only after completion of t2
			t2.join();
			t3.start();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
class myThread1 implements Runnable {
	public void run() {
		System.out.println("Thread1 Started");
	}
}
class myThread2 implements Runnable {
	public void run() {
		System.out.println("Thread2 Started");
	}
}
class myThread3 implements Runnable {
	public void run() {
		System.out.println("Thread3 Started");
	}
}

2.Ouput



Thread1 Started
Thread2 Started
Thread3 Started


Java Callable and Future Simple Example

 

🧵 Java Callable and Future – Simple Example

💡 Overview

In Java, the Callable and Future interfaces are part of the java.util.concurrent package and provide a more powerful alternative to the traditional Runnable interface.

Both Runnable and Callable are designed for classes whose instances can be executed by another thread — but with one key difference:

InterfaceReturns Result?Throws Checked Exception?
Runnable❌ No❌ No
Callable✅ Yes✅ Yes

So, if you need a thread to return a result or throw a checked exception, Callable is the right choice.


⚙️ Key Concepts

  1. Callable Interface

    • Similar to Runnable, but defines a method call() that can return a result and throw exceptions.

    • Signature:

      V call() throws Exception;
  2. ExecutorService

    • Manages a pool of worker threads.

    • Handles thread creation, task scheduling, and shutdown gracefully.

  3. Future Interface

    • Represents the result of an asynchronous computation.

    • Allows you to retrieve the result using future.get() once the task completes.


🧩 Example: Callable and Future in Action

1️⃣ File: CallableExample.java

package threading; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Demonstrates the use of ExecutorService, Callable, and Future interfaces. * * <ul> * <li>Thread1 implements Callable and overrides call() to return the thread name.</li> * <li>ExecutorService uses a fixed thread pool to execute multiple tasks.</li> * <li>Future stores and retrieves the result returned by Callable.</li> * </ul> * * Author: Vinod Kariyathungal Kumaran */ public class CallableExample { public static void main(String[] args) throws InterruptedException, ExecutionException { // Create a fixed thread pool of 10 threads ExecutorService ex = Executors.newFixedThreadPool(10); Thread1 t1 = new Thread1(); // Submit the Callable task multiple times and print results for (int i = 0; i <= 10; i++) { Future<String> future = ex.submit(t1); System.out.println(future.get()); } // Shutdown the executor ex.shutdown(); } } /** * Thread1 implements Callable and returns the current thread's name. */ class Thread1 implements Callable<String> { @Override public String call() throws Exception { return Thread.currentThread().getName(); } }

🧾 Output

pool-1-thread-1 pool-1-thread-2 pool-1-thread-3 pool-1-thread-4 pool-1-thread-5 pool-1-thread-6 pool-1-thread-7 pool-1-thread-8 pool-1-thread-9 pool-1-thread-10 pool-1-thread-1

🧠 Explanation

  1. ExecutorService creates a pool of 10 threads.
    This means at most 10 threads can run concurrently.

  2. Each time we call ex.submit(t1), the executor picks an available thread from the pool and runs the task.

  3. The Future<String> returned by submit() is used to get the result from Thread1.call().

  4. The output shows that threads are reused by the executor (thread-1 appears again at the end).

 

Java Template engine Freemarker simple example

1. Create a maven project and add below dependency

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.19</version>
</dependency>
            

2. Create a Template file and placed in to project folder (helloworld.flt)

Hello world Mr ${name}

3. Create a main class (FreeMarkerExample.java)

package com.pretech;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerExample {
	public static void main(String[] args) {
		try {
			Configuration config = new Configuration();
			Map<String, String> root = new HashMap<String, String>();
			root.put("name", "PRETECH");
			Template template;
			template = config.getTemplate("helloworld.ftl");
			StringWriter out = new StringWriter();
			template.process(root, out);
			System.out.println(out.getBuffer().toString());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
}

4. Output



Hello Mr PRETECH


Joining Iterable values using Guava Joiner

Joiner is an object which joins pieces of text which is from Iterable like ArrayList or Map. Here is one simple example to Joins ArrayList and Map values using Guava Joiner.

1. Create a Maven project add Guava dependency

  <dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>r09</version>
</dependency>

2. Create a Main Program to Join values (JoinerExample.java)

package com.pretech;
import java.util.List;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
public class JoinerExample {
	public static void main(String[] args) {
		// ArrayList Joining and skipping null
		final List<String> days = Lists.newArrayList("sunday", "monday",
				"tuesday", null);
		System.out.println(Joiner.on("\t ").skipNulls().join(days));
		// Map Joining
		final Map<String, String> personDetails = ImmutableMap.of("Name",
				"vinod", "Location", "Bangalore");
		System.out.println(Joiner.on("\t").withKeyValueSeparator(": ")
				.join(personDetails));
	}
}

3. Output



sunday     monday     tuesday
Name: vinod    Location: Bangalore


How to convert Java Properties to HashMap?

package com.pretech;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesToHashMap {
	public static void main(String args[]) {
		Properties properties = new Properties();
		properties.put("name", "Raj");
		Map<String, String> map = new HashMap<String, String>((Map) properties);
		System.out.println("Name is :" + map.get("name"));
	}
}

Output



Name is :Raj


XML to Java object using XMLDecoder Example

XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean.
The XMLDecoder class is used to read XML documents created using the XMLEncoder and is used just like ObjectInputStream. Here is one simple example to convert a java object to xml String and xml String to Java object

1. Create a java bean (Customer.java)

package com.pretech;
public class Customer {
	private String name;
	private String address;
	public Customer() {
	}
	public Customer(String name, String address) {
		super();
		this.name = name;
		this.address = address;
	}
//Getters and Setters

2. Create a main class to convert java object to xml

package com.pretech;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class ExlDecoderExample {
	public static void main(String[] args) {
		Customer c1 = new Customer("Pretech", "Bangalore");
		
		String customerXml=objectToXML(c1);
		System.out.println("Customer xml data :" +customerXml );
		System.out.println("Customer object data :" + XMLToObject(customerXml));
	}
	public static String objectToXML(Object voObj) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = null;
		try {
			xmlEncoder = new XMLEncoder(new BufferedOutputStream(stream));
			xmlEncoder.writeObject(voObj);
			xmlEncoder.close();
			return stream.toString("UTF-8");
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
	public static Object XMLToObject(String dataXML) {
		XMLDecoder d = null;
		try {
			d = new XMLDecoder(new ByteArrayInputStream(
					dataXML.getBytes("UTF-8")));
			Object voObj = d.readObject();
			d.close();
			return voObj;
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
}

3.Output

Customer xml data :<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_04" class="java.beans.XMLDecoder">
 <object class="com.pretech.Customer">
  <void property="address">
   <string>Bangalore</string>
  </void>
  <void property="name">
   <string>Pretech</string>
  </void>
 </object>
</java>
Customer object data :Customer [name=Pretech, address=Bangalore]

Ref: http://www.oracle.com/technetwork/java/persistence4-140124.html

Java object to xml using XmlEncoder Example

XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean. Here is one simple example to convert a java object to xml String.

1. Create a java bean (Customer.java)

package com.pretech;
public class Customer {
	private String name;
	private String address;
	public Customer() {
	}
	public Customer(String name, String address) {
		super();
		this.name = name;
		this.address = address;
	}
//Getters and Setters

2. Create a main class to convert java object to xml

package com.pretech;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
public class XMLEncoderExample {
	public static void main(String[] args) {
		Customer c1 = new Customer("Pretech", "Bangalore");
		
		String customerXml=objectToXML(c1);
		System.out.println("Customer xml data :" +customerXml );
	}
	public static String objectToXML(Object voObj) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = null;
		try {
			xmlEncoder = new XMLEncoder(new BufferedOutputStream(stream));
			xmlEncoder.writeObject(voObj);
			xmlEncoder.close();
			return stream.toString("UTF-8");
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
	
}

3.Output

Customer xml data :<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_04" class="java.beans.XMLDecoder">
 <object class="com.pretech.Customer">
  <void property="address">
   <string>Bangalore</string>
  </void>
  <void property="name">
   <string>Pretech</string>
  </void>
 </object>
</java>

Ref: http://www.oracle.com/technetwork/java/persistence4-140124.html

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts