Sunday, August 31, 2014
Handling persistent properties is an important aspect in software design to prevent hard coding values in code. Properties allow the customization of values like username, password, port numbers etc. during run time and provides flexibility to the implementation. Java support simple APIs to handle read and store properties. This article provides an introduction to working with properties in Java.

Java supports the Properties class which extends the Hashtable and hence it is easy to visualize the properties as key and value pairs. Java supports XML property files as well. We will understand the approaches using examples below.

Reading a properties file

This example provides a sample implementation to read a properties file. We create a Properties object and load the properties from an input stream. The properties are now available for the program to read.

Let us consider a simple properties file.

Username=john
Password=smith

Here we read this properties file and access the values.

public static void main(String[] args) {
  try (FileInputStream in = new FileInputStream("resources/example1.properties")) {
    Properties properties = new Properties();
    properties.load(in);
    
    // Get all properties
    Enumeration<?> keys = properties.propertyNames();
    while ( keys.hasMoreElements() ) {
      System.out.println(keys.nextElement());       
    }
    
    // Print the property list for debugging
    properties.list(System.out);
    
    // Get properties with key
    String user = properties.getProperty("Username");
    String pass = properties.getProperty("Password");
    System.out.println(user);
    System.out.println(pass);   
  } catch (IOException e) {
    e.printStackTrace();
  }
}

This program produces the following output.

Username
Password
-- listing properties --
Username=john
Password=smith
john
smith

Writing a properties file

This example provides a sample implementation to store a properties file. We creates a Properties object and associate properties and then write to the output stream to persist.

public static void main(String[] args) {
  try (FileOutputStream out = new FileOutputStream("resources/example7.properties")) {
    Properties properties = new Properties();
    properties.setProperty("Host", "localhost");
    properties.setProperty("Port", "8080");
    properties.store(out, "Example to write a properties file");
  } catch (IOException e) {
    e.printStackTrace();
  }
}

This program writes a file with the following contents.

#Example to write a properties file
#Sun Aug 31 08:04:13 IST 2014
Host=localhost
Port=8080

Reading a XML properties file

Java also supports XML based properties file format. This example provides a sample implementation for reading a XML properties file. Please note the DOCTYPE definition in the properties file.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="Username">John</entry>
<entry key="Password">Smith</entry>
</properties>

Reading this properties file is simple as reading key and value based properties. Java support loadFromXML to handle XML based properties file.

public static void main(String[] args) {
  try (FileInputStream in = new FileInputStream("resources/example2.properties")) {
      Properties properties = new Properties();
      properties.loadFromXML(in);
      
      // Get all properties
      Enumeration<?> keys = properties.propertyNames();
      while ( keys.hasMoreElements() ) {
        System.out.println(keys.nextElement());       
      }
      
      // Print the property list for debugging
      properties.list(System.out);
      
      // Get properties with key
      String user = properties.getProperty("Username");
      String pass = properties.getProperty("Password");
      System.out.println(user);
      System.out.println(pass);   
    } catch (IOException e) {
      e.printStackTrace();
    }
}

Writing a XML properties file

This example provides a sample implementation to write a XML properties file. We creates a Properties object and associate properties and then write to the output stream to persist.

public static void main(String[] args) {
  try (FileOutputStream out = new FileOutputStream("resources/example7.properties")) {
    Properties properties = new Properties();
    properties.setProperty("Host", "localhost");
    properties.setProperty("Port", "8080");
    properties.storeToXML(out, "Example to write a properties file");
  } catch (IOException e) {
    e.printStackTrace();
  }
}

Working with encrypted properties

Sometimes it is necessary to handle sensitive properties and we would need encryption. It is possible to store encrypted properties and read the values using a Java library Jasypt (Java Simplified Encryption).

Download Jasypt and install to your PC. Jasypt provides command line utilities to encrypt and decrypt strings. Let us encrypt some strings and store them in a properties file. Use the Jasypt utility "encrypt.bat" to encrypt strings.

C:\Installs\jasypt-1.9.1\bin>encrypt.bat input=Smith password=sourcetricks

----ENVIRONMENT-----------------

Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.45-b08



----ARGUMENTS-------------------

input: Smith
password: sourcetricks



----OUTPUT----------------------

05r6z1nJsdtqwLkTIyO+xw==

Now create a properties file using the encrypted output. Please note the use ENC wrapper to represent encoded properties.

Username=ENC(OUcamtVFitq8Di0DMd4ZKg==)
Password=ENC(05r6z1nJsdtqwLkTIyO+xw==)
Host=localhost

Now we create an EncryptableProperties object and read the properties file. Please note that we use the same password to decrypt as was used during the encryption process. Jasypt provides several algorithms to customize and secure the encryption and decryption process.

public static void main(String[] args) {
  try (FileInputStream in = new FileInputStream("resources/example5.properties")) {
    
    BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
    textEncryptor.setPassword("sourcetricks");

    Properties properties = new EncryptableProperties(textEncryptor);
    properties.load(in);
    
    // Print the property list for debugging
    properties.list(System.out);
    
    // Get properties with key
    String user = properties.getProperty("Username");
    String pass = properties.getProperty("Password");
    String host = properties.getProperty("Host");
    System.out.println(user);
    System.out.println(pass);
    System.out.println(host);
    
  } catch (IOException e) {
    e.printStackTrace();
  }
}

Continue to read other Java tutorials from here.

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top