Thursday, August 20, 2020

How to use Redis caching server with Spring Boot.

Firstly, I would like to explain about the advantage about cacheing.


When we use RESTFull applicatoin, most of the time, we are using token (Ex: JWT) base authentication/authorization. Since we are using token base authentication/authorization, we don't cross check the user infomation with the database. Therefore, if somebody copy the token and logout from the system, still, if he/she knows the API details, they can invoke the APIs (Using Postman, curl or similer tools). It is very unsecure, so, better to keep the token information somewhere, we can access the inforation very quickly and easily, then we can validate service invokation whether is it valid or not.

In this article I'm going to describe, how to conect and use Redis server in Spring Boot application.

Steps:

1. Start the Redis server. For this explanation I'm going to use the docker.

 docker run -p 6379:6379 --name redis -v redis.conf:/usr/local/etc/redis/redis.conf -d --memory 100m redis


2. Then we need to add below dependency for the project

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
</dependency>


Here I'm going to use jedis client.

3. Enable caching

import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class TestApplication {
    ....
}


4. Redis cache repository

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

@Repository
public class RedisCacheRepository {
    private HashOperations hashOperations;
    private RedisTemplate redisTemplate;

    private final Logger logger = LoggerFactory.getLogger(RedisCacheRepository.class);

    private long tokenValidity = 180000;

    public RedisCacheRepository(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
        this.hashOperations = this.redisTemplate.opsForHash();
    }

    public void save(String tokenId) {
        try {
            hashOperations.put("USERS", tokenId, tokenId);
            redisTemplate.expire("USERS", tokenValidity, TimeUnit.MILLISECONDS);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
    }
    
    public boolean findById(String tokenId) {
        boolean activeUser = false;
        try {
            activeUser = hashOperations.get("USERS", tokenId) != null;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return activeUser;
    }

    public void delete(String tokenId) {
        try {
            hashOperations.delete("USERS", tokenId);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
    }
}


Above data is just for explain purpose only.
I have added token validity period (tokenValidity), because, if user ideal and/or doesn't logout properly, we cannot delete the login info from the cache. Therefore, we can add a expire time as above.

Wednesday, February 12, 2020

Feign Client - Spring Boot (Microservice) inter service call

In this article I'm planing to explain the way we can implement Feign Client to invoke inter service call.

We have eurekaServer, zuulServer, clientServer, serverServer. Initially, we need to register our all servers with the eurekaServer.
zuulServer register as proxyService
clientServer register as oneService
serverServer register as twoService
twoService has a end-point as below:
 http method: POST

 url: /api/person/{personId}/bank

1st of all, we need to add dependency to the application. In this example I'm going to use maven dependency as below.
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-feign</artifactId>
      <version>#{feign.version}</version>
</dependency>

According to the above end-point, we need to implement the feign-client as below
 @FeignClient(name = "twoservice", path = "/api",
        fallback = TwoServiceFallBack.class,
        configuration = DefaultFeignConfig.class)
public interface TwoServiceClient {

    @RequestMapping(path = "/person/{personId}/bank", method = RequestMethod.POST)
    CustomResponseMessage addBankInfo(@PathVariable("personId") String personId, @RequestBody BankDTO bankDTO);

}

And also fall-back class below (when calling the service, if something happen, you can handle the situation here).
@Component
public class TwoServiceClientFallBack implements TwoServiceClient {

    @Override
    public CustomResponseMessage addBankInfo(String personId, BankDTO bankDTO) {
     //
        return null;
    }
}

CustomResponseMessage -> response payload.
BankDTO -> request body

Hope this will helpful.

Thursday, April 18, 2019

Java 8 method reference

Java 8 provides a new feature call method reference. Method reference is used to refer method of functional interface.

There are 3 types of method reference as listed below.
  1. Reference to a static method
  2. Reference to an instance method
  3. Reference to a constructor
I'm going to use same sample to explain the way can use method reference.

1. Reference to a static method

Syntax:
ClassName::staticMethodName

Sample code:
public class MyPrinter { public static void print(String name) { System.out.println(name); } }


public class PrinterApp { public static void main(String[] args) { List<String> names = Arrays.asList("Tharanga", "Wijeweera"); names.forEach(MyPrinter::print); } }


2. Reference to an instance method

Syntax:
object::instanceMethodName

Sample code:
    public class MyPrinter {
     public void print(String name) {
         System.out.println(name);
     }
   }


public class PrinterApp {
public static void main(String[] args) { MyPrinter myPrinter = new MyPrinter(); List<String> names = Arrays.asList("Tharanga", "Wijeweera"); names.forEach(myPrinter::print); } }

3. Reference to a constructor

Syntax:
ClassName::new

Sample code:
    public class MyPrinter {

     private String name;

     public MyPrinter(String name) {
         this.name = name;
         print();
     }

     public void print() {
         System.out.println(this.name);
     }
    }


public class PrinterApp {
public static void main(String[] args) { List<String> names = Arrays.asList("Tharanga", "Wijeweera"); names.forEach(MyPrinter::new); } }

Hope this will help you to get an idea about the method reference in Java 8.

Thursday, November 22, 2018

Spring Boot (Microservice) - Inter service call

Generally, inter service call more common, when we develop a microservice application. So in this artical, I'm going to explain, how to use RestTemplate to call another service.

We have eurekaServer, zuulServer, clientServer, serverServer. Initially, we need to register our all servers with the eurekaServer.
zuulServer register as proxyService
clientServer register as oneService
serverServer register as twoService

twoService has a end-point as below:
http method: PUT
url: /api/person/{personId}/bank

this end-point is going to update the bank information in particulate person and we need to pass the bank details in the body. As below, you can call above end-point in twoService from oneService.

    @Autowired 
    private final RestTemplate restTemplate;
    @Autowired 
    private final EurekaClient eurekaClient;
   .....
   .....
    public CustomResponseMessageDTO method() {
     ....
        String endPoint = "/api/person/{personId}/bank"
        HttpEntity<BankDTO> requestEntity = new HttpEntity<>(bank_information_BankDTO_object);
        Map<String, String> param = new HashMap<>();
param.put("personId", "person_id_should_pass");
        Application application = eurekaClient.getApplication(twoService);
        InstanceInfo instanceInfo = application.getInstances().get(0);
        String url = "http://" + instanceInfo.getIPAddr() + ":" + instanceInfo.getPort() + endPoint;
        ResponseEntity<CustomResponseMessageDTO> exchange = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, CustomResponseMessageDTO.class, param);
        return exchange.getBody(); // this return the CustomResponseMessageDTO object.
    }
....
As above, you can pass the message body using HttpEntity and url paramerter using HashMap.

If you need to pass the header you can add the header to the HttpEntity as below
HttpEntity<BankDTO> requestEntity = new HttpEntity<>(bank_information_BankDTO_object, HttpHeaders_object);

Enjoy..!!!

Spring Boot - Read yml file

When developing a Spring Boot application, we are using yml (properties) file to store the data. Due to this without we don't want to re-build the source code after change the property values.

Even thought this a very basic thing, in this article, I'm going to explain the way we can get the data from yml file.

For this explanation, I'm going to take application.yml file and we have a property as below
company:
  name: Company ABC

Then we can get this value in java code as below
public class TestApplication {
...
@Value("${company.name}")
        private String companyName;
...
}

This value will cast to the variable type.

Enjoy.....!!!

Thursday, June 21, 2018

No 'Access-Control-Allow-Origin' header is present on the requested resource.

In this blog I'm try to explain the way we can solve above issue from the "SpringBoot" side.

I faced the below issue with calling my service through the React.
Failed to load http://xx.xx.xx.xx:8080/api/yy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xx.xx.xx.xx:3000' is therefore not allowed access.

Default, it didn't set the "Access-Control-Allow-Origin" header. So, you can solve this as below.

1. Create a filter as below
 
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter extends GenericFilterBean implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        //httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        //httpResponse.setHeader("Access-Control-Allow-Headers", "*");
        //httpResponse.setHeader("Access-Control-Allow-Credentials", "false");
        //httpResponse.setHeader("Access-Control-Max-Age", "3600");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

Add if you need add more headers you can add as above.

2. In the main application you have to set the @Bean as below
@SpringBootApplication
@EnableMongoRepositories(basePackages= {"com.home"})
@EntityScan(basePackages = {"com.home"})
@EnableEurekaClient
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class);
    }
    public FilterRegistrationBean corsFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CORSFilter());
        registrationBean.setName("CORS Filter");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        return registrationBean;
    }
}


After this, when you execute the service you can see the 'Access-Control-Allow-Origin' in the header.

Enjoy...!!!

Friday, March 2, 2018

The way we can use 'intellij community edition' to debug tomcat application:

 Environment configurations use for this explanation:

        #  apache-tomcat-7.0.85
        #  IntelliJ IDEA 2017.3.2 (Community Edition)

Steps:

1. Build the project and put the war file into the webapps folder(<tomcat_home>/webapps/).

2. Intellij IDEA
    a) Run -> Edit Configurations
    b) Press the green + and select 'Remote'
    c) Give a proper name (Ex: debug-demo)
    d) Set the host and port(not the tomcat running port number. better to keep the default 5005)
    f) Select the 'Search sources using module's classpath (better to select root)
    g) Copy the 'Command line arguments for running remove JVM'
    Ex: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

3. Tomcat
    a) Open the 'setclasspath.sh'
    b) Set the above copied 'Command line arguments for running remove JVM' value to the  'JAVA_OPTS'. To do that, paste the below line at the end of the file:
JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
    c) Start the tomcat
        Ex: sh startup.sh

4. Intellij IDEA
    a) Select the 'debug-demo' according to our example
    b) Press 'Debug' icon (Shift+9)

Then you can see the connected message in the console as below:
Connected to the target VM, address: 'localhost:5005', transport: 'socket'

Enjoy...!!!

Friday, January 26, 2018

How to connect MySql 5.x using Hibernate 5

In this post, I'll discuss below points

  • How to create 'SessionFactory' and 'Session'
  • How to choose  'dialect'
Create 'SessionFactory' and 'Session'

Hibernate 5 comes with major changes and they change the way we can building 'SessionFactory'

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

....

StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
SessionFactory sf = metadata.getSessionFactoryBuilder().build();
Session session = sf.openSession()

...
Select 'dialect'.

In hibernate 5, we can below below dialects when connecting to the MySQL


  • org.hibernate.dialect.MySQL5Dialect
  • org.hibernate.dialect.MySQL55Dialect
  • org.hibernate.dialect.MySQL57Dialect

Note: org.hibernate.dialect.MySQLDialect is for MySQL 4.x or earlier.

Enjoy...!!

Sunday, December 10, 2017

Spring - Execute a init method when initializing bean and destroying bean.

There are couple of ways to achieve this requirement.

First methodology
You can simply implements below interfaces in the bean

  • InitializingBean
  • DisposableBean
Then you have to override below methods respectively above interfaces. 

  • afterPropertiesSet()
  • destroy()
Note: You have to use registerShutdownHook (link) to see the effect of the destroy method.

Second methodology
In this scenario, I would like to introduce the way we can execute the custom method when initializing and destroying beans.

Initially, you have to implement custom methods for init and destroy as below
    public void myInit() {
        System.out.println("This is the custom init method");
    }
....
    public void myDestroy() {
        System.out.println("This is the custom destroy method");
    }

In the bean configuration file you have to tell to the Spring what are the init and destroy methods as below.
<beans>
    <bean id="student" class="com.home.model.Student" init-method="myInit" destroy-method="myDestroy">
        .....
    </bean>
.....
.....
</beans>

Enjoy...!!!


Tuesday, December 5, 2017

Spring - How to destroy beans when application shutdown? (registerShutdownHook)

If someone needs to destroy the beans when shutdown then application, what you need to do is:
  • Create a 'AbstractApplicationContext'
  • call the 'registerShutdownHook'
Find the below code for your reference

AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
context.registerShutdownHook();

Once this "registerShutdownHook()" method executes, it destroy the beans when down the application.


Enjoy..!!

Sunday, September 24, 2017

Lambda (Java 8) - Transfer one type of object to another type of object

We will assume that we have list of Students to convert into list of Persions.

public class Student {
    private String name;
    private String school;
    private int age;

    public Student(String name, String school, int age) {
        this.name = name;
        this.school = school;
        this.age = age;
    }

    // getters/setters should come here

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", school='" + school + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Person {
    private String fullName;
    private int age;

    public Person(String fullName, int age) {
        this.fullName = fullName;
        this.age = age;
    }

    //getters/setters should come here

    @Override
    public String toString() {
        return "Person{" +
                "fullName='" + fullName + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

In this article, I'm going to use functional interface call Funcation to achieve this.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class StudentApplication {
    public static void main(String[] args) {
        Function<Student, Person> functionStuToPer = student -> new Person(student.getName(), student.getAge());

        List<Student> students = Arrays.asList(
                new Student("Tharanga", "UOC", 22),
                new Student("Ruwan", "UOM", 24),
                new Student("Ruvini", "UOK", 20),
                new Student("Randika", "TOUC", 25),
                new Student("Amara", "UOR", 23)
        );

        List<Person> persons = convertStudentListToPerson(students, functionStuToPer);
        persons.forEach(System.out::println);

    }

    private static List<Person> convertStudentListToPerson(List<Student> students, Function<Student, Person> functions) {
        List<Person> persons = new ArrayList<>();
        for (Student student: students) {
            persons.add(functions.apply(student));
        }
        return persons;
    }
}


Enjoy...!!

Lambda (Java 8) - How to sort and filter array

In this article, I'm going to explain about the way we can sort and filter an array using lambda expressions.

TASK 1

We will assume that, we have a list of students as follows:
 List<Student> students = Arrays.asList(
         new Student("Tharanga", "UOC", 22),
         new Student("Ruwan", "UOM", 24),
         new Student("Ruvini", "UOK", 20),
         new Student("Randika", "TOUC", 25),
         new Student("Amara", "UOR", 23)
);

In this scenario, we will assume that we have to sort the students by name:

Initially, how we cater this without lambda expression:
Collections.sort(students, new Comparator<Student>() {
       @Override
       public int compare(Student o1, Student o2) {
           return o1.getName().compareTo(o2.getName());
       }
});

Now will cater this requirement with lambda expressions.
 Collections.sort(students, (o1, o2) -> o1.getName().compareTo(o2.getName()));

Note: Since 'Comparator' interface is a functional interface we can sort the object list as above.

TASK 2

In here, we will assume that we need to filter the students, name starting with 'R'

Without lambda expression we can achieve this as below.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class StudentApplication {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                new Student("Tharanga", "UOC", 22),
                new Student("Ruwan", "UOM", 24),
                new Student("Ruvini", "UOK", 20),
                new Student("Randika", "TOUC", 25),
                new Student("Amara", "UOR", 23)
        );

        Collections.sort(students, (o1, o2) -> o1.getName().compareTo(o2.getName()));

        printConditionally(students, new Condition() {
            @Override
            public boolean test(Student student) {
                return student.getName().startsWith("R");
            }
        });

    }

    private static void printConditionally(List<Student> students, Condition condition) {
        for (Student student: students) {
            if(condition.test(student)) {
                System.out.println(student);
            }
        }
    }
}

interface Condition {
    boolean test(Student student);
} 

How we achieve this using lambda expression.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

public class StudentApplication {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                new Student("Tharanga", "UOC", 22),
                new Student("Ruwan", "UOM", 24),
                new Student("Ruvini", "UOK", 20),
                new Student("Randika", "TOUC", 25),
                new Student("Amara", "UOR", 23)
        );

        Collections.sort(students, (o1, o2) -> o1.getName().compareTo(o2.getName()));

        printConditionally(students, student -> student.getName().startsWith("R"));

    }

    private static void printConditionally(List<Student> students, Predicate<Student> predicate) {
        for (Student student: students) {
            if(predicate.test(student)) {
                System.out.println(student);
            }
        }
    }
}

Note: Java 8, OFTB support many functional interfaces such as "Predicate". You can find more on here.

Note: Find more information about funcational interfaces here.

Lambda (Java 8) - Functional Interface

To write a lambda expression, the interface should have only one abstract method. If an interface has more than one abstract method, we cannot write lambda expression.

When we work as a team, someone creates an interface to write a lambda expression. Later, another team member can add another abstract method to that interface to fulfill his requirement. But in this scenario, that change will effect to the lambda expression and it will not work.

To avoid above scenarios, we need to tell specifically, this interface should have only one abstract method.

We have a lovely annotation to cater this requirement as @FunctionalInterface. It restricts the adding more than one abstract method to the interface.

Find the below sample:
@FunctionalInterface
public interface Greeting {
    String perform(String s) ;
}


Enjoy...!!

Lambda (Java 8) - How to use Runnable interface

In this article, I'm going to explain the way we can use lambda to implement the Runnable interface.

General scenario is below:
  
   ...
   Thread myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Printed inside runnable");
            System.out.println(Thread.currentThread().getId());
        }
   });
   myThread.start();
   ...
Below is the code segment, same above implementation with lambda.
   ...
        Thread myLambdaThread = new Thread(() -> {
            System.out.println("printed inside the lambda expression");
            System.out.println("Thread Id: " + Thread.currentThread().getId());
        });

        myLambdaThread.start();
   ...


  • Empty parentheses: because run() method doesn't allow any arguments.
  • If there is more than one line of the implementation, we need to write the implementation inside the curly brackets.


Note: Runable interface only one method call run(), so we can write lambda expression. If there is more than one method declaration inside a interface, we cannot write lambda expression.

Enjoy..!!

Saturday, September 23, 2017

Lambda (Java 8) - Interface Implementation

In this post, I'm going to describe the way, we use lamdba to 'Interface Implementation'.

Find the below steps:

1. Create an interface as below
public interface Greeting {
    void perform() ;
}

2. In lambda, you can implement the perform method as below
Greeting greeting = () -> System.out.println("Hello Greeting");

3. Then finally, you can invoke the perform method as below.
...
Greeting greeting = () -> System.out.println("Hello , Greeting");
greeting.perform();
...
In the above scenario, I used empty parentheses, it is because, it should be similar to the method signature.
For an example, If I declare the perform() as perform(String message), lambda expression should be as below.
Greeting greeting = (message) -> System.out.println("Hello " + message);

Note: Here we don't need to specify the parameter type, java automatically sets the relevant type.

When we have a return type, above sample should change like follows.

public interface Greeting {
    String perform(String message) ;
}
Lambda:
Greeting greeting = (message) -> "Hello " + message;
Then, when we execute the perform method, it returns a string value.

Note: If you have to pass a single parameter, you can remove the parentheses as below
Greeting greeting = message -> "Hello " + message;

Enjoy...!!

Sunday, August 6, 2017

Mule ESB - How to write a simple munit unit-test for a flow

In this post, I'm going to use pretty simple flow to demonstrate the 'munit' test.

For an example, we will assume that we have sub-flow as below
    <sub-flow name="decision-Sub_Flow1">
        <set-variable variableName="country" value="Sri Lanka" doc:name="Variable"/>
    </sub-flow>

In this sub-flow, what we do is, we are creating a flow variable call 'country' and setting the value as 'Sri Lanka'.

Steps to write a munit test for the above scenario.

Right click the 'src/text/munit' folder and New -> MUnit Test. Then you can set a proper name to the text file and then need to select the flow which we are going to test.

It will open-up the test-suite as below
<mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:munit="http://www.mulesoft.org/schema/mule/munit" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/munit http://www.mulesoft.org/schema/mule/munit/current/mule-munit.xsd
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">

    <munit:config name="munit" doc:name="MUnit configuration"/>
    
    <spring:beans>
        <spring:import resource="classpath:demo-munit-test.xml"/>
    </spring:beans>
    
    <munit:test name="SubFlow1-test-suite-decision-Sub_Flow1Test" description="Test">
        <flow-ref name="decision-Sub_Flow1" doc:name="Flow-ref to decision-Sub_Flow1"/>
    </munit:test>
</mule>

In the above test-suite file, we can clearly see that 3 components such as munit-config, spring-beans, and munit-test.
1. munit-config - we are saying that this is a munit config file
2. spring-beans - we are importing the mule app which we are going to write a munit test.
3. munit-test -  the area where we write the test code.

In this example, we are setting the country name and need to check the value whether it is correct of not. So, we can use the 'assert-on-equals' to fulfill this requirement as below
<munit:assert-on-equals expectedValue="#['Sri Lanka']" actualValue="#[flowVars.country]" doc:name="Assert Equals" message="Did not get expected value. expected value is 'Sri Lanka' but received #[flowVars.country]"/>

expectedValue: need to give the expected value in here, in this example it would be 'Sri Lanka'.
actualValue: here we need to give the actual value. we have set the flow variable call country, so, we can access that value as '#[flowVars.country]'
message: if this test fails, what would be the message to print.

After added this final munit test suite as below
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:munit="http://www.mulesoft.org/schema/mule/munit" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/munit http://www.mulesoft.org/schema/mule/munit/current/mule-munit.xsd
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">

    <munit:config name="munit" doc:name="MUnit configuration"/>
    
    <spring:beans>
        <spring:import resource="classpath:demo-munit-test.xml"/>
    </spring:beans>
    
    <munit:test name="SubFlow1-test-suite-decision-Sub_Flow1Test" description="Test">
        <flow-ref name="decision-Sub_Flow1" doc:name="Flow-ref to decision-Sub_Flow1"/>
        <munit:assert-on-equals expectedValue="#['Sri Lanka']" actualValue="#[flowVars.country]" doc:name="Assert Equals" message="Did not get expected value. expected value is 'Sri Lanka' but received #[flowVars.country]"/>
    </munit:test>
</mule>

Saved and 'Run MUnit suite'

You can see the log file as below
===============================================================
===========  Running  SubFlow1-test-suite.xml  test ===========
===============================================================
Running SubFlow1-test-suite-decision-Sub_Flow1Test
SUCCESS - Test SubFlow1-test-suite-decision-Sub_Flow1Test finished Successfully.
INFO  2017-08-06 12:31:02,615 [main] org.mule.construct.FlowConstructLifecycleManager: Stopping flow: demo-munit-testFlow
INFO  2017-08-06 12:31:02,615 [main] org.mule.processor.SedaStageLifecycleManager: Stopping service: demo-munit-testFlow.stage1
INFO  2017-08-06 12:31:02,721 [main] org.mule.construct.FlowConstructLifecycleManager: Stopping flow: decision-Flow
INFO  2017-08-06 12:31:02,722 [main] org.mule.processor.SedaStageLifecycleManager: Stopping service: decision-Flow.stage1
INFO  2017-08-06 12:31:02,921 [main] org.mule.construct.FlowConstructLifecycleManager: Stopping flow: SubFlow1-test-suite-decision-Sub_Flow1Test
INFO  2017-08-06 12:31:02,921 [main] org.mule.processor.SedaStageLifecycleManager: Stopping service: SubFlow1-test-suite-decision-Sub_Flow1Test.stage1
INFO  2017-08-06 12:31:03,123 [main] org.mule.lifecycle.AbstractLifecycleManager: Stopping model: _muleSystemModel
INFO  2017-08-06 12:31:03,153 [main] org.mule.module.http.internal.listener.DefaultHttpListenerConfig: Stopped listener on http://0.0.0.0:8086
INFO  2017-08-06 12:31:03,155 [main] org.mule.util.queue.QueueXaResourceManager: Stopping ResourceManager
INFO  2017-08-06 12:31:03,155 [main] org.mule.util.queue.QueueXaResourceManager: Stopped ResourceManager
Connected to localhost in port 54275
INFO  2017-08-06 12:31:03,269 [Thread-1] org.mule.munit.plugins.coverage.server.MunitCoverageServer: Coverage connection received from localhost - true
INFO  2017-08-06 12:31:03,270 [main] org.mule.lifecycle.AbstractLifecycleManager: Disposing RegistryBroker
INFO  2017-08-06 12:31:03,274 [main] org.mule.construct.FlowConstructLifecycleManager: Disposing flow: demo-munit-testFlow
INFO  2017-08-06 12:31:03,277 [main] org.mule.processor.SedaStageLifecycleManager: Disposing service: demo-munit-testFlow.stage1
INFO  2017-08-06 12:31:03,278 [main] org.mule.construct.FlowConstructLifecycleManager: Disposing flow: decision-Flow
INFO  2017-08-06 12:31:03,278 [main] org.mule.processor.SedaStageLifecycleManager: Disposing service: decision-Flow.stage1
INFO  2017-08-06 12:31:03,278 [main] org.mule.construct.FlowConstructLifecycleManager: Disposing flow: SubFlow1-test-suite-decision-Sub_Flow1Test
INFO  2017-08-06 12:31:03,278 [main] org.mule.processor.SedaStageLifecycleManager: Disposing service: SubFlow1-test-suite-decision-Sub_Flow1Test.stage1
INFO  2017-08-06 12:31:03,280 [main] org.mule.lifecycle.AbstractLifecycleManager: Disposing model: _muleSystemModel
[org.mule.munit.remote.CoverageManager]accumulating report
[org.mule.munit.remote.CoverageManager]report is not null
INFO  2017-08-06 12:31:03,297 [Thread-1] org.mule.munit.plugins.coverage.server.MunitCoverageServer: Waiting for coverage connection 
INFO  2017-08-06 12:31:03,403 [main] org.mule.munit.runner.spring.config.MunitApplicationContext: Closing org.mule.munit.runner.spring.config.MunitApplicationContext@553f1d75: startup date [Sun Aug 06 12:30:57 IST 2017]; root of context hierarchy
INFO  2017-08-06 12:31:03,590 [main] org.mule.DefaultMuleContext: 
**********************************************************************
* Mule Context shut down normally on: 8/6/17 12:31 PM                *
* Server was up for: 0 days, 0 hours, 0 mins, 1.386 sec              *
**********************************************************************

===================================================================================
Number of tests run: 1 - Failed: 0 - Errors: 0 - Skipped: 0 - Time elapsed: 0.185ms
===================================================================================

Enjoy..!!