Sunday, March 25, 2012

Spring bean scope annotation example

Spring bean instance will be created depend on scope specified on that bean , spring container support five types of scope
  • singleton – Return a single bean instance per Spring IoC container
  • prototype – Return a new bean instance each time when requested
  • request – Return a single bean instance per HTTP request.
  • session – Return a single bean instance per HTTP session.
  • globalSession – Return a single bean instance per global HTTP session.
Spring container default scope is singleton , so you have to be careful before use bean instance . In multi-thread environment , singleton instance must be thread safe to avoid race condition . In that situation you might use prototype scope. Other three scopes are only valid in the context of a web-aware Spring ApplicationContext.
Example
Here is an example to explain difference between singleton and prototype .
1. Singleton Example: Since no bean scope is specified ,default to singleton
package com.example.springscope;

import org.springframework.stereotype.Service;

@Service("userService")
// default scope is Singleton
public class User {
 private Integer id;
 private String userName;

 public int getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
   public String toString(){
    return "[ ID : "+id+" Name :"+userName+"]";
   }
}


Configuration XML : component-scan will allow us to use annotation base bean declaration and enable auto component scan. All beans declared in com.example and its child package will be available in spring context.


 
 


Test example :
package com.example.springscope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "app-config.xml" });
  // retrieve configured instance
  User customerA = (User) context.getBean("userService");
  customerA.setId(1);
  customerA.setUserName("Jeff");
  System.out.println(" Customer Info A:" +customerA);
   // Since Scope is singleton , same instance will be return to caller
  User customerB = (User) context.getBean("userService"); 
  System.out.println(" Customer Info B:" +customerB);
 }

}


Output :
 Customer Info A:[ ID : 1 Name :Jeff]
 Customer Info B:[ ID : 1 Name :Jeff]


In this example Id and name has been set on the customerA but same value is also showing on customerB , because of singleton scope. Spring container will create only one object for singleton scope , that will be return to caller every time.
Prototype Example
If you want new instance every time , you have to use prototype scope .
 package com.example.springscope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("userService")
@Scope("prototype")
public class User {
 private Integer id;
 private String userName;

 public int getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
   public String toString(){
    return "[ ID : "+id+" Name :"+userName+"]";
   }
}

Test Example :
package com.example.springscope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "app-config.xml" });
  // retrieve configured instance
  User customerA = (User) context.getBean("userService");
  customerA.setId(1);
  customerA.setUserName("Jeff");
  System.out.println(" Customer Info A:" +customerA);
   // Since Scope is prototype , new instance will be return to caller
  User customerB = (User) context.getBean("userService"); 
  System.out.println(" Customer Info B:" +customerB);   // all fields value will be null
  
  customerB.setId(2);
  customerB.setUserName("Jhon");
  System.out.println(" Customer Info B:" +customerB);  
  
 }

}


Output :
  Customer Info A:[ ID : 1 Name :Jeff]
 Customer Info B:[ ID : null Name :null]
 Customer Info B:[ ID : 2 Name :Jhon]


You can download this example project from github https://github.com/sujanctg2005/Example

Saturday, March 24, 2012

Some Useful Java File Operations and Utility methods

File Modification, Copy, delete and create new file is quite easy in java programming. Here I wrote some java file operation utility method that might be useful for your application.  

Java File Copy Method
public static void copyfile(String srFile, String dtFile) throws Exception {

File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

// For Append the file.
// OutputStream out = new FileOutputStream(f2,true);

// For Overwrite the file.
OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {

 out.write(buf, 0, len);
}
in.close();
out.close();

}

Java Delete File Method
public static void removeFile(String fileName) throws Exception {

File file = new File(fileName);

if (file.exists()) {
 boolean success = file.delete();
 if (!success) {
  throw new Exception("Fail to delete existing file");
 }
}

}

Java Rename File Method
public static void renameFile(String oldName, String newName) throws IOException {
   File srcFile = new File(oldName);
   boolean bSucceeded = false;
   try {
       File destFile = new File(newName);
       if (destFile.exists()) {
           if (!destFile.delete()) {
               throw new IOException(oldName + " was not successfully renamed to " + newName);
           }
       }
       if (!srcFile.renameTo(destFile))        {
           throw new IOException(oldName + " was not successfully renamed to " + newName);
       } else {
               bSucceeded = true;
       }
   } finally {
         if (bSucceeded) {
               srcFile.delete();
         }
   }
}

Java List of files in specified directory with filter option
  
List fileList = FileUtil.dirlist(sourceLocation, "*.csv");

 public static List dirlist(String path, String filter) throws FileNotFoundException {

   File dir = new File(path);
   
   FileFilter fileFilter = new WildcardFilter(filter);
    File[] chld = dir.listFiles(fileFilter);  
   
   List fileList = new ArrayList();
   
   if (chld == null) {
    log.error("Specified directory does not exist or is not a directory.");
    throw new FileNotFoundException("Specified directory does not exist or is not a directory.");
    
    
   } else {
    for (int i = 0; i < chld.length; i++) {
     File file = chld[i];
     
     if(file.isFile()) {
      fileList.add(file);
     }
     
    }
   }
   return fileList;
  }

Java List of files in specified directory
public static List dirlist(String path) throws FileNotFoundException {
  File dir = new File(path);
  File[] chld = dir.listFiles();
  List fileList = new ArrayList();
  
  if (chld == null) {
   log.error("Specified directory does not exist or is not a directory.");
   throw new FileNotFoundException("Specified directory does not exist or is not a directory.");
   
  } else {
   for (int i = 0; i < chld.length; i++) {
    File file = chld[i];
    
    if(file.isFile()) {
     fileList.add(file);
    }
    
   }
  }
  return fileList;
 }

Thursday, March 15, 2012

Bind Oracle Listener with SID

Most of the time when we try to access oracle database from outside of localhost using oracle client or JDBC driver , we will get "ORA-12505, TNS:listener does not currently know of SID given in connect descriptor" error. But database can be accessible from local machine . To avoid this problem we need follow this steps.
  1. Go to Oracle Net Manager from All Program> Oracle> Configuration and Migration Tool> Oracle Net Manager,
  2. In Oracle Net Manager ,change oracle listener host name "Localhost" to database server IP or server full domain name , e.g : 60.84.278.155 or db.acm.com.
  3. Then you need to save change by clicking File>Save Network Configuration.
  4. Do not forget to add listener port into firewall if your firewall is enable.
  5. Next you have to bind your listener with oracle SID. For this you will change listener.ora. You will get this file into Oracle_HOME\NETWOReK\ADMIN . e.g C:\app\Administrator\product\11.2.0\dbhome_2\NETWORK\ADMIN\listener.ora. Add this in your listener.ora
    SID_LIST_LISTENER =
    (SID_LIST =
    (SID_DESC =
    (SID_NAME = orcl)
          (ORACLE_HOME = C:\app\Administrator\product\11.2.0\dbhome_2)
    
    )
    )
    
    
  6. Restart Listener to effect the change. In command prompt type following command to restart listener.
       
      lsnrctl stop
      lsnrctl start
    
Finally you will be to connect to database from outside of localhost successfully .