StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Saturday, August 30, 2014

Java Properties Example

 August 30, 2014     Java     No comments   

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.
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk