Sunday, November 15, 2015

File Watcher Job Using Apache Common IO

File Watcher Jobs in Java using Apache Commons (JDK1.6)

What is the Objective: we want to invoke something based on some event in our file system, event could be

1. Directory creation/deletion/movement
2. File Creation/deletion/movement

What we are saying here we want to do some activity based on some event happening in the file system, the first thing should ring in our mind, are we looking for some listener ? – Which can listen to the events and respond accordingly.

Yes, that is what I am going to explain you here, the Listener provided by Apache Common library:

org.apache.commons.io.monitor.FileAlterationListener

(Please download the commons.io jars in case you don’t have from here)  

For any Listener three things required:
1.       Listener itself.
2.     The Observer – which will be configured to observe on certain path and based on the event happening in that path, will call the corresponding method of the listener. Apache observer is org.apache.commons.io.monitor.FileAlterationObserver.

3.       The last, one active thread which will have this observer running inside it for any event – Apache active thread is  
org.apache.commons.io.monitor.FileAlterationMonitor

Let’s explore our Apache listener:

What should be the program flow:
1.       Create an implementation for Listener and implement event methods, whichever required
2.       Create and Observer to observer on some path – let’s say (“/temp/”or C:/temp/)
3.       Register our listener with this observer.
4.       Start a Thread and register our observer with it (we call it Monitor)
5.       Done

Code:

1.      Listener:

import java.io.File;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;


public class FileWatcherListenerUsingApache implements FileAlterationListener {

      @Override
      public void onDirectoryChange(File arg0) {
            System.out.println("Directory changed " + arg0.getName() );
           
      }

      @Override
      public void onDirectoryCreate(File arg0) {
            System.out.println("Directory created " + arg0.getName() );
           
      }

      @Override
      public void onDirectoryDelete(File arg0) {
            System.out.println("Directory deleted " + arg0.getName() );
           
      }

      @Override
      public void onFileChange(File arg0) {
            System.out.println("File changed: " + arg0.getName() );
           
      }

      @Override
      public void onFileCreate(File arg0) {
            System.out.println("File craeted " + arg0.getName() );
           
      }

      @Override
      public void onFileDelete(File arg0) {
            System.out.println("File deleted " + arg0.getName() );
           
      }

      @Override
      public void onStart(FileAlterationObserver arg0) {
            System.out.println("Observation started for " + arg0.getDirectory().getAbsolutePath() );
           
      }

      @Override
      public void onStop(FileAlterationObserver arg0) {
            System.out.println("Observation stopped for " + arg0.getDirectory().getAbsolutePath() );
           
      }

}



2.       Observer, Monitor:

import java.io.File;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

/***
 * It is used to monitor file system activities on /temp/ directory
 * 
 *
 * @author Sushil
 *
 */
public class FileWatcherObserverUsingApache {

      public static void main(String[] args) throws Exception {
           
            //create file to watch on
            File dirToWatch=new File("/temp/");
           
            // create alteration observer on file
            FileAlterationObserver observer=new FileAlterationObserver(dirToWatch);
           
            // register listener with observer
            observer.addListener(new FileWatcherListenerUsingApache());
           
            // create Monitor ( Thread )
            final FileAlterationMonitor monitor=new FileAlterationMonitor();
           
            // Register Observer with Monitor
            monitor.addObserver(observer);
           
            // Start thread to observe on /temp
            System.out.println("Observation started on :"+ dirToWatch.getAbsolutePath());
            monitor.start();
           
            //
            System.out.println("PRESS CNTL+C to stop");
           
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                  try {
                              monitor.stop();
                        } catch (Exception e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                        }
                }
             });
      }

}


Output:

1.       When started:



2.       Created a new empty file in temp - sushil.txt




3.       Create a directory: sushil




4.       Moved Sushil.txt into sushil directory:




Sunday, October 18, 2015

Mockito Spy

Org.mockito.Spy
Now here comes the situation, the Employee class has one method, and when that method will be called not mockingly but really and call will return the value, we have to use that value to test our real method.

Did you get anything out of my above sentence, if no then read below:
Our Employee.getSummary() method requires address, which can’t be mocked or it requires to call real getTotalMarks() method of Employee class to supply marks during testing.
So what do you want here mocking 1 method, while calling come real method- it means you want to do partial mocking. We call this partial mocking spying as well.
Here is a basic example:
Employee.java

/**
 *
 */
package com.sushil.mockito;

/**
 * @author Sushil
 *
 */
public class Employee {
     String name;
     int  totalMarks;
     String address;
    
     public String getName() {
              return name;
     }
     public void setName(String name) {
              this.name = name;
     }
     public int getTotalMarks() {
              System.out.println("get total marks called");
              return totalMarks;
     }
     public void setTotalMarks(int totalMarks) {
              this.totalMarks = totalMarks;
     }
     public String getAddress() {
              return address;
     }
     public void setAddress(String address) {
              this.address = address;
     }
    
     public String getSummary(String name, int marks, String address){
              System.out.println(name + " from " + address + " has recieved " + marks + " marks. " );
              return "hello I am from real class";
     }
     @Override
     public String toString() {
              return "Employee [name=" + name + ", totalMarks=" + totalMarks
                                  + ", address=" + address + "]";
     }
    
}



Test Class:
     EmployeeTest.java


/**
 *
 */
package com.sushil.mockito;

import static org.junit.Assert.fail;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * @author Sushil
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class EmployeeTest {

     @Mock
     Employee emp, spy;
    
     @Before
     public void setUp() throws Exception {
              MockitoAnnotations.initMocks(emp);
              Employee emp1=new Employee();
              emp1.setAddress("H");
              emp1.setName("K");
              emp1.setTotalMarks(20);
              spy=spy(emp1);
              int marks=spy.getTotalMarks();
       doReturn("HELLO").when(spy).getSummary(anyString(),eq(marks), anyString());
     }

     /**
      * @throws java.lang.Exception
      */
     @After
     public void tearDown() throws Exception {
     }

     @Test
     public void test() {
                  System.out.println(spy.getSummary(“Output - 1”));
                  System.out.println(spy.getSummary("L",10,"Y"));
                  System.out.println(spy.getSummary(“Output - 2”));
               System.out.println(spy.getSummary("L",20,"Y"));
     }

}


OUTPUT:


 //the real get()  method of EMPLOYEE class is called due to spy.getTotalMarks()
get total marks called


//as we have not mocked method for marks equal to 10, it calls real getSummary() method.
Output – 1  
L from Y has received 10 marks.
hello I am from real class

//as we have mocked method for marks equal to 20, it returns the result mocked.
Output - 2
HELLO

Mock it i.e. Mockito

What is Mockito ?
Now a days, we are running in sprints. Someone is having shorter sprint ( 1 week… why they call it Sprint, rename it to slow run) and someone is having longer Sprint ( 3-4 weeks, ha ha… what do you thought, will they allow you to slow walk).
Gone are the days when developer has to wait for BRD to get completed and he will get time to analyze it and then start writing code with all interaction also well defined. In the world of sprint you have to shed your weight daily and have to make sure that it will be not having impact on your health as well.
Means two things to take care
1.   Shed the weight ( produce some result daily)
2.   Make sure it is sustainable daily.
To make sure it works, we have to test it daily for its sustainability for whole sprint, but how?
We are still waiting for
1.   wheat to be grinded ( network connectivity)
2.   vegetables to be chosen ( database connectivity )
3.   Recipe to be decided ( Team members classes )
Than few wise men, will start saying ‘why not you are assuming/Predicting something, and start sprinting as whole interaction is cooperative, the person who is sprinting behind you has also assumed a lot about you.’
This saying of the wise man, can be summed up in the single sentence –
“please mock all the persons, objects or whatever you require. Predict their behavior and that is the MOCKITO”
Mockito not only allows you to mock the java class, predict its method behavior, it will even allow you to decide what it should do (in mocking world), instead of what it is doing in real world.
Mockito is the third party tool, which can be easily used to assume or predict the behavior of interacting code.
Mockito has many features let’s start with few: