java 7 feature – java watchservice-hello world

java7 introduce a new feature called WatchService. You can now register particular directory in the file system and can trigger any member function based on the event it occurs.

Before the WatchService feature, you need to create a thread continuously watch the file system, and you need to check the last modified time stamp
to get to know what really changed, and maintains the updated files is cumbersome. This will be a boost to lot of file system based operations.

Here is a sample hello world demo demonstrate the File system watch service.

package com.ananth.java7

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.*;

public class JavaWatchServiceDemo {
	private Path path = null;
	private WatchService watchService = null;

	private void initialize() {
		path = Paths.get("/home/ananth/test");  // get the directory which needs to be watched.
		try {
			watchService = FileSystems.getDefault().newWatchService();
			path.register(watchService, ENTRY_CREATE, ENTRY_DELETE,
					ENTRY_MODIFY);   // register the watch service on the path. ENTRY_CREATE-register file create event, ENTRY_DELETE=register the delete event, ENTRY_MODIFY- register the file modified event
		} catch (IOException e) {
			System.out.println("IOException"+ e.getMessage());
		}
	}
/**
 * Once it added to the watch list it will start to monitor the changes on the directory 
 */
	private void doMonitor() {
		WatchKey key = null;
		while(true) {  // important - create an indefinite loop to watch the file system changes.
			try {
				key = watchService.take();
				for (WatchEvent event : key.pollEvents()) {
					Kind kind = event.kind();
					System.out.println("Event on " + event.context().toString() + " is " + kind);
				}
			} catch (InterruptedException e) {
				System.out.println("InterruptedException: "+e.getMessage());
			}
			boolean reset = key.reset();
			if(!reset)
				break;
		}
	}

	public static void main(String[] args) {
		JavaWatchServiceDemo watchservicedemo = new JavaWatchServiceDemo();
		watchservicedemo.initialize();
		watchservicedemo.doMonitor();
	}
}

Advertisements

hello world-java annotations

Java annotation is a good concept to implement while you designing a large application in order to reduce the maintenance overhead. Some of the use cases like,
1. Code generation automatically
2. Initialize some of the variables or your caching system while staring the application.
3. Define the life cycle of your application and make sure your code running after all the life cycle of your framework.

Step 1:
Create an interface and add the code like below.

package com.test;

import java.lang.annotation.*;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FirstAnnotations {
	
}

Note the interface keyword, you should add “@” to mark it as annotation.

Then Let us create an Annotation implementation class like below.

package com.test;
public class AnnoImplementation {
	@FirstAnnotations()	
	public static void callMe() {		
		System.out.println("test");
		
	}

}

while all set all we need to call the annotation like below.

package com.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class CallAnno {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			for(Method m: Class.forName("com.test.AnnoImplementation").getMethods()) {
				
				
				
				if(m.isAnnotationPresent(FirstAnnotations.class)) {
					//System.out.println("called");
					//m.invoke(null);
					try {
						System.out.println(m.getName());
						m.invoke(null);
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}