Thursday, July 25, 2013

Dynamically generating a properties file and Reading a properties file in Java using Properties java class


To generate a properties file setting the key-value attributes:

The code is self explanatory 

Code snippet example #1: 

 Below is the code which will generate the properties file named, dbdetail.properties.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
 
public class GenerateProperties
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
      //set the properties value
      prop.setProperty("databasename", "dbname");
      prop.setProperty("dbuserid", "userId");
      prop.setProperty("dbpassword", "passwrd");
 
      //save properties to project root folder
      prop.store(new FileOutputStream("dbdetail.properties"), null);
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
    }
}
Output:
a file dbdetail.properties will be created with below content

#Thu Jul 25 10:09:07 PDT 2013
dbuserid=userId
databasename=dbname
dbpassword=passwrd


To read the properties file using Properties object of java

Code snippet example #2:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
 
public class ReadProperties
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file
      prop.load(new FileInputStream("dbdetails.properties"));
 
               //get the property value and print it out
                System.out.println(prop.getProperty("databasename"));
      System.out.println(prop.getProperty("dbuserid"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}
Note: be sure that the location of the properties file is within the classpath.
Output will be :

dbname
userId
passwrd

There are other scenarios to load the properties file:
Instead of specifying the location of the properties file, if we include the properties file in class path we can directly read the file. 
refer to the  (Code snippet example #2), we are using FileInputStream instead we can use getClassLoader() to locate the properties file if its included in the classpath. 

Below is the code to load the properties file when the properties file is within the class path

1. to access the properties file - static way
2. to access the propertied file within non-static way

Below is representation of 1. accessing within a static block
Code snippet example #3

import java.io.FileInputStream;
import java.io.IOException;
import java.utilutil.Properties;
 
public class ReadPropFrmClasspath
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file from class path, inside static method
      prop.load(ReadPropFrmClasspath.class.getClassLoader().getResourceAsStream("dbdetail.properties");));
 
               //get the property value and print it out
                System.out.println(prop.getProperty("databasename"));
      System.out.println(prop.getProperty("dbuserid"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}
Note: 
prop.load(ReadPropFrmClasspath.class.getClassLoader().getResourceAsStream("dbdetail.properties");));
Output:
dbname
userId
passwrd


Below is representation of 2. accessing within a non-static block:

import java.io.FileInputStream;
import java.io.IOException;
import java.utilutil.Properties;
 
public class ReadPoprFrmClassPath2
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file from class path, non-static method
      prop.load(getClass().getClassLoader().getResourceAsStream("dbdetail.properties");));

 
               //get the property value and print it out
                System.out.println(prop.getProperty("database"));
      System.out.println(prop.getProperty("dbuser"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}
Note: 
prop.load(getClass().getClassLoader().getResourceAsStream("dbdetail.properties");));
Output:

dbname
userId
passwrd


To read the properties file we can also use the ResourceBundle objects of java.

It all depends on the situation in the development to use.











Tuesday, July 23, 2013

Spring 3.1+ Profile - using profile in web application development.

SPRING Profiles:

Definition: This is spring framework newest feature (available in spring 3.1 and above versions)
During the development of web application we undergo different environments through out the software development life cycle (SDLC) like development environment, testing environment, production environment, etc.
Assume the database for each environment is different, then it is overhead for the developer to change the information in the configuration file or properties file for database credentials for every environment. If the web-application is developed using spring (3.1 +) profiles comes into picture to rescue us.

Its easy to configure. Let us see how to configure it in spring application.

The spring context file has provision to define profile in beans tag. (i assume you have knowledge about the spring context files).

Example (code snippet of spring-context.xml):

Note: i am using Spring 3.2.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema- 
                                          instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
                                         xmlns:context="http://www.springframework.org/schema/context" 
                               xsi:schemaLocation="http://www.springframework.org/schema/mvc 
                                          http://www.springframework.org/schema/mvc/spring- mvc-3.2.xsd 
                                          http://www.springframework.org/schema/beans 
                                          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd     
                                          http://www.springframework.org/schema/context 
                                          http://www.springframework.org/schema/context/spring-context-3.2.xsd   
                                      >

 <beans profile= "development">
     <bean id = "datasoure" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
                          <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@host:port:dbname" />
<property name="username" value="usrid" />
<property name="password" value="passwrd" />
     </bean>
</beans>
 <beans profile= "test">
     <bean id = "datasoure" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
                          <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@host:port:dbname" />
<property name="username" value="usrid" />
<property name="password" value="passwrd" />
     </bean>
  </beans>
</beans>

The nexted <beans> tag is used here for defining the profile information.

Now we need to tell Spring to take the appropriate database information from this context file, so we will use "spring.profiles.active"
I am using the web.xml servlet.Dispatcher to tell spring to use spring-context.xml file.and we can use the profile value (development or test) as init parameter to fetch the appropriate database information.

Example Code snippet of  web.xml to invoke the specific profile information:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>profilesample</display-name>
        
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring-context.xml</param-value>
</init-param>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>development</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
  <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
         </servlet-mapping>
...
...
..
 </web-app>

The init-pram for the "spring.profile.active" is development which tells spring to use the "development" bean information of spring-context.xml to get the database connection. If you need the test database information to be used in the init-param tag param-value used test.

Info:
The profiles can also be configured using annotation.