Send data to remote REST web application using Mule ESB

In this tutorial I am going to show you how to send data from Mule application to remote web application which is basically a REST webservice application.

Prerequisites
Eclipse, JDK 1.8, JAX-RS jars 2.23.2
Have maven installed and configured
JAX-RS dependencies in pom.xml

For this tutorial we will create a web maven project in Eclipse. If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Step 1. Create a web maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-webapp
Now enter the required fields (Group Id, Artifact Id) as shown below
Group Id : com.roytuts
Artifact Id : rest
Step 2. Modify the pom.xml file as shown below.

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>rest</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>rest Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<java.version>1.8</java.version>
		<jersey.version>2.23.2</jersey.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>rest</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Modify web.xml file to use the jersey servlet

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
	<display-name>REST Service</display-name>
	<servlet>
		<servlet-name>REST</servlet-name>
		<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
		<init-param>
			<param-name>jersey.config.server.provider.packages</param-name>
			<param-value>com.roytuts.rest.resources</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Map /rest/* to Jersey -->
	<servlet-mapping>
		<servlet-name>REST</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app>

Step 5. Create a REST resource class as shown below

package com.roytuts.rest.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
@Path("/")
public class HelloRestService {
	@POST
	@Path("hello")
	@Consumes(MediaType.TEXT_PLAIN)
	public void sayHello(String message) {
		System.out.println("Message received : " + message);
	}
}

Step 6. Now run the application on Tomcat 8.

Mule Application

Let’s see how you can use an HTTP outbound endpoint to POST data to a URL. Using HTTP as a message source is just as easy.

Now we will create Mule application which will read data from file, convert to string and send to above remote REST application.

Prerequisites

Mule Studio 3.x(Anypoint Studio) (Download from https://www.mulesoft.com/platform/studio)
Maven 3.2.1 (Download from https://maven.apache.org/download.cgi?Preferred=ftp://mirror.reverse.net/pub/apache/)
JDK 1.7 (Download from http://www.oracle.com/technetwork/java/javase/downloads/index.html)
Configure JDK, Maven and Mule Studio

Step 1. First install JDK
Step 2. Add the Java_Home/bin directory to your system’s PATH.
Step 3. After downloading Maven, extract it to a drive
Step 4. Add the M2_Home/bin directory to your system’s PATH.
Step 5. Download and extract Mule Studio to a drive
Step 6. Now start Mule Studio by clicking on AnypointStudio exe icon in the folder <physical drive>/AnypointStudio
Step 7. Once started, close the startup page
Step 8. In Mule Studio, go to Window -> Preferences. Expand Java, then click on Installed JREs. Add JDK 1.7 and select it. In expanded Java, click on Compiler and select the compiler level as 1.7
Step 9. Now expand Anypoint Studio and click on Maven Settings. Then select appropriate Maven installation home directory using Browse button.
Step 10. If you want you can input Default groupId for new projects, it will save your time every time when you want to create a new project.

Create Mule project in Mule Studio
Now we will see how to create a new project in Mule Studio(Anypoint Studio).

Step 1. In Anypoint Studio, go to File -> New -> Mule Project
Step 2. Input Project Name: mule, Runtime is by default selected, tick on Use Maven; here the artifactId is automatically picked up from the Project Name:, the Group Id is picked up from the Default groupId for new projects and version is also a default value.
Step 3. Click Next and verify the JDK, mainly select Use default JRE(currently ‘jdk1.7.0_x’)
Step 4. Click on Next and click on Finish.

Example

The below screen-shot shows the graphical representation of the Mule flow

Step 1. Create the post-data-with-http-transport.xml file under src/main/app directory and put the below file connector. While you create the xml file you will see on red mark on each file connector. Do not worry, red mark will be disappeared once you modify the xml file as given in Step 3.


mule post data to remote application

Step 2. Open the post-data-with-http-transport.xml file and click on Configuration XML view in the Editor
Step 3. Modify the post-data-with-http-transport.xml file as shown below

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:file="http://www.mulesoft.org/schema/mule/file"
	xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking"
	xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
	xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.5.1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">
	<flow name="post-data-with-http-transport-flow" doc:name="post-data-with-http-transport-flow">
		<file:inbound-endpoint path="D:mule_workspaceinput_files"
			responseTimeout="10000" doc:name="File" />
		<file:file-to-string-transformer
			doc:name="File to String" />
		<http:outbound-endpoint exchange-pattern="one-way"
			host="${rest.service.host}" port="${rest.service.port}" path="${rest.service.path}"
			method="POST" doc:name="HTTP" />
	</flow>
</mule>

In the above configuration we a Mule flow named as post-data-with-http-transport-flow and inside this flow there are one file connector, which is acting as inboud-endpoint, a file-to-string transformer, which transforms file data into string and another one is http transport as outbound-endpoint, which is responsible for sending data to remote REST service.

Step 4. Open the file src/main/app/mule-app.properties and put the below key/value pairs

rest.service.host=localhost
rest.service.port=8080
rest.service.path=rest/hello

Step 6. Create hello.txt file and put it under D:mule_workspaceinput_files with below content inside the file.

Hello, World!

Running the application

Now do a right-click on the post-data-with-http-transport.xml file and click on Run As -> Mule Application. Then you will see something like below in Console when the application runs

INFO  2016-09-25 07:50:52,874 [main] org.mule.DefaultMuleContext:
**********************************************************************
* Application: mule                                                  *
* OS encoding: Cp1252, Mule encoding: UTF-8                          *
*                                                                    *
* Agents Running:                                                    *
*   DevKit Extension Information                                     *
*   Batch module default engine                                      *
*   Clustering Agent                                                 *
*   JMX Agent                                                        *
**********************************************************************
INFO  2016-09-25 07:50:52,874 [main] org.mule.module.launcher.MuleDeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Started app 'mule'                                       +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO  2016-09-25 07:50:52,877 [main] org.mule.module.launcher.DeploymentDirectoryWatcher:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Mule is up and kicking (every 5000ms)                    +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO  2016-09-25 07:50:59,843 [[mule].connector.file.mule.default.receiver.01] org.mule.transport.file.FileMessageReceiver: Lock obtained on file: D:mule_workspaceinput_fileshello.txt
INFO  2016-09-25 07:50:59,909 [[mule].connector.http.mule.default.dispatcher.01] org.mule.transport.service.DefaultTransportServiceDescriptor: Loading default outbound transformer: org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest
INFO  2016-09-25 07:50:59,914 [[mule].connector.http.mule.default.dispatcher.01] org.mule.transport.service.DefaultTransportServiceDescriptor: Loading default response transformer: org.mule.transport.http.transformers.MuleMessageToHttpResponse
INFO  2016-09-25 07:50:59,929 [[mule].connector.http.mule.default.dispatcher.01] org.mule.transport.service.DefaultTransportServiceDescriptor: Loading default outbound transformer: org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest
INFO  2016-09-25 07:50:59,930 [[mule].connector.http.mule.default.dispatcher.01] org.mule.lifecycle.AbstractLifecycleManager: Initialising: 'connector.http.mule.default.dispatcher.11971339'. Object is: HttpClientMessageDispatcher
INFO  2016-09-25 07:50:59,934 [[mule].connector.http.mule.default.dispatcher.01] org.mule.lifecycle.AbstractLifecycleManager: Starting: 'connector.http.mule.default.dispatcher.11971339'. Object is: HttpClientMessageDispatcher
INFO  2016-09-25 07:50:59,955 [[mule].connector.http.mule.default.dispatcher.01] org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest: Content-Type not set on outgoing request, defaulting to: text/plain

Once the application is up and running put the hello.txt file under D:mule_workspaceinput_files, you will receive the message “Message received : Hello, World!” in the REST webservice Eclipse console.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *