Search Tutorials


Calling and Consuming Webservices using Apache Camel | JavaInUse

Calling and Consuming Webservices using Apache Camel

In previous posts Apache Camel JAX-RS REST Web Service and Apache Camel CXFRS REST Web Service we had seen how to expose REST APIs using Apache Camel.
In this post we will be calling and consuming an existing REST Service using Apache Camel Route. We will be using Apache Camel Java DSL and and Spring for this purpose. We will be calling and consuming both REST GET and REST POST Api's.
Apache Camel Consume Webservice

Apache Camel - Table of Contents

File Transfer Using Java DSL Apache Camel Apache Camel Java DSL + Spring Integration Hello World Example Apache Camel Exception Handling Using Simple Example Apache Camel Redelivery policy using example Integrate Apache Camel and ActiveMQ EIP patterns using Apache Camel Apache Camel Tutorial- Integrate Spring Boot+ Apache Camel Apache Camel Tutorial- Integrate with MySQL DB using SQL query Apache Camel EIP - Splitter and Aggregator pattern Apache Camel Unit Testing Apache Camel + Spring + Quartz Hello World Example Camel application deployment on JBoss Fuse Apache Camel + Apache CXF SOAP Webservices Apache Camel + JAX-RS REST Webservice Apache Camel + CXFRS REST Webservice Apache Camel Routing Slip EIP Pattern Apache Camel Dynamic Router Pattern Apache Camel Load Balancer EIP Pattern Apache Camel Interceptors Apache Camel + Kafka Hello World Example Apache Camel - Marshalling/Unmarshalling XML/JSON Data Example Calling and Consuming Webservices using Apache Camel Apache Camel Tutorial - Send SMTP Email Using Gmail Apache Camel Tutorial - SEDA component Hello World Example

Video

This tutorial is explained in the below Youtube Video.

Lets Begin

  • Expose web services using Spring Boot

    First lets create a Spring Boot application to expose two REST API's. One will be a GET request while other will be a POST request.
    The maven project we will be creating is as follows-

    Spring Boot expose REST API
    The pom.xml with spring boot dependencies is as follows-
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>com.javainuse</groupId>
    	<artifactId>employee-producer</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.4.1.RELEASE</version>
    		<relativePath /> <!-- lookup parent from repository -->
    	</parent>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    		<java.version>1.8</java.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    
    
    </project>
    

Define the domain class Employee.
package com.javainuse.model;

public class Employee {
	private int empId;
	private String name;
	private String designation;
	private double salary;

	public Employee() {
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}

}

Expose the service using the Controller. We will be exposing 2 API's here-
  • The GET API will accept an id as a request parameter and create an employee object using the passed id and return it as response.
  • The POST API will accept an employee object as request body. Using the parameters of the employee object it will create another employee object and return it as response.
package com.javainuse.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.model.Employee;

@RestController
public class TestController {

	@RequestMapping(value = "/employee", method = RequestMethod.GET)
	public Employee firstService(@RequestParam int id) {

		Employee emp = new Employee();
		emp.setName("emp1");
		emp.setDesignation("manager");
		emp.setEmpId(id);
		emp.setSalary(3000);

		return emp;
	}

	@RequestMapping(value = "/employee", method = RequestMethod.POST)
	public Employee secondService(@RequestBody Employee employee) {

		System.out.println("Inside POST Method");
		Employee emp = new Employee();
		emp.setName(employee.getName());
		emp.setDesignation(employee.getDesignation());
		emp.setEmpId(employee.getEmpId());
		emp.setSalary(employee.getSalary());

		return emp;
	}

}

