Thursday, 29 March 2012

JUnit Test cases for Struts2 Action class With Spring and hibernate integration


Base Test Class
  1. /**
  2.  *
  3.  */
  4. package com.lkr.base.test;
  5. import java.util.HashMap;
  6. import junit.framework.TestCase;
  7. import org.apache.struts2.ServletActionContext;
  8. import org.apache.struts2.dispatcher.Dispatcher;
  9. import org.apache.struts2.views.JspSupportServlet;
  10. import org.springframework.context.ApplicationContext;
  11. import org.springframework.mock.web.MockHttpServletRequest;
  12. import org.springframework.mock.web.MockHttpServletResponse;
  13. import org.springframework.mock.web.MockServletConfig;
  14. import org.springframework.mock.web.MockServletContext;
  15. import org.springframework.web.context.ContextLoader;
  16. import com.opensymphony.xwork2.ActionProxy;
  17. import com.opensymphony.xwork2.ActionProxyFactory;
  18. import com.opensymphony.xwork2.ActionSupport;
  19. /**
  20.  *
  21.  * @author KONDA REDDY. LINGAMDINNE
  22.  */
  23. public abstract class IDEActionBaseTest extends TestCase {
  24.     private static final String CONFIG_LOCATIONS ="applicationContext.xml"+",ideazExchangeTiles-defs.xml";
  25.     private static ApplicationContext applicationContext;
  26.     private Dispatcher dispatcher;
  27.     protected ActionProxy proxy;
  28.     protected static MockServletContext servletContext;
  29.     protected static MockServletConfig servletConfig;
  30.     protected MockHttpServletRequest request;
  31.     protected MockHttpServletResponse response;
  32.     public IDEActionBaseTest(String name) {
  33.         super(name);
  34.     }
  35.     @SuppressWarnings({ "unchecked", "deprecation", "rawtypes" })
  36.     protected ActionSupport createAction( String namespace, String name)
  37.     throws Exception {
  38.         proxy = dispatcher.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(namespace, name, null, true, false);
  39.         proxy.getInvocation().getInvocationContext().
  40.         setParameters(new HashMap());
  41.         proxy.setExecuteResult(true);
  42.         ServletActionContext.setContext(
  43.         proxy.getInvocation().getInvocationContext());
  44.         request = new MockHttpServletRequest();
  45.         response = new MockHttpServletResponse();
  46.         ServletActionContext.setRequest(request);
  47.         ServletActionContext.setResponse(response);
  48.         ServletActionContext.setServletContext(servletContext);
  49.         return (ActionSupport) proxy.getAction();
  50.     }
  51.     @SuppressWarnings({ "rawtypes", "unchecked" })
  52.     protected void setUp() throws Exception {
  53.         if (applicationContext == null) {
  54.             servletContext = new MockServletContext();
  55.             servletContext.addInitParameter(
  56.                     ContextLoader.CONFIG_LOCATION_PARAM,
  57.                     CONFIG_LOCATIONS);
  58.             applicationContext = (new ContextLoader())
  59.                     .initWebApplicationContext(servletContext);
  60.             new JspSupportServlet().init(new MockServletConfig(servletContext));
  61.         }
  62.         HashMap params = new HashMap();
  63.         params.put("actionPackages", "com.lkr.admin.action");
  64.         dispatcher = new Dispatcher(servletContext, params);
  65.         dispatcher.init();
  66.         Dispatcher.setInstance(dispatcher);
  67.     }
  68.    
  69. }


  1. package com.lkr.base.test;
  2. import com.lkr.view.UsersView;
  3. import com.lkr.admin.action.LoginAction;
  4. public class LoginActionTest extends IDEActionBaseTest {
  5.     public LoginActionTest(String name) {
  6.         super(name);
  7.         // TODO Auto-generated constructor stub
  8.     }
  9.     protected void setUp() throws Exception {
  10.         super.setUp();
  11.     }
  12.     protected void tearDown() throws Exception {
  13.         super.tearDown();
  14.     }
  15.     public void testLogin() throws Exception {
  16.        
  17.         LoginAction loginAction = (LoginAction) createAction("/", "login");
  18.        
  19.         UsersView usersView = new UsersView();
  20.        
  21.         loginAction.setUsersView(usersView);
  22.        
  23.         usersView.setLoginId("use");
  24.         usersView.setPassword("fuhdsiah");
  25.         // loginAction.login();
  26.     //  System.out.println(loginAction.login());
  27.     }
  28. }

Wednesday, 28 March 2012

Directory Creation With Date Format


1:  package com.lkr.properties;  
2:  import java.io.File;  
3:  import java.text.SimpleDateFormat;  
4:  import java.util.Date;  
5:  public class CreateDirectoryExample  
6:  {  
7:    public static void main(String[] args)  
8:    {       
9:       File file = new File("d:\\Directory1");  
10:       if(file.mkdir()){  
11:            System.out.println(file);  
12:            System.out.println("Directory is created!");  
13:       }else{  
14:            System.out.println(file);  
15:            System.out.println("Failed to create directory!");  
16:       }  
17:       File files = new File("d:\\Directory2\\Sub2\\Sub-Sub2");       
18:       if(files.mkdirs()){  
19:            System.out.println(files);  
20:            System.out.println("Multiple directories are created!");  
21:       }else{  
22:            System.out.println(files);  
23:            System.out.println("Failed to create multiple directories!");  
24:       }  
25:       // Create Date object      
26:    Date date = new Date();  
27:    //Specify the desired date format      
28:    String DATE_FORMAT = "MM/dd/yyyy";  
29:    //Create object of SimpleDateFormat and pass the desired date format      
30:    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);  
31:    /*  
32:    Use format method of SimpleDateFormat class to format the date.  
33:    */  
34:    System.out.println("Today is " + sdf.format(date));  
35:    }  
36:  }  

Saturday, 24 March 2012

JNotify - Java library that allows java application to listen to file system events

JNotify works on both Windows (Windows 2000, XP, Vista) and Linux with INotify support (Kernel 2.6.14 and above).

JNotify is a java library that allow java application to listen to file system events, such as:
file created.
file modified.
file renamed.
file deleted.
This property can be used in a number of scenarios.I have used it to reload resource bundles
whenever there is a modiofication in it.
Reference:
http://jnotify.sourceforge.net/ 


1)When this program is not working properly,
2)you should check some files are there or not in your computer
3)jnotify.dll and jnotify_64bit.dll are mandatory for working these program
4)you should copy and paste these two dll files in your system32 folder or jdk lib folder
 


1:  package org.life.java.lkr.questions;  
2:  import java.io.File;  
3:  import net.contentobjects.jnotify.JNotify;  
4:  import net.contentobjects.jnotify.JNotifyListener;  
5:  import org.apache.log4j.Logger;  
6:  /**  
7:   *   
8:   * @author Konda Reddy. L
9:   */  
10:  public class JNotifyDemo {  
11:       private static Logger logger = Logger.getLogger(JNotifyDemo.class);  
12:       public void sample() throws Exception {  
13:            // path to watch  
14:            // String path = System.getProperty("user.home");  
15:            String path = System.getProperty("user.dir");  
16:            //System.out.println(path);  
17:            logger.info(path);  
18:            // watch mask, specify events you care about,  
19:            // or JNotify.FILE_ANY for all events.  
20:            int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED  
21:                      | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;  
22:            // watch subtree?  
23:            boolean watchSubtree = true;  
24:            // add actual watch  
25:            int watchID = JNotify  
26:                      .addWatch(path, mask, watchSubtree, new Listener());  
27:            // sleep a little, the application will exit if you  
28:            // don't (watching is asynchronous), depending on your  
29:            // application, this may not be required  
30:            Thread.sleep(1000000);  
31:            // to remove watch the watch  
32:            boolean res = JNotify.removeWatch(watchID);  
33:            if (!res) {  
34:                 // invalid watch ID specified.  
35:            }  
36:       }  
37:       class Listener implements JNotifyListener {  
38:            public void fileRenamed(int wd, String rootPath, String oldName,  
39:                      String newName) {  
40:                 System.out.println("fileRenamed");  
41:                 //print("renamed " + rootPath + " : " + oldName + " -> " + newName);  
42:                 logger.info("renamed"+rootPath+":"+oldName+"->"+newName);  
43:            }  
44:            public void fileModified(int wd, String rootPath, String name) {  
45:                 //System.out.println("modified");  
46:                 logger.info("modified");  
47:                 logger.info("name");
                      File csvfile = new File(name);
   logger.info("csvfile::" + csvfile);
   try {
    FileProccessor.loadDatabaseData(csvfile);
   } catch (Exception e) {
    e.printStackTrace();
   }  
48:                 //System.out.println(name);  
49:  //print("modified " + rootPath + " : " + name);  
50:                 logger.info("modified"+rootPath+":"+name);  
51:            }  
52:            public void fileDeleted(int wd, String rootPath, String name) {  
53:                 //print("deleted " + rootPath + " : " + name);  
54:                 logger.info("fileDeleted"+rootPath+":"+name);  
55:            }  
56:            public void fileCreated(int wd, String rootPath, String name) {  
57:                 //System.out.println("fileCreated");  
58:                 //print("created " + rootPath + " : " + name);  
59:                 logger.info("fileCreated"+rootPath+":"+name);  
60:                 logger.info("fileCreated");  
61:            }  
62:            void print(String msg) {  
63:                 System.err.println(msg);  
64:            }  
65:       }  
66:       public static void main(String[] args) throws Exception {  
67:            new JNotifyDemo().sample();  
68:       }  
69:  }  
1:  package org.life.java.lkr.questions;   
2:  import java.io.BufferedReader;  
3:  import java.io.File;  
4:  import java.io.FileReader;  
5:  import java.io.FileWriter;  
6:  import java.io.FilenameFilter;  
7:  import org.apache.log4j.Logger;  
8:  import org.hibernate.Session;  
9:  import org.hibernate.Transaction;  
10:  import org.hibernate.cfg.Configuration;  
11:  public class FileProccessor {  
12:       private static Logger logger = Logger.getLogger(FileProccessor.class);  
13:       private static Session session = new Configuration().configure()  
14:                 .buildSessionFactory().openSession();  
15:       private static Integer age;  
16:       private static String name;  
17:       /**  
18:        *   
19:        * This method assumes that Hibernate is set up already and can be loaded  
20:        *   
21:        * with data contained in the CSV file.  
22:        *   
23:        *   
24:        *   
25:        * @param csvFile  
26:        *   
27:        * @throws Exception  
28:        */  
29:       public static void loadDatabaseData(File csvFile) throws Exception {  
30:            String filename = csvFile.getName();  
31:            logger.info("Reading contents of :" + filename);  
32:            BufferedReader in = new BufferedReader(new FileReader(csvFile));  
33:            logger.info("csv" + csvFile);  
34:            String values = in.readLine();  
35:            if (values != null) {  
36:                 do {  
37:                      logger.info("before replace all" + values);  
38:                      String str = values;  
39:                      String[] temp;  
40:                      /* delimiter */  
41:                      String delimiter = ",";  
42:                      /*  
43:                       * given string will be split by the argument delimiter  
44:                       * provided.  
45:                       */  
46:                      temp = str.split(delimiter);  
47:                      /* print substrings */  
48:                      for (int i = 0; i < temp.length; i++) {  
49:                           logger.info("temp Values:::" + temp[i]);  
50:                           age = Integer.parseInt(temp[i]);  
51:                           name = temp[++i];  
52:                           logger.info("name is:" + name);  
53:                      }  
54:                      // inserting data into database  
55:                      insertIntoDatabase(age, name);  
56:                      values = in.readLine();  
57:                 } while (values != null);  
58:                 try {  
59:                      FileWriter fwriter = new FileWriter(csvFile);  
60:                      fwriter.close();  
61:                 } catch (Exception e) {  
62:                      e.printStackTrace();  
63:                 }  
64:            }  
65:       }  
66:       /**  
67:        * Calls hibernate and inserts the datainto the database  
68:        *   
69:        *   
70:        * @param age2  
71:        * @param name2  
72:        */  
73:       private static void insertIntoDatabase(Integer age2, String name2) {  
74:            Transaction transaction = session.beginTransaction();  
75:            Gdata emp = new Gdata();  
76:            emp.setAge(age2);  
77:            emp.setName(name2);  
78:            session.save(emp);  
79:            transaction.commit();  
80:            logger.info("inserting done");  
81:            logger.info("SQL SUCCEEDED");  
82:       }  
83:       /**  
84:        *   
85:        * Private class to allow only CSV files to be read. Could have been in a  
86:        *   
87:        * different class but thought it would be more portable this way.  
88:        *   
89:        *   
90:        *   
91:        * @author Konda Reddy  
92:        *   
93:        *   
94:        */  
95:       private static class CsvFilter implements FilenameFilter {  
96:            public CsvFilter() {  
97:            }  
98:            public boolean accept(File dir, String name) {  
99:                 if (name.toLowerCase().endsWith(".csv")) {  
100:                      return true;  
101:                 } else {  
102:                      return false;  
103:                 }  
104:            }  
105:       }  
106:  }  
1:  package org.life.java.lkr.questions;  
2:  public class Gdata {  
3:       private Integer id;  
4:       private Integer age;  
5:       private String name;  
6:       /**  
7:        * @return the age  
8:        */  
9:       public Integer getAge() {  
10:            return age;  
11:       }  
12:       /**  
13:        * @param age the age to set  
14:        */  
15:       public void setAge(Integer age) {  
16:            this.age = age;  
17:       }  
18:       /**  
19:        * @return the name  
20:        */  
21:       public String getName() {  
22:            return name;  
23:       }  
24:       /**  
25:        * @param name the name to set  
26:        */  
27:       public void setName(String name) {  
28:            this.name = name;  
29:       }  
30:       /**  
31:        * @return the id  
32:        */  
33:       public Integer getId() {  
34:            return id;  
35:       }  
36:       /**  
37:        * @param id the id to set  
38:        */  
39:       public void setId(Integer id) {  
40:            this.id = id;  
41:       }  
42:  }  
1:  <?xml version="1.0"?>  
2:  <!DOCTYPE hibernate-mapping PUBLIC   
3:       "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
4:       "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
5:  <hibernate-mapping>  
6:  <class name="org.life.java.lkr.questions.Gdata" table="test">  
7:       <id name="id" column="idtest">  
8:       <generator class="increment"/>  
9:       </id>  
10:       <property name="age" column="age"/>  
11:       <property name="name" column="name"/>  
12:  </class>  
13:  </hibernate-mapping>  
1:  <!DOCTYPE hibernate-configuration PUBLIC  
2:       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
3:       "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
4:  <hibernate-configuration>  
5:  <session-factory>  
6:  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
7:  <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>  
8:  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>  
9:  <!-- <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property> -->  
10:  <property name="hibernate.connection.username">root</property>  
11:  <property name="hibernate.connection.password">root</property>  
12:  <mapping resource="Gadget.hbm.xml"/>  
13:  </session-factory>  
14:  </hibernate-configuration>  

Wednesday, 21 March 2012

Hibernate CSV Loader

A typical issue when developing a web application is needing to add test data to a database or needing data to be added to a live database as it makes up an essential part of the application. Certain frameworks allow you to add data to a database through "*.sql" scripts. This can be frustrating when working with Hibernate as you may encounter syntax issues although this is unlikely. Also adding multiple insert statements into scripts is just simply unnecessary and very frustrating if its allot of data.

I avoid this headache through using a simple CSV loader class. I can then edit the CSV file through a spreadsheet package. I have found that strings are also surrounded by quotes by default which makes creating insert statements really simple.

Below is a dump of the class that I use to insert data into a database.

Here are some simple instructions when using the class:
      1. The name of the csv file is the name of the table.
      2. The first row of the table contains the name of the columns in the database.
      3. If the database requires unique insert syntax just overload the class and add a new insert statement.
      4. The CSV file should be in UTF8 format.
      5. Has issues with some special characters. Certain quotes has a nasty habit of breaking the code.

Heres the class:


1:  public class LoadDatabase {
  
2:  private static Logger log = Logger.getLogger(LoadDatabase.class);
  
3:  private static Session session = getSessionFactory().getCurrentSession();
  
4:  private static String SQL_INSERT = "INSERT INTO ${table}(${keys}) VALUES(${values})";
  
5:  private static final String TABLE_REGEX = "\\$\\{table\\}";
  
6:  private static final String KEYS_REGEX = "\\$\\{keys\\}";
  
7:  private static final String VALUES_REGEX = "\\$\\{values\\}";
  
8:  /**
  
9:  * To allow running from command line for when live system is being built
  
10:  *
  
11:  * @param args
  
12:  * @throws Exception
  
13:  */
  
14:  public static void main(String[] args) throws Exception {
  
15:  // The only arguement is the directory containing the CSV files
  
16:  String csvDirectory = args[0];
  
17:  if (csvDirectory == null) {
  
18:  throw new Exception(
  
19:  "No CSV directory supplied to LoadDatabase class");
  
20:  }
  
21:  File csvFiles = new File(csvDirectory);
  
22:  run(csvFiles);
  
23:  }
  
24:  public static void run(File csvDirectory) throws Exception {
  
25:  if (!csvDirectory.exists() || !csvDirectory.isDirectory()) {
  
26:  throw new Exception(
  
27:  "You can only supply a directory to this LoadDatabase");
  
28:  }
  
29:  log.info("Retrieving list of csv files contained within :"
  
30:  + csvDirectory.getName());
  
31:  CsvFilter csvFilter = new CsvFilter();
  
32:  File[] csvFiles = csvDirectory.listFiles(csvFilter);
  
33:  for (File csvFile : csvFiles) {
  
34:  loadDatabaseData(csvFile);
  
35:  }
  
36:  }
  
37:  /**
  
38:  * This method assumes that Hibernate is set up already and can be loaded
  
39:  * with data contained in the CSV file.
  
40:  *
  
41:  * @param csvFile
  
42:  * @throws Exception
  
43:  */
  
44:  private static void loadDatabaseData(File csvFile) throws Exception {
  
45:  String filename = csvFile.getName();
  
46:  log.info("Reading contents of :" + filename);
  
47:  String databaseName = filename.substring(0, filename.indexOf("."));
  
48:  log.info("Obtained database name: " + databaseName);
  
49:  BufferedReader in = new BufferedReader(new FileReader(csvFile));
  
50:  // First line will allways be the column names
  
51:  String keys = in.readLine();
  
52:  if (keys == null || keys.length() == 0) {
  
53:  throw new Exception("No columns defined in :" + filename);
  
54:  }
  
55:  // trailing garbage plus " from column names
  
56:  keys = keys.replaceAll("\"", "");
  
57:  String insertTemplate = SQL_INSERT.replaceFirst(TABLE_REGEX, databaseName);
  
58:  insertTemplate = insertTemplate.replaceFirst(KEYS_REGEX, keys);
  
59:  String values = null;
  
60:  while ((values = in.readLine()) != null) {
  
61:  values = values.replaceAll("\"", "\\\'");
  
62:  insertIntoDatabase(insertTemplate.replaceFirst(VALUES_REGEX, values));
  
63:  }
  
64:  }
  
65:  /**
  
66:  * Calls hibernate and inserts the datainto the database
  
67:  *
  
68:  * @param statement
  
69:  */
  
70:  private static void insertIntoDatabase(String statement) {
  
71:  log.debug(statement);
  
72:  session.beginTransaction();
  
73:  session.createSQLQuery(statement).executeUpdate();
  
74:  session.flush();
  
75:  log.debug("SQL SUCCEEDED");
  
76:  }
  
77:  /**
  
78:  * Private class to allow only CSV files to be read. Could have been in a
  
79:  * different class but thought it would be more portable this way.
  
80:  *
  
81:  * @author Konda Reddy . L
  
82:  *
  
83:  */
  
84:  private static class CsvFilter implements FilenameFilter {
  
85:  public CsvFilter() {
  
86:  }
  
87:  public boolean accept(File dir, String name) {
  
88:  if (name.toLowerCase().endsWith(".csv")) {
  
89:  return true;
  
90:  } else {
  
91:  return false;
  
92:  }
  
93:  }
  
94:  }
  
95:  }
  

Monday, 12 March 2012

Java Collections Framework: TreeSet Example with Comparable and Comparator implementation

Java Collections Framework: TreeSet Example with Comparable and Comparator implementation

The TreeSet implementation of the Set interface maintains a sorted collection of unique objects. The custom sort order is determined by implementing either the Comparable interface or the Comparator interface.

In case of the Comparable interface, the class (objects of which will be added to the TreeSet) has to implement the interface.

In case of the Comparator interface. an external class implements the interface. The Comparator allows creating a custom sort order for objects of a 3rd party class.

TreeSet code example with Comparable to compare objects for custom sort order

package info.icontraining.collections;

import java.util.*;

public class TreeSetExample {

   public static void main(String[] args) {
 
      Set customers = new TreeSet();

      customers.add(new Customer("Dinesh", "Atlanta"));      
      customers.add(new Customer("Tanvi", "Norcross"));
      customers.add(new Customer("Laksh", "Duluth"));
  
      for(Customer c: customers) {
         System.out.print(c.getCustomerName() + " | ");
         System.out.println(c.getCustomerCity());      
      }  
     
      customers.add(new Customer("Dinesh", "Alpharetta"));

      System.out.println();

      for(Customer c: customers) {
         System.out.print(c.getCustomerName() + " | ");
         System.out.println(c.getCustomerCity());      
      }    
   }
}

package info.icontraining.collections;

public class Customer implements Comparable {

   private String customerName;
   private String customerCity;
 
   public Customer(String customerName, String customerCity) {
      this.customerName = customerName;
      this.customerCity = customerCity;
   }
 
   public int compareTo(Customer customer) {
      int nameOrder = this.customerName.compareTo(customer.customerName);

      if (nameOrder == 0)
         return this.customerCity.compareTo(customer.customerCity);
  
      return nameOrder;
   }
 
   public String getCustomerName() {
      return this.customerName;
   }
 
   public String getCustomerCity() {
      return this.customerCity;
   }
}

TreeSet code example with Comparator to compare objects for custom sort order

Using the Comparator interface entails creating a new class to implement the interface. The Comparator should be used in the situation where the Customer class is a 3rd party class whose source code is unavailable to us.

package info.icontraining.collections;

import java.util.Comparator;

public class CustomerComparator implements Comparator {

   public int compare(Customer c1, Customer c2) {
      int nameOrder = c1.getCustomerName().compareTo(c2.getCustomerName());
  
      if (nameOrder == 0)
         return c1.getCustomerCity().compareTo(c2.getCustomerCity());
  
      return nameOrder;
   }
}

Also make the following changes to run the example with Comparator instead of Comparable,

1) From the Customer class, remove the implements Comparable

2) In the TreeSetExample class, replace the following line to instantiate the TreeSet

Set<Customer> customers = new TreeSet<Customer>();

with

Set<Customer> customers = new TreeSet<Customer>(new CustomerComparator());

Wednesday, 7 March 2012

What is the difference between Iterator and Listiterator ?



There are two Differences are there :

1. We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.

That is, we can get a Iterrator object by using Set and List, see here :

 By using Iterator we can retrieve the elements from Collection Object in forward direction only.

Methods in Iterator :

1. hashNext()
2. next()
3. remove()



Iterator ite = Set.iterator();
Iterator ite = List.iterator();


2. But we get List Iterator object only from List interface, see here :

where as List Iterator, which allows you to traverse in either directions. That is List Iterators traverse two directions. So it has another methods hasPrevious() & previous() other than Iterator.

Methods in ListIterator

1. hashNext()
2. next()
3. previous()
4.hashPrevious()
5. remove()
6. nextIndex()
7. previousIndex()


ListIterator listite = List.listIterator();

i.e., we can't get List Iterator object from Set interface.