Social Icons

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

How to use Java 7 File Watcher Service for polling File system

Java 7 have brought in Watcher Service API in its NIO (Non-blocking IO) package which allows us to monitor a particular folder for any changes like addition, modification, deletion of files. This very useful when you want to trigger some file processing action or alike on any file change event. Thus we do not need to use any thrid party API any more and is fairly simple to work with.

So let's dive in...
First create an object of WatchService

WatchService watchFolder = pathToFolder.getFileSystem().newWatchService();

Create WatchQueueReader object, and create a thread with it.
You can actually this way make your application monitor different directories for file changes, and run the operation is separate threads.

WatchQueueReader watchQueueReader = new WatchQueueReader(watchFolder);
Thread th1 = new Thread(watchQueueReader, "FILE_INPUT_DIRECTORY");
th1.start();


Register this WatchService for a given directory like the following:

Path pathToFolder = Paths.get("c:/some_file_path_to_monitor");
pathToFolder.register(watchFolder, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

Note: If you want to monitor only creation, or modify then register only with those Watch event kinds.

The Watch Service API does not allow registering an individual file. We’ll get a java.nio.file.NotDirectoryException if trying to do so.

WatchKey key = watchService.take();
Thread t = Thread.currentThread();

Next, write an infinite loop to repeatedly poll the events fired by the watcher and process the events accordingly.

while (key != null && !mStop) {
    for (WatchEvent event : key.pollEvents()) {
        if (t.getName().equals("FILE_INPUT_DIRECTORY")) {
            // Process the file
            log.info("FILE_INPUT_DIRECTORY: " +  event.context());
            /**
             *  do something here with the file
             *  event.context() will give the file name
             *  event.kind() will tell what kind of event occurred
             */
         }
         key.reset();
         key = watchService.take();
    }
}

It’s very important that the key must be reset after the events have been processed. If not, the key won’t receive further events.

Often, you might have a need to pick-up all files in the monitored folder which might have accumulated while your application was not running. Since, WatchService only picks up the events, so we can simulate the event just by modifying the LastModified with the same value as it is now. This would ideally trigger the MODIFY event, without actually making any change to the metadata value.

private static void triggerWatchService(File dir) throws IOException {
 File[] dirContent = dir.listFiles();
 for (File f : dirContent) {
  if (!f.isDirectory()) {
   log.debug("Processing existing file: " + f.getName());
   f.setLastModified(f.lastModified());
  }
 }
}

FolderWatcher.zip Download the Eclipse project FolderWatcher.zip

Text Encryption & Decryption using Java


The need of encryption is very very common in today's world. Many-a-times one needs to encrypt some text, password or even some paragraphs at times for respective needs. Encryption gives you certain peace of mind that eavesdroppers won't be able to read the content, and it can only be deciphered by someone who has the key.

Let's look at a simple yet robust working solution of a text / string encryption & decryption algorithm.

You need to define a key for the encryption. AES only supports key sizes of 16, 24 or 32 bytes.

Following is the code for encryption of the input text

And here goes the logic for decryption of encrypted text

Note: The key is required both for encryption and decryption

Encrypt_Decrypt.zipDownload the Eclipse project Encrypt_Decrypt.zip

Install Java SE on Raspberry Pi without complete upgrade


As you must be aware the latest versions of Raspbian OS comes pre-installed with Java VM. However enthusiasts who are already running their Raspbian installation from some prior version and have their perfect environment set might not like the idea of doing a clean install of the Raspbian OS again.

To solve this, there is a simple way to get the latest Java VM installed on your Raspbian without any hassle and start exploring the power of Java on your RasPi.

Step. 1
pi@raspberrypi ~ $ sudo apt-get update

Step. 2
pi@raspberrypi ~ $ sudo apt-get install oracle-java7-jdk
(Note: oracle-java8-jdk is also available)

Verify the installation:
pi@raspberrypi ~ $ java -version
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) Client VM (build 24.0-b56, mixed mode)

You should see the version details of your installed Java VM.

Spring 3 - Complete Bean & Annotation based configuration, No XMLs used

With the advent of Spring 3 there has been an widespread use of annotations and annotations based configurations. It brings down the development time and also has it's own advantages & disadvantages.

However there are very few examples online which shows a complete Spring MVC application configured using ONLY bean based configuration. In most of the cases you will find atleast the dispatcher-servlet.xml lying around even in a Bean based configuration.

So, let's see how can we get rid of any Spring related XML files for configuration and develop a Spring MVC application. First let's take a look at the application's entry point and the only XML file of any standard web application web.xml:




Note that we have configured ContextLoaderListener to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext and added contextConfigLocation as the Beans Class which will contain the spring configuration.

Now, let's see the the Bean based configuration class:



You don't have to declare your bean in your context file in this bean based config, instead Annotate the class with @Component, @Service, @Controller or @Repository and our @ComponentScan annotation in BeansConfig.java will automatically register them in Spring context. Your Bean configuration class should be annotated with @Configuration annotation.

Make sure you mark Service classes with @Service annotation and not with @Component as the former is the more specialized annotation for Service components. Similarly, @Controller for Controller components and @Repository for DAO components in your application.


The controller below shows also the use of @Autowired annotation for auto-wiring and injecting OfficeAddress into Employee bean.

Download


Download the Eclipse project SpringDIAndAutowired.zip




Identify from which JAR file the class was loaded

It's a very common situation that Java developers, especially web developers face in day to day work field that a class with same name exists in two different JAR files even sometimes with same package name. A classic example is logger classes or servlet / jsp related classes, or when libraries from server gets loaded first ignoring the application's library set.

While we all know the remedy is to remove the conflicting JAR file but it becomes cumbersome to determine from what location the offending class is getting loaded.

To solve this we present you the simple java code which you can run as a JSP page, or a Servlet or standalone code by modifying accordingly and determine the path as well as the JAR from which the offending version of the class is getting loaded.



Note that you just need to edit the fully qualified class name to get the details.
The code is pretty self explanatory and hope doesn't needs any further explanation.


Thank you for visiting techjawab.com, feel free to post your comments back!

Dynamic menu with Sitemesh

It's always a matter of concern for web developers to keep the page design constant across all of the application. Using frames is a dead idea, so what's left including your header, navigation and footer jsp on each and every page ?

Well there is something better than that, Sitemesh. It allows you to keep your page design consistent or even maintaining different UI styles for different parts of the site.


But a major problem which Sitemesh users often come across is to implement a dynamic menu / navigation, like in a situation where menus in your application changes based on the 'role' of the logged in user. The solution for the same is here implemented in a simple JSP / Servlet code.


Dynamic menu with Sitemesh


To keep a dynamic approach, I have kept Menu texts and links in a properties file.

Downloads:
sitemesh-2.4.2.jar - http://wiki.sitemesh.org/display/sitemesh/Download

Logic:
The basic idea is once the user logs into the application, the user's role is stored into the application session. The sitemesh reads the user role and applies appropriate navigation menus based on the role. Secondly to highlight the menu item which is currently selected a meta tag is placed on each page just to denote under when menu item it belongs. The sitemesh decorator reads the same meta tag and applies a different css to it's menu item.


web.xml - Configure the sitemesh filter to intercept request and send for decoration



decorators.xml - sitemesh config file for defining decorators



main.jsp - decorator, the place where you design the layout of your design and implement the dynamic logic. The code below is pretty self-explainatory with the logic stated above.



Download




Download the MyEclipse / Eclipse project SiteMeshDynamicMenu.zip




Hope these tips helped you, don't forget to leave your comments here.