Day-8 Configuring Exception strategies

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

exception-1

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

try{

}catch(Exception ex){

}

exception-2

In flow:

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

 

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

exception-3

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.

exception-4

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 Day-8.zip at

https://drive.google.com/drive/folders/0B7kdTdRlWaF_TVhOaTk1cDVEYzQ

 

 

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 {
@Override
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;
@WebService
public interface EmployeeService {
public SalaryDetails getEmpSalDetails(Employee emp);
}

  1. Exposing Contract first web service, Please refer
    •  https://dzone.com/articles/mulesoft-contract-first-web-service-development

Code examples find at Day-7.zip at

https://drive.google.com/drive/folders/0B7kdTdRlWaF_TVhOaTk1cDVEYzQ

Day-6 JMS and DB Insert

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

  • Download  ActiveMQ from http://activemq.apache.org/download.html
  • 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

Jms-4

Import and execute the project, analyze the ActiveMQ console at

http://localhost:8161/admin/index.jsp

open the queues tab to see the queue details.

Demo-2 JMS as Inbound.

Design a flow that initiates from the JMS queue.

JMS-5

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

JMS-6

 

 

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.

DB_Insert1

DB-Insert-2

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″?>
<MovieDetail>
<movieCode>robo</movieCode>
<movieName>robo</movieName>
<director>Raj</director>
<hero>HYD</hero>
<releaseDate>2017-05-28</releaseDate>
<status>HYD</status>
</MovieDetail>

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-6.zip

https://drive.google.com/drive/folders/0B7kdTdRlWaF_TVhOaTk1cDVEYzQ

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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

inserted few records in to database as

INSERT INTO `mulesupport`.`moviedetails`
(`movieCode`,
`movieName`,
`director`,
`hero`,
`releaseDate`,
`status`)
VALUES
(<{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

db_select

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=”http://www.mulesoft.org/schema/mule/http&#8221; xmlns:tracking=”http://www.mulesoft.org/schema/mule/ee/tracking&#8221; xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
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/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd”&gt;
<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″/>
</async>
<logger message=”In Flow1 after referncing flow2″ level=”INFO” doc:name=”Logger”/>
</flow>
<flow name=”flow-2″>
<component class=”syncasync.MyObj” doc:name=”Java”/>
<logger message=”In Flow2 executing the flow” level=”INFO” doc:name=”Logger”/>
</flow>
</mule>

Please find the demo projects available  at day-5 zip

https://drive.google.com/drive/folders/0B7kdTdRlWaF_TVhOaTk1cDVEYzQ

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:

Capture

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 

flow-ref

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

2. Flow and Session Variables:

flowSession

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 Day-4.zip https://drive.google.com/drive/folders/0B7kdTdRlWaF_TVhOaTk1cDVEYzQ

Mule Exercises( Day 1,2 and 3)

Please find course contents and demo projects  here https://drive.google.com/drive/folders/0B7kdTdRlWaF_TVhOaTk1cDVEYzQ

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

Problem

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

Solution

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

Hibernate Basic Setup

Configuration

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- 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="hbm2ddl.auto">update</property>

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

</hibernate-configuration>

 

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
                .build();
        try {
             sessionFactory = new MetadataSources(registry)
                    .buildMetadata().buildSessionFactory();
        } catch (Exception e) {
            e.printStackTrace();
            StandardServiceRegistryBuilder.destroy(registry);
        }
        return sessionFactory;
    }

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

Entities

Base Entity

package com.model;

import java.io.Serializable;
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;

@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;

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

    @Column(name = "INIT_DATE")
    @Temporal(TemporalType.TIMESTAMP)
    private Date initDate = new Date();

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.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.
 * 
 */
@Entity
@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() {
        return this.name;
    }

    public void setName(String name) {
        this.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();

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

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

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

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

    }

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

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) {
        super(type);
    }
    // Implementations of ItemDao methods.
   }

Usage

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

1)Command:

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.

2)Invoker:

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

3)Receiver

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

4)Client:

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

Example

//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() {

bus.startVehicle();

}

}

//Command Implementation.

package com.javamirchi.command;

import com.javamirchi.command.service.Car;

public class StartCar implements Command {

Car car;

public StartCar(Car car) {

this.car = car;

}

public void execute() {

car.startVehicle();

}

}

//Invoker

package com.javamirchi.command;

public class Invoker {

Command command;

public Invoker(Command command) {

this.command = command;

}

public void processRequest() {

command.execute();

}

}

//Client

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);

invoker.processRequest();

Bus bus = new Bus();

command = new StartBus(bus);

invoker = new Invoker(command);

invoker.processRequest();

}

}

Output:

CAR has started…

BUS has started…

command2

Benefits:

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.

Drawback:

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

Example

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();
System.out.println(str);
} catch(final InterruptedException ex) {
ex.printStackTrace();
} catch(final ExecutionException ex) {
ex.printStackTrace();
}
service.shutdownNow();
}
}
class Foo implements Callable {
public String call() {
try {
// sleep for 10 seconds
Thread.sleep(10 * 1000);
} catch(final InterruptedException ex) {
ex.printStackTrace();
}
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() {
System.out.println(“Super”);
}
}
public class Child extends Super {
public static void foo() {  // hides Super.foo()
System.out.println(“Child”);
}
}
Here, Child.foo() is said to hide Super.foo().
static methods are not polymorphic

Super.foo(); // prints Super
Child.foo(); // prints Child

Lets examing on non-static scope

Super a = new Super();
Super b = new Child();
Child c = new Child();
Super d = null;

a.foo(); //  Prints Super
b.foo(); //  Prints Super because the declared type of b is Super
c.foo(); //  Prints Child because the declared type of c is Child
d.foo(); //  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;

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