Wednesday, 21 September 2016

Java Preferences API tutorial

Suppose you are developing a desktop application. At the time of installing the application, you generally ask user for the some of the options like, where to install the application, where to store log files, configuration files etc., User supply this information only once, application has to remember this information. Whenever application restarts, it shouldn’t ask this information every time.

Ideally most of the applications store the installation path in system environment variables. Configuration files, log files location are stored in property files. One disadvantage of this is, you need to read the installation path from system environment variables, and load the property files when the application reloads.

There is another better way to handle this
Java provides Preferences API to address this real time issue. Preferences API works like Properties API, but it stores the information in System persistence store like flat files, OS-specific registries, directory servers and SQL databases etc.,  Whenever your application restarts, you can get the data from this persistence store in easy way.

Let me demonstrate with an example.
import java.util.prefs.Preferences;

public class PreferenceTest {
 private Preferences prefs;
 private static final String VERSION = "version";
 private static final String NAME = "name";
 private static final String IS_STABLE_RELEASE = "isStableRelease";

 private static void displayPreferences(Preferences prefs) {
  /* Try to read preference before setting */
  int versionNum = prefs.getInt(VERSION, 1);
  String productName = prefs.get(NAME, "MySports");
  boolean isStableRelease = prefs.getBoolean(IS_STABLE_RELEASE, false);

  System.out.println("versionNum : " + versionNum);
  System.out.println("productName : " + productName);
  System.out.println("isStableRelease : " + isStableRelease);
  System.out.println("*****************************");
 }

 public void setPreference() {
  // This will define a node in which the preferences can be stored
  prefs = Preferences.userRoot().node(this.getClass().getName());

  displayPreferences(prefs);

  /* Set the Preferences */
  prefs.putInt(VERSION, 123);
  prefs.put(NAME, "MyCityInfo");
  prefs.putBoolean(IS_STABLE_RELEASE, true);

  displayPreferences(prefs);
 }

 public static void main(String[] args) {
  PreferenceTest test = new PreferenceTest();
  test.setPreference();
 }
}

Following are the sample outputs.


On Run1 Output
versionNum : 1
productName : MySports
isStableRelease : false
*****************************
versionNum : 123
productName : MyCityInfo
isStableRelease : true
*****************************

On Run2 Output
versionNum : 123
productName : MyCityInfo
isStableRelease : true
*****************************
versionNum : 123
productName : MyCityInfo
isStableRelease : true
*****************************


On Run3 Output
versionNum : 123
productName : MyCityInfo
isStableRelease : true
*****************************
versionNum : 123
productName : MyCityInfo
isStableRelease : true
*****************************


int versionNum = prefs.getInt(VERSION, 1);
String productName = prefs.get(NAME, "MySports");
boolean isStableRelease = prefs.getBoolean(IS_STABLE_RELEASE, false);

Observe above statements, Preferences class provides gettter methods to get the values associated with given properties. If the property is not exist, the getter method return the second argument.

As I said, Preferences stores the information in persistent store, on first run of the application, it stores the values to persistent storage. For later runs of the application it retrieves the values from this persistence storage. You can see this from outputs of Run 2 and 3.

How to create Preferences object?
There are two ways to create Preferences object.

a. Create User Preference object
Following statement creates User Preference object.

Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
        
b. Create System Preference object
Following statement creates System Preference object.

Preferences prefs = Preferences.systemRoot().node(this.getClass().getName());

Difference between User Preference and System Preference object
Once a preference is stored in a userNode it is not accessible to other users of the system, just like user variables. Whereas system preference are available to all users. font choice, color choice, or preferred window location of an user are stored in User Preferences, whereas Application installation path, application version, any other global information can be stored in system preferences.

How to remove the preference?
Preferences class provides 'remove' method to remove a preference.

Ex:
prefs.remove(VERSION);

How to clear all the preferences?
Preferences class provides 'clear' method to remove all the preferences in this preference node.

Ex:
try {
         prefs.clear();
} catch (BackingStoreException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
}

What is the persistent storage location in Windows?
It is at ‘HKEY_CURRENT_USER\Software\JavaSoft\Prefs’.

Go to Start > Run > type "regedit" > Enter > then browse the key ‘HKEY_CURRENT_USER’, you can able to see the preferences associated with this user.

Reference

Itext: setTextRise: Specify superscript and subscripts

Chunk class provides setTextRise method to set the text displacement relative to the baseline. Positive values rise
the text, negative values lower the text.

public Chunk setTextRise(final float rise)

Following program displays country and their language code as superscript.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 private static List<String> countries = Arrays.asList("India - Assamese", "India - Bengali", "India - English",
   "India - Gujarati", "India - Hindi", "India - Kannada", "India - Konkani", "India - Malayalam",
   "India - Marathi", "India - Oriya", "India - Punjabi", "India - Sanskrit", "India - Tamil",
   "India - Telugu");

 private static List<String> countryCodes = Arrays.asList("as-IN", "bn-IN", "en-IN", "gu-IN", "hi-IN", "kn-IN",
   "kok-IN", "ml-IN", "mr-IN", "or-IN", "pa-IN", "sa-IN", "ta-IN", "te-IN");

 private static Font font = FontFactory.getFont(FontFactory.COURIER, 20, Font.NORMAL, BaseColor.BLACK);
 private static Font superScriptFont = FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC, BaseColor.BLACK);
 private static Font fontHeading = FontFactory.getFont(FontFactory.HELVETICA, 25, Font.BOLD,
   new BaseColor(255, 0, 0));

 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Document document = new Document();

  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("countries.pdf"));
  writer.setInitialLeading(16);

  document.open();

  document.add(new Chunk("Langauage codes in India", fontHeading));
  document.add(Chunk.NEWLINE);
  document.add(Chunk.NEWLINE);

  int counter = 0;
  for (String country : countries) {

   Chunk chunk = new Chunk(country, font);
   document.add(chunk);

   String code = "(" + countryCodes.get(counter) + ")";
   counter++;
   Chunk superScript = new Chunk(code, superScriptFont);
   superScript.setTextRise(6);
   document.add(superScript);

   document.add(Chunk.NEWLINE);
   document.add(Chunk.NEWLINE);
  }

  document.close();

 }
}





Previous                                                 Next                                                 Home

Tuesday, 20 September 2016

Itext: Working with Chunk object

Chunk represents text that is added to the document. Technically chunk is a string with specific font properties.

Chuck class provides following constructors to define a Chunk instance.

public Chunk()
public Chunk(final Chunk ck)
public Chunk(final String content)
public Chunk(final String content, final Font font)
public Chunk(final char c)
public Chunk(final char c, final Font font)
public Chunk(final Image image, final float offsetX, final float offsetY)
public Chunk(final Image image, final float offsetX, final float offsetY,final boolean changeLeading)
public Chunk(final DrawInterface separator)
public Chunk(final DrawInterface separator, final boolean vertical)

Following step-by-step procedure explains, how to write chunk of data to pdf file.

Step 1: Define Document instance.
Document document = new Document();

Step 2: Get PdfWriter instance and set leading.
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("countries.pdf"));
writer.setInitialLeading(16);

‘writer.setInitialLeading(16)’  specify the space between two lines. If you comment this line, all the text is written on same line.

Step 3: Define font object.
Font font = FontFactory.getFont(FontFactory.COURIER, 20, Font.NORMAL, BaseColor.BLACK);

Step 4: Define Chunk instance.
Chunk chunk = new Chunk("data", font);

Step 5: Write the chunk to the document.
document.add(chunk);
document.add(Chunk.NEWLINE);

Step 6: After adding the data, close the document.
document.close();


Following example writes list of countries to the pdf document ‘countries.pdf’ using Chuck.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 private static List<String> countries = Arrays.asList("Afghanistan", "Armenia", "Azerbaijan", "Bahrain",
   "Bangladesh", "Bhutan", "Brunei", "Cambodia", "China", "Cyprus", "Georgia", "India", "Indonesia", "Iran",
   "Iraq", "Israel", "Japan", "Jordan", "Kazakhstan", "Kuwait", "Kyrgyzstan", "Laos", "Lebanon", "Malaysia",
   "Maldives", "Mongolia", "Myanmar (Burma)", "Nepal", "North Korea", "Oman", "Pakistan", "Palestine",
   "Philippines", "Qatar", "Russia", "Saudi Arabia", "Singapore", "South Korea", "Sri Lanka", "Syria",
   "Taiwan", "Tajikistan", "Thailand", "Timor-Leste", "Turkey", "Turkmenistan", "United Arab Emirates (UAE)",
   "Uzbekistan", "Vietnam", "Yemen");

 private static Font font = FontFactory.getFont(FontFactory.COURIER, 20, Font.NORMAL, BaseColor.BLACK);
 private static Font fontHeading = FontFactory.getFont(FontFactory.HELVETICA, 25, Font.BOLD,
   new BaseColor(255, 0, 0));

 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Document document = new Document();

  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("countries.pdf"));
  writer.setInitialLeading(16);

  document.open();

  document.add(new Chunk("List Of Countries in Asia", fontHeading));
  document.add(Chunk.NEWLINE);
  document.add(Chunk.NEWLINE);

  for (String country : countries) {
   Chunk chunk = new Chunk(country, font);
   document.add(chunk);
   document.add(Chunk.NEWLINE);
  }

  document.close();

 }
}



Previous                                                 Next                                                 Home

Monday, 19 September 2016

Itext: Setting pagesize and margins

In my previous posts, I explained how to set pagesize and margins to a Document. Document class provides setPageSize and setMargins methods to set page size and margins.

public boolean setPageSize(Rectangle pageSize)
public boolean setMargins(float marginLeft, float marginRight,float marginTop, float marginBottom)

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Document document = new Document();
  int marginLeft = 36, marginRight = 72, marginTop = 144, marginBottom = 288;

  document.setPageSize(PageSize.A5);
  document.setMargins(marginLeft, marginRight, marginTop, marginBottom);

  PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
  document.open();
  document.add(new Paragraph("Hello World!"));
  document.close();
 }
}



Previous                                                 Next                                                 Home

Sunday, 18 September 2016

Watching a directory for changes in Java

If your application is closely working with files and directories, you may come to a situation, where you need to monitor a directory (or) file for any changes like file updates, deletes, new sub directory creations etc.,

Watch Service API
Java NIO package provides Watch service api to monitor a directory for changes. All you need to do is register your directory with watch service to monitor changes. One great flexibility of watch service is, while registering a directory to watch service, you can specify the events that you are interested in like file creation, file deletion, or file modification.

Following step-by-step procedure explains, how to watch a directory using watch service.

Step 1: Get WatchService instance by using following statement 'FileSystems.getDefault().newWatchService()'.

WatchService watcher = FileSystems.getDefault().newWatchService();

WatchService is an interface, it watch all the registered objects for any changes. For example, you can monitor a directory for all the operations like create, update, delete and rename operations happened on the directory.

Step 2: Register the directory to the WatchService instance to monitor.

Path dir = Paths.get("/Users/harikrishna_gurram");
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

‘register’ method return 'WatchKey', it represents a token representing the registration of a Watchable (Here it is a directory) object with a WatchService.

This key remains valid, until
          a. It is cancelled, explicitly, by invoking its cancel method.
          b. Cancelled implicitly, because the object is no longer accessible,
          c. By closing the watch service using WatchService close method.

A watch key has a state, at the time of creation key is in ready state. When an event is detected then the key is signalled and queued so that it can be retrieved by invoking the watch service's poll() or take methods. Key remains in this state until its reset method is invoked to return the key to the ready state.

What happen if my key is in signalled state and some other event (like creation, deletion (or) updation on directory) on this key?
Events detected while the key is in the signalled state are queued but do not cause the key to be re-queued for retrieval from the watch service. Events are retrieved by invoking the key's {@link #pollEvents pollEvents} method. This method retrieves and removes all events accumulated for the object. When initially created, a watch key has no pending events.

When can I call reset method on watch key?
Make sure ‘reset’ method is only invoked after the events for the object have been processed.

Following table summarizes the methods of WatchKey interface.

Method
Description
boolean isValid()
Return true if the watch key is valid, else false
List<WatchEvent<?>> pollEvents()
Retrieves and removes all pending events for this watch key
boolean reset()
Reset this watch key. If the watch key is in ready state (or) already cancelled, calling this method has no effect.
void cancel()
Cancels the registration with the watch service.
Watchable watchable()
Returns the object for which this watch key was created. This method return the object, even after calling the cancel method.

Step 3: First two steps register the directory to watcher service. It is time for us to retrieve the signaled events. WatchService interface provides take method, which retrieves and removes next watch key, waiting if none are yet present.

WatchKey key = watcher.take();

Step 4: Once you got the signaled WatchKey, you can able to get all the events associated with this watch key by calling ‘pollEvents’ method. pollEvents method retrieves and removes all pending events for this watch key, returning a List of the events that were retrieved.

List<WatchEvent<?>>  pollEvents = key.pollEvents();


Following is the complete working application.

import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WatchDir {

 private final WatchService watcher;
 private final Map<WatchKey, Path> keys;
 private final boolean recursive;
 private boolean trace = false;

 @SuppressWarnings("unchecked")
 static <T> WatchEvent<T> cast(WatchEvent<?> event) {
  return (WatchEvent<T>) event;
 }

 /**
  * Register the given directory with the WatchService
  */
 private void registerDirectory(Path dir) throws IOException {
  WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
  if (trace) {
   Path prev = keys.get(key);
   if (prev == null) {
    System.out.format("register: %s\n", dir);
   } else {
    if (!dir.equals(prev)) {
     System.out.format("update: %s -> %s\n", prev, dir);
    }
   }
  }
  keys.put(key, dir);
 }

 /**
  * Register the given directory, and all its sub-directories, with the
  * WatchService.
  */
 private void registerDirectoryTree(final Path start) throws IOException {
  // register directory and sub-directories
  Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
   @Override
   public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    registerDirectory(dir);
    return FileVisitResult.CONTINUE;
   }
  });
 }

 /**
  * Creates a WatchService and registers the given directory
  */
 WatchDir(Path dir, boolean recursive) throws IOException {
  this.watcher = FileSystems.getDefault().newWatchService();
  this.keys = new HashMap<WatchKey, Path>();
  this.recursive = recursive;

  if (recursive) {
   registerDirectoryTree(dir);
  } else {
   registerDirectory(dir);
  }

  // enable trace after initial registration
  this.trace = true;
 }

 /**
  * Process all events for keys queued to the watcher
  */
 void startService() {
  for (;;) {

   // wait for key to be signalled
   WatchKey key;
   try {
    key = watcher.take();
   } catch (InterruptedException x) {
    return;
   }

   Path dir = keys.get(key);
   if (dir == null) {
    System.err.println("WatchKey not recognized!!");
    continue;
   }

   List<WatchEvent<?>> pollEvents = key.pollEvents();

   for (WatchEvent<?> event : pollEvents) {
    WatchEvent.Kind kind = event.kind();

    // TBD - provide example of how OVERFLOW event is handled
    if (kind == OVERFLOW) {
     continue;
    }

    // Context for directory entry event is the file name of entry
    WatchEvent<Path> ev = cast(event);
    Path name = ev.context();
    Path child = dir.resolve(name);

    System.out.println("event.kind().name() = " + event.kind().name());
    System.out.println("child : " + child);

    // if directory is created, and watching recursively, then
    // register it and its sub-directories
    if (recursive && (kind == ENTRY_CREATE)) {
     try {
      if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
       registerDirectoryTree(child);
      }
     } catch (IOException x) {
      // ignore to keep sample readbale
     }
    } else if (kind == ENTRY_CREATE) {
     // Created Event handling
    } else if (kind == ENTRY_DELETE) {
     // Write code for entry delete
    } else if (kind == ENTRY_MODIFY) {
     // Write code for entry modify
    } else if (kind == OVERFLOW) {
     // Write code for overflow condition
    } else {
     // Do nothing
    }
   }

   // reset key and remove from set if directory no longer accessible
   boolean valid = key.reset();
   if (!valid) {
    keys.remove(key);

    // all directories are inaccessible
    if (keys.isEmpty()) {
     break;
    }
   }
  }
 }

 static void usage() {
  System.err.println("usage: java WatchDir [-r] dir");
  System.exit(-1);
 }

 public static void main(String[] args) throws IOException {
  // parse arguments

  if (args.length == 0 || args.length > 2) { 
   usage(); 
  }

  boolean recursive = false;
  int dirArg = 0;
  if (args[0].equals("-r")) {
   if (args.length < 2) {
    usage();
   }
   recursive = true;
   dirArg++;
  }

  // register directory and process its events
  Path dir = Paths.get(args[dirArg]);
  new WatchDir(dir, recursive).startService();
 }
}

Sample Output
C:>java WatchDir -r C:\\Users\\Documents\\testing
event.kind().name() = ENTRY_DELETE
child : C:\Users\Documents\testing\1\2\a.txt
event.kind().name() = ENTRY_MODIFY
child : C:\Users\Documents\testing\1\2




Previous                                                 Next                                                 Home