Finally define the Spring Boot Main class
package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootHelloWorldApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootHelloWorldApplication.class, args);
	}
}
  • Apache Camel Module for consuming REST API's

    The project structure we would be creating will be as follows-

    Apache Camel consume REST API module

    The pom.xml will be as follows-
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>com.javainuse</groupId>
    	<artifactId>apache-camel-consume</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<dependencies>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-core</artifactId>
    			<version>2.12.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-spring</artifactId>
    			<version>2.12.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-http</artifactId>
    			<version>2.12.0</version>
    
    
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-jackson</artifactId>
    			<version>2.12.0</version>
    		</dependency>
    	</dependencies>
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.1</version>
    			</plugin>
    		
    		</plugins>
    	</build>
    </project>
    

    Define the domain class Employee.
    package com.javainuse.model;
    
    public class Employee {
    	private int empId;
    	private String name;
    	private String designation;
    	private double salary;
    
    	public Employee() {
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getDesignation() {
    		return designation;
    	}
    
    	public void setDesignation(String designation) {
    		this.designation = designation;
    	}
    
    	public double getSalary() {
    		return salary;
    	}
    
    	public void setSalary(double salary) {
    		this.salary = salary;
    	}
    
    	public int getEmpId() {
    		return empId;
    	}
    
    	public void setEmpId(int empId) {
    		this.empId = empId;
    	}
    
    }
    

    Create the camel processor which will create an Employee object and then marshal it to JSON. This will be required for POST call-
    package com.javainuse.processor;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    
    import com.javainuse.model.Employee;
    
    public class CreateEmployeeProcessor implements Processor {
    
        public void process(Exchange exchange) throws Exception {
            System.out.println(exchange.getIn().getBody(String.class));
        	Employee emp = new Employee();
    		emp.setName("camel-employee");
    		emp.setDesignation("camel-manager");
    		emp.setEmpId(111);
    		emp.setSalary(30000);
    		exchange.getIn().setBody(emp);
        }
    
    }
    

    Create the SimpleRouteBuilder class that extends RouteBuilder and configures the camel route.
    package com.javainuse.route;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.builder.RouteBuilder;
    import org.apache.camel.component.jackson.JacksonDataFormat;
    
    import com.javainuse.model.Employee;
    import com.javainuse.processor.CreateEmployeeProcessor;
    import com.javainuse.processor.MyProcessor;
    
    public class SimpleRouteBuilder extends RouteBuilder {
    
    	JacksonDataFormat jsonDataFormat = new JacksonDataFormat(Employee.class);
    
    	@Override
    	public void configure() throws Exception {
    
    		// route for REST GET Call
    		from("file:C:/inputFolderREST?noop=true").setHeader(Exchange.HTTP_METHOD, simple("GET"))
    				.to("http://localhost:8080/employee?id=5").process(new MyProcessor());
    
    		// route for REST POST Call
    		from("file:C:/inboxPOST?noop=true").process(new CreateEmployeeProcessor()).marshal(jsonDataFormat)
    				.setHeader(Exchange.HTTP_METHOD, simple("POST"))
    				.setHeader(Exchange.CONTENT_TYPE, constant("application/json")).to("http://localhost:8080/employee")
    				.process(new MyProcessor());
    	}
    
    }
    
    Create the camel processor which will be printing the response returned after consuming the REST API
    package com.javainuse.processor;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    
    public class MyProcessor implements Processor {
    
        public void process(Exchange exchange) throws Exception {
            System.out.println(exchange.getIn().getBody(String.class));
        }
    }
    

    Create the application context that calls the Java DSL RouteBuilder class using the routeBuilder
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    		http://www.springframework.org/schema/beans/spring-beans.xsd          
    		http://camel.apache.org/schema/spring 
    		http://camel.apache.org/schema/spring/camel-spring.xsd">
    
    	<bean id="routeBuilder" class="com.javainuse.route.SimpleRouteBuilder" />
        <bean id="processor" class="com.javainuse.processor.MyProcessor" />
        
    	<camelContext xmlns="http://camel.apache.org/schema/spring">
    		<routeBuilder ref="routeBuilder" />
    	</camelContext>
    </beans>
    

    Finally load the context file to start the Java DSL camel route.
    package com.javainuse.main;
    
    import org.springframework.context.support.AbstractApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MainApp {
    
        public static void main(String[] args) {
            AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-camel.xml");
            ctx.start();
            System.out.println("Application context started");
            try {
                Thread.sleep(5 * 60 * 1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.stop();
            ctx.close();
        }
    }
    
    • Start the Spring Boot Module which exposes the REST API.
    • Start the Apache Camel Module- Copy some data in C:/inputFolderREST folder. The REST GET API consumption route gets triggered
      Apache Camel consume REST GET API
      Copy some data in C:/inputFolderPOST folder. The REST POST API consumption route gets triggered
      Apache Camel consume REST POST API
  • Download Source Code

    Download it - Apache Camel Consume REST API Module
    Download it - Spring Boot Expose REST API Module

    See Also

    Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions