Day-8 Configuring Exception strategies

There are different types of strategies available in mule to configure exceptions.


If we did not configure the exception strategy to the flow. then the exception will be handled by Mule Default Message exception strategy.

catchExceptionStrategy like similar to handling exception in Java using


}catch(Exception ex){



In flow:

<catch-exception-strategy doc:name=”CatchExceptionStrategy”>
<logger message=”Exception occured” level=”INFO” doc:name=”Logger”/>


It will handle all the exceptions.  if you want to handle each exception in a different manner then need to choose choiceExceptionStrategy.


if you define exception strategy inside flow the scope of strategy is up to the flow. the flow won’t be available in other flows.

To make the flow available to al flows, the strategy need to declare exception on global scope rather flow scope. the refer the strategy in the flow using ReferenceExceptionStrategy.


we can override Mule default exception strategy by declaring the exception strategy at global scope and marking it as default using configuration tag

  <configuration  defaultExceptionStrategy-ref=”myCatch”/> 

Code examples available at at



Day -7 Configuring SOAP web Services

In Mule ESB we can configure SOAP based web services through CXF component available in component palette.  we can develop services and clients for Simple and JAX-WS and proxy.

we can configure code first and contract first style web services.

  1. Exposing a method implementation as web service without JAX-WS
  2. Exposing a method implementation as web service with JAX-WS
  3. Exposing Contract first web service

Steps for Simple Service without JAX-WS.

  • configure HTTP component
  • Code the Service interface and implementation.

package simplesoap;
public interface WishService {
public String sayHello(String name);

package simplesoap;
public class WishServiceImpl implements WishService {
public String sayHello(String name) {
return “Hello” + name + “How are you ??” ;

  • Configure Java componentSOAP-1
  • Configure CXF component.SOAP-2
  • The configuration looks like
  • SOAP-3

2) Configuring service with JAX-WS

TO expose Jax-WS based web services, we need to annotate the service interface with @webservice

Steps are same as above service, only the service interface is annotated with @Webservice annotation

package jaxwssoap;
import javax.jws.WebService;
public interface EmployeeService {
public SalaryDetails getEmpSalDetails(Employee emp);

  1. Exposing Contract first web service, Please refer

Code examples find at at

Day-6 JMS and DB Insert

Configure JMS queue in Mule flow. we are using ActiveMQ JMS implementation for this demo.

  • Download  ActiveMQ from
  • Navigate to the path of activeMq
  • C:\xxxxx\apache-activemq-5.14.2-bin\apache-activemq-5.14.2\bin\win64
  • start ActiveMq messging server by giving command as >activemq
  • Configure ActiveMq to Anypoint studio
  • Drag and drop JMS icon to canvas
  • JMS
  • the properties as below. select the exchange pattern one-way or request-response based on requirement and provide queue namejms-2
  • Provide queue name and click on + icon
  • jms-3
  • provide username and password as admin/admin
  • Configuration complete

Demo-1: JMS as outbound endpoint.

send a request to mule flow where JMS queue configured as outbound endpoint


Import and execute the project, analyze the ActiveMQ console at


open the queues tab to see the queue details.

Demo-2 JMS as Inbound.

Design a flow that initiates from the JMS queue.


download and execute the project jmsreceiver.

Use ActiveMQ console to send the message to JMS queue. by clicking “Send” menu item on ActiveMQ home page




DB Insert Program:

Use Expression transformer to retrieve the fields from the payload. expression transformer will create new outbound endpoint properties. and populates them using Mule expression language.



Import the project DBInsertDemo  to the Anypoint  and run the flow

Test the flow with Postman or SOAPUI using the payload

<?xml version=”1.0″ encoding=”UTF-8″?>

makesure you selected mime type as application/xml while sending the request.

4) Analyze the Iterating the ResultSet and sending each record as JMS message in DBdemo projectDB-Iterate

The Demo projects available at

Day-5 Database connectivity and Sync & Async FLow concept

Concepts discussed today

  • Database connectivity and retrieving information
  • Sync-Async flows

Database connectivity:  MySql database has out of box support for Mule platform.

create Maven based mule project in order to manage database dependent jars. else create normal Mule project add mysql driver jar file to the build path.

DB setup:

created DB schema as :

CREATE DATABASE `mulesupport` /*!40100 DEFAULT CHARACTER SET utf8 */;

Created table in DB moviedetails in mulesupport schema as

CREATE TABLE `moviedetails` (
`movieCode` varchar(7) NOT NULL,
`movieName` varchar(50) DEFAULT NULL,
`director` varchar(45) DEFAULT NULL,
`hero` varchar(45) DEFAULT NULL,
`releaseDate` date DEFAULT NULL,
`status` varchar(14) DEFAULT NULL,
PRIMARY KEY (`movieCode`)

inserted few records in to database as

INSERT INTO `mulesupport`.`moviedetails`
(<{movieCode: }>,
<{movieName: }>,
<{director: }>,
<{hero: }>,
<{releaseDate: }>,
<{status: }>);

insert the date format as yyyy-MM-dd for release date field .

Application execution:

Design a flow that contains DB as message processor


execute the 3 modes of query processing.  execute the shared project and try to run the similar requirement in a customized way.

Sync and Async Flows:

Incase of Async caller won’t wait for the response from the calle. whereas in Sync mode caller blocks till the response received from the called flow.

execute the analyze the project and try to create your own customized implementation.

<?xml version=”1.0″ encoding=”UTF-8″?>

<mule xmlns:http=”; xmlns:tracking=”; xmlns=”; xmlns:doc=”;
<http:listener-config name=”HTTP_Listener_Configuration” host=”localhost” port=”8081″ doc:name=”HTTP Listener Configuration”/>
<flow name=”Flow-1″>
<http:listener config-ref=”HTTP_Listener_Configuration” path=”/” doc:name=”HTTP”/>
<logger message=”got request” level=”INFO” doc:name=”Logger”/>
<async doc:name=”Async”>
<flow-ref name=”flow-2″ doc:name=”flow1″/>
<logger message=”In Flow1 after referncing flow2″ level=”INFO” doc:name=”Logger”/>
<flow name=”flow-2″>
<component class=”syncasync.MyObj” doc:name=”Java”/>
<logger message=”In Flow2 executing the flow” level=”INFO” doc:name=”Logger”/>

Please find the demo projects available  at day-5 zip

Day-4 Flows and Variables

Discussed concepts

  • Connecting Flows
  • Passing properties between flows
  • Flow and session Variables
  • Flows, sub flows and private flows
  • Synchronous and Asynchronous flows

Connecting Flows:


Points to observe:

  • VM endpoint configuration
  • Properties flowing from first flow to second flow
  • what need to do if we want to copy all inbound properties of first flow to the second flow
  • download execute the project “connectingflows” in Anypoint studio
  • Test from the browser:  http://localhost:8081?name=abc&age=22
  • How to copy selected inbound properties to outbound. execute the demo project  “usingmessagetransformer”  to analyze this.

Using Flow-reference 


Debug the project and test with browser http://localhost:8085?name=abc&age=22

2. Flow and Session Variables:


Points to observe

  • Import the project and analyze how the flow and session variables are created.
  • Debug the demo and understand scope of flow and session variables

The projects available at

Mule Exercises( Day 1,2 and 3)

Please find course contents and demo projects  here

Lab -1:  Mule Basics

  • 1) Develop a flow that will display “HelloWorld”  to the browser.
  • 2) Install Postman plug-in to google  chrome and  send HTTP POST request,

“Hello World”  as Payload, print payload using logger component and observe Inbound and outbound properties in debug mode.

Lab-2: Configuring Java component to Mule Flow

  • 1) Configure component with Method Entry point resolver
  • 2) Configure Java component with three different types of method arguments with the Help of Invoke activity
  • 3) What is the difference between Configuring java component as Spring bean and configuring component as non-spring based?
  • 4) Develop a component implementing Callable Interface
  • 5) Develop a Java component using Annotations.


Lab-3: Mule Expression Language:

  • 1) What is syntax of retrieving inboundProperties of  Mule Message
  • 2) What is Mule Expression to Retrieve Http method? In how many ways we can define this expression?
  • 3) Develop  Xpath expression to extract data from payload
  • 4) Develop regular expression to extract data from Payload

Lab-4: Connecting Flows

  • 1) Connecting the flows using VM endpoints and flowref, observe inbound and outbound properties in both scenarios







Generic DAO


Redundant/Duplicate CURD operations code for all entities in their respective DAO’s.


Now we have encapsulated the CURD operations in one Generic class and make other other DAO’s extend the generic dao.

Hibernate Basic Setup



<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"



        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="">update</property>

        <mapping class="com.pos.model.BaseEntity" />
        <mapping class="com.pos.model.Item" />



Hibernate Utils

SessionFactory is made Singleton here

package com.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtils {

    private HibernateUtils() {

    private static SessionFactory sessionFactory;

    private static SessionFactory buildSessionAnnotationFactory() {

        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
        try {
             sessionFactory = new MetadataSources(registry)
        } catch (Exception e) {
        return sessionFactory;

    public static synchronized SessionFactory getSessionAnnotationFactory() {
        if (sessionFactory == null)
            sessionFactory = buildSessionAnnotationFactory();
        return sessionFactory;


Base Entity

package com.model;

import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

public abstract class BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "ID", nullable = false)
    protected int id;

    @Column(name = "INIT_DATE")
    private Date initDate = new Date();

    public void setCreationDate() {
        this.initDate = new Date();

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public Date getInitDate() {
        return initDate;

    public void setInitDate(Date initDate) {
        this.initDate = initDate;


Item Entity – For Example

package com.model;

import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

 * The persistent class for the ITEM database table.
@Table(name = "ITEM")
@AttributeOverride(name = "id", column = @Column(name = "ITEM_ID", nullable = false))
public class Item extends BaseEntity {
    private static final long serialVersionUID = 1L;

    @Column(name = "`DESC`", length = 45)
    private String desc="";

    @Column(name = "NAME", nullable = false, length = 45)
    private String name="";

    @Column(name = "QTY")
    private float qty = 0.0F;

    public Item() {

    public String getDesc() {
        return this.desc;

    public void setDesc(String desc) {
        this.desc = desc;

    public String getName() {

    public void setName(String name) { = name;

    public float getQty() {
        return qty;

    public void setQty(float qty) {
        this.qty = qty;


Generic DAO

package com.dao;

import java.util.List;

import com.model.BaseEntity;

public interface GenricDao<T extends BaseEntity> {

    public List<T> get();

    public T get(int id);

    public void save(T t);

    public void update(T t);
    public void delete(T t);


Generic DAO Impl

package com.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.pos.model.BaseEntity;
import com.pos.util.HibernateUtils;

public class GenericDaoImpl<T extends BaseEntity> implements GenricDao<T> {

    public GenericDaoImpl(Class<T> type) {
        this.type = type;

    protected Class<T> type;

    protected SessionFactory factory = HibernateUtils.getSessionAnnotationFactory();

    public List<T> get() {
        List<T> list = null;
        Session session = null;
        try {
            session = factory.openSession();
            list = session.createCriteria(type).list();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (session != null && session.isOpen())
        return list;

    public T get(int id) {
        T t = null;
        Session session = null;
        try {
            session = factory.openSession();
            t = session.get(type, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (session != null && session.isOpen())
        return t;

    public void save(T t) {
        Session session = null;
        try {
            session = factory.openSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (session != null && session.isOpen())

    public void update(T t) {
        Session session = null;
        try {
            session = factory.openSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (session != null && session.isOpen())


    public void delete(T t) {
        Session session = null;
        try {
            session = factory.openSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (session != null && session.isOpen())

Item DAO

package com.dao;

import com.model.Item;

public interface ItemDao extends GenricDao<Item> {

   // Other Operations/methods specific to this DAO.

Item DaoImpl

package com.dao;

import org.hibernate.Session;

import com.model.Item;

public class ItemDaoImpl extends GenericDaoImpl<Item> implements ItemDao {

    public ItemDaoImpl(Class<Item> type) {
    // Implementations of ItemDao methods.


Now you can use itemDao and access the Basic CURD and other Specific to Item operations.

private ItemDao itemDao = new ItemDaoImpl(Item.class);

In case you need only Basic CURD you can also use like this

private GenricDao<Item> itemDao = new GenericDaoImpl<Item>(Item.class);


Command design pattern

The command design pattern is a behavioral design pattern in which object is used to represent and encapsulates the all information need to call a method at later time.

Using command design pattern the interaction between client and service is more decoupled manner.

In command design pattern we have below components


It is a parent interface for all the commands, it defines the contract.

2)Command Implementation:

These classes are the implementation of command interface, these classes are responsible for calling actual service code.


It will act as a bridge between the client request and command object.


Is nothing but service implementation class, which contain core logic.


Client will instantiate appropriate command  and it will execute the action command.


//Service interface

package com.javamirchi.command.service;

public interface Vehicle {

public void startVehicle();

public void stopVehicle();


//Service implementation (Receiver)

package com.javamirchi.command.service;

public class Bus implements Vehicle{

public void startVehicle() {

System.out.println(“BUS has started…”);


public void stopVehicle() {

System.out.println(“BUS has stopped…”);



//Service implementation2 (Receiver)

package com.javamirchi.command.service;

public class Car implements Vehicle{

public void startVehicle() {

System.out.println(“CAR has started…”);


public void stopVehicle() {

System.out.println(“CAR has stopped…”);



//Command Interface

package com.javamirchi.command;

public interface Command {

public void execute();


//Command Implementation.

package com.javamirchi.command;

import com.javamirchi.command.service.Bus;

public class StartBus implements Command {

Bus bus;

public StartBus(Bus bus) {

this.bus = bus;


public void execute() {




//Command Implementation.

package com.javamirchi.command;

import com.javamirchi.command.service.Car;

public class StartCar implements Command {

Car car;

public StartCar(Car car) { = car;


public void execute() {





package com.javamirchi.command;

public class Invoker {

Command command;

public Invoker(Command command) {

this.command = command;


public void processRequest() {





package com.javamirchi.client;

import com.javamirchi.command.Command;

import com.javamirchi.command.Invoker;

import com.javamirchi.command.StartBus;

import com.javamirchi.command.StartCar;

import com.javamirchi.command.service.Bus;

import com.javamirchi.command.service.Car;

public class CilentTest {

public static void main(String[] args) {

Car car = new Car();

Command command = new StartCar(car);

Invoker invoker = new Invoker(command);


Bus bus = new Bus();

command = new StartBus(bus);

invoker = new Invoker(command);





CAR has started…

BUS has started…



i)We can store list of command for later user.

ii)A class is a good place to store procedure

iii)Best way to implement callback functionality

iv)Decoupling the service implementation class and receiver.


The only drawback is  number of classes will be increased.

How Thread return a value after finishing its job?

ExecutorService is an interface that extends Executor class and represents an asynchronous execution. It provides us mechanisms to manage the end and detect progress of the asynchronous tasks.
Java Callable tasks return java.util.concurrent.Future object. Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.

Callable and Future Example in Java


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;

public class Main {
public static void main(final String[] args) {
final ExecutorService service;
final Future task;
service = Executors.newFixedThreadPool(5);
task = service.submit(new Foo());
try {
final String str;
str = task.get();
} catch(final InterruptedException ex) {
} catch(final ExecutionException ex) {
class Foo implements Callable {
public String call() {
try {
// sleep for 10 seconds
Thread.sleep(10 * 1000);
} catch(final InterruptedException ex) {
return (“Hello, World!”);

Method Hiding in java

“Method hiding means subclass has defined a class method with the same signature as a class method in the superclass. In that case the method of superclass is hidden by the subclass.”

public class Super {
public static void foo() {
public class Child extends Super {
public static void foo() {  // hides
Here, is said to hide
static methods are not polymorphic; // prints Super; // prints Child

Lets examing on non-static scope

Super a = new Super();
Super b = new Child();
Child c = new Child();
Super d = null;; //  Prints Super; //  Prints Super because the declared type of b is Super; //  Prints Child because the declared type of c is Child; //  Prints Super because of static method

if the methods are nonstatic  in Super and child classes then

Super a = new Super();
Super b = new Child();
Child c = new Child();
Super d = null;; // prints Super; // prints Child–> Observe and compare this method call on static and non-                                                                                                                                    static scenarios; // prints Child // throws NullPointerException