Social Icons

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

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
  "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 = 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());
} Download the Eclipse project

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

Install OwnCloud 8 with Nginx and MySql on Raspberry Pi

This article has been long due from our side since OwnCloud 8 has been released, the product is pretty stable and popular now with the latest stable release of version 8.1.1

Like previous iterations, keeping in mind the small footprint and power of Raspberry Pi we would be using following components:
  • Nginx (as Webserver instead of Apache, as it would be faster)
  • MySql
  • Php 5
So without much ado, let get straight into Business...

Step 1.
Update the repositories
sudo apt-get update

Step 2.
Install MySql
sudo apt-get install mysql-server

Enter a password for root account when prompted, and do remember it :)

Step 3.
Let's now configure the mysql so that it runs better on our tiny resource tight Raspberry Pi
Backup existing config
sudo mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak

Use a suitable config for Raspberry Pi
sudo cp /usr/share/doc/mysql-server-5.5/examples/my-small.cnf /etc/mysql/my.cnf

Edit the config file
sudo nano /etc/mysql/my.cnf

Find the [mysqld] section of the file and place the following line in it:
query_cache_size = 8M

Step 4.
Now we will connect to the database and created required db objects and users
mysql -u root -p

Execute the following at MySql prompt (change the fields in red as per your setup)
CREATE USER techjawab@localhost IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON owncloud.* TO techjawab@localhost;

Step 5.
Install Php5 and related libraries
sudo apt-get install php5-mysql openssl ssl-cert php5-cli php5-common php5-cgi php-pear php-apc curl libapr1 libtool php5-curl libcurl4-openssl-dev php-xml-parser php5-dev php5-gd memcached php5-memcache

Step 6.
Install Nginx
sudo apt-get install php5-fpm nginx

Step 7.
Install and configure OwnCloud
Create directories required for owncloud
sudo mkdir -p /var/www/owncloud
cd /var/www/

Download OwnCloud and set permissions
sudo wget
sudo tar -xvf owncloud-8.1.1.tar.bz2
sudo chown -R www-data:www-data /var/www

Create SSL certificates for https connection
sudo mkdir -p /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /etc/nginx/ssl/owncloud.key -out /etc/nginx/ssl/owncloud.crt

Configure owncloud
Edit the below file and copy - paste the config given below
Note:  Remember to edit your domain name or ip under "server_name" field both for http and https
sudo nano /etc/nginx/sites-available/owncloud

Enabling owncloud settings
sudo ln -s /etc/nginx/sites-available/owncloud /etc/nginx/sites-enabled/owncloud
sudo unlink /etc/nginx/sites-enabled/default

Configure Php FastCGI Process Manager
sudo nano /etc/php5/fpm/php.ini

Set the following values accordingly in the config file, change value for upload directory according to your setup

default_charset = "UTF-8"
upload_max_filesize = 10G
post_max_size = 10G
upload_tmp_dir = /mnt/usbstorage/owncloud/tmp
max_input_time = 360000
#The maximum time in seconds a script is allowed to parse input data.
max_execution_time = 360000
memory_limit = 512M

Restart the services
sudo service nginx restart
sudo service php5-fpm restart

Create directories for owncloud on your mounted external storage
sudo mkdir -p /media/NASDRIVE/owncloud
sudo chown -R www-data:www-data /media/NASDRIVE/owncloud

sudo mkdir -p /media/NASDRIVE/owncloud/tmp
sudo chown -R www-data:www-data /media/NASDRIVE/owncloud/tmp

Step 8.
Open Browser and browse to your domain name or ip address

You would need to setup the following:
  • setup admin username / password
  • Provide the owncloud storage path created above
  • Provide database name, username and password created in step 4, and click "Finish setup"

Viola, you have your "own"cloud up and running now...

Install MiniDLNA on Raspberry Pi

*These steps works both on Raspbian Wheezy & Jessie*

Install MiniDLNA
sudo apt-get update
sudo apt-get install minidlna

Open and edit MiniDLNA's configuration file
sudo vi /etc/minidlna.conf

Configure your media directory

Adding "V," as prefix to the path will restrict the media dir to video content type.
Similarly, "A," for Audio and "P," for pictures respectively.

Set a name for your DLNA servers, this will show up on clients

Set inotify to yes to let MiniDLNA automatically pick up file / media changes

Un-comment the line

Add minidlna user to pi group
sudo usermod -a -G pi minidlna

Force Restart MiniDLNA to let it build it's media database
sudo service minidlna force-reload

Check the logs at /var/logs (check if your media library is being indexed)
tail -f  minidlna.log

Viola... Your video collection should soon  show up on your DLNA devices :)

Internet Ban? Bypass blockade in easy steps

Time and again several governments and states have tried to execute their dictatorship by imposing ban on contents on internet. Some time it has been a blanket ban on a long list of file sharing sites, some times it has been discussion forums, some times popular video sharing sites like vimeo, or simple paste tool like pastebin.

And probably such problems will be more on rise in countries like India, China, Pakistan, Middle Eastern countries and many others where there is hardly any Data Protection laws and it's just the whimsical decision of government that they can bring down any website any time for any period of time.

Fortunately for us, that's not the end of the road. Internet was always free and open and that's how it is meant to be. To accept the right and reject the wrong should rest in the hands of common netizens, no corporates or governments should dictate it.

To cut the long story short, If you are unable to browse your favorite discussion forum, or unable to see short film video posted by your film-maker friend, or unable to see a porn clip (if it's not illegal to see in your country) you badly wanted to, then here is the solution.

While there are many options to bypass around such blockades, I am here to advice about two simple solutions which any layman without any techie background can opt for.
  1. Tor Browser
  2. VPN
Each have their merits and demerits as discussed below:

Tor Browser
You can download the Tor Browser and start using it for anonymous browsing, however the browser does not supports 3rd party plugins like Adobe Flash, etc. Thus any Flash enabled video sites might not give you full experience. To know more how tor works you can read here

Virtual Private Network is the ultimate solution where in you can prevent your ISP and Government from snooping into your data packets (well make sure it's a good VPN service with repute) and bypass all blockades and also hide your real identity on the web. This can also allow you to make VOIP calls where it is otherwise blocked. VPNs can be free or paid but it is always recommended to go for a reputed paid VPN service which does not logs your activity. There are lot of reviews over the Internet to guide you to make an informed decision.

As a suggestion (with no responsibility whatsoever) we do recommend the following VPNs
 You can start with a Free service of CyberGhost to get a feel and gradually choose as you opt to. It simple simply go to their website and download their VPN client, install the same on your device (PC / Mac / Linux / iOS / Android) and start using web anonymously.
This is a basic guide for anonymous web surfing and the author / publisher of this article does not encourage you to do anything illegal as per the laws of your state. Happy Surfing...