Saturday, December 24, 2011

Creating your Own Marker Interface

Here we are going to Create our own marker Interface."SingleTon". If any class implements this interface,then its object will be created only 1 time.
Folder Structure


SingleTon.java 
public interface SingleTon
{
}

FrameWorkContainer.java
import java.lang.reflect.Constructor;
import java.util.HashMap;                 
                                                            
class FrameWorkContainer               
{                                                          
static Object obj=null;                       

//HashMap will Only store those objects whose class has implemented SingleTon interface
static HashMap hmap=new HashMap();

public static Object createObject(Class cls)
 {
    //Get the Exact className,from cls
    String objName=cls.getCanonicalName();
     try
     {//get access to constructor and make it accessible
      Constructor construct=cls.getDeclaredConstructor();
      construct.setAccessible(true);
      //if hmap doesnot contain object with this key,create the object,
      //and store it in hashmap only if that object has implemented SingleTon interface
      //If the object has not implemented singleton,simple return the object without storing in hashmap
   
      if(!hmap.containsKey(objName))
      {
          obj=construct.newInstance();
          if(obj instanceof SingleTon )
              hmap.put(objName, obj);
          return obj;
      }
      else //if hashMap contains that object,return that object
      {   
            obj=hmap.get(objName);
            return obj;
      }
     
     
     }catch(Exception e){return null;}
   
}
}

Client.java 
------------
public class Client
{
    public static void main(String[] args)
    {       
        //Test class has implemented Singleton interface
        Test t1=(Test)FrameWorkContainer.createObject(Test.class);
        Test t2=(Test)FrameWorkContainer.createObject(Test.class);
        Demo d1=(Demo)FrameWorkContainer.createObject(Demo.class);
        Test t3=(Test)FrameWorkContainer.createObject(Test.class);
        Demo d2=(Demo)FrameWorkContainer.createObject(Demo.class);
        t1.sayHello();
       
        System.out.println(t1.hashCode());
        System.out.println(t2.hashCode());
        System.out.println(t3.hashCode());
        System.out.println(d1.hashCode());
        System.out.println(d2.hashCode());
      }
}
Demo.java
------------
public class Demo  
{
    private Demo(){}
}


Test.java
--------------------------------------------------------------------------------------------------------
public class Test implements SingleTon
{
    private Test(){System.out.println("Constructor::Test");}
    public void  sayHello()
    {
        System.out.println("Test::sayHello()");
    }
}




Enabling Https in Tomcat 6.0

This features works in Tomcat 7.0 as well
Steps:-
1.Use keytool tool to generate a keystore  in dos prompt
    C:\>keytool -genkey -alias mytomcat -keyalg RSA
2. A .keystore file will be created under "C:\Documents and Settings\Welcome" folder,
where welcome is your current user

3.Activate https service in your tomcat server,by including .keystore file produced above,in server.xml. These Entries are present in the server.xml,simple enable them and modify keystore file location and password

<Connector port="8443" maxThreads="200" scheme="https" secure="true" SSLEnabled="true"
  keystoreFile="C:\Documents and Settings\Welcome\.keystore"  keystorePass="satya123" 
   clientAuth="false" sslProtocol="TLS"/>                                                                                               

4.If you want you can disable normal Http Service by commenting
<Connector port="8080" protocol="HTTP/1.1"  connectionTimeout="20000" redirectPort="8443"/>

5.Restart the server,and give request to any webapplication using https,It will ask you to save the certificate in your system,and then after you can access the webapplication using https

Thursday, December 22, 2011

Batch Update Using PreparedStatement with MySql Database

BatchExecutePreparedStatment.java
----------------------------------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class BatchExecutePreparedStatment {

    public static void main(String[] args)throws Exception
    {
         String userName = "root";
         String password = "root";
         String url = "jdbc:mysql://localhost/dhportaldb";
         Class.forName ("com.mysql.jdbc.Driver").newInstance ();
         Connection con = DriverManager.getConnection (url, userName, password);
        
       con.setAutoCommit(false);
      
     
       PreparedStatement pst=con.prepareStatement("insert into employee values(?,?)");
      
       pst.setInt(1,100);
       pst.setString(2,"raj");
       pst.addBatch();
      

       pst.setInt(1,200);
       pst.setString(2,"satyam");
       pst.addBatch();

       pst.setInt(1,300);
       pst.setString(2,"wipro");
       pst.addBatch();
      
      int count[]=pst.executeBatch();
      con.commit();
     
      for(int i=0;i<count.length;i++)
               if(count[i]!=0)
                    {
                     con.rollback();
                     break;
                     }
    }
}
ClassPath:Add mysql-connector-java-5.0.8-bin.jar  to your classpath

Batch Update Using Statement with MySql Database

BatchExecuteStatement.java
------------------------------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class BatchExecuteStatement {

    public static void main(String[] args)throws Exception
    {
         String userName = "root";
         String password = "root";
         String url = "jdbc:mysql://localhost/dhportaldb";
         Class.forName ("com.mysql.jdbc.Driver").newInstance ();
         Connection con = DriverManager.getConnection (url, userName, password);
        
       con.setAutoCommit(false);
      
      // PreparedStatement pst=con.prepareStatement("insert into");
       Statement st=con.createStatement();
       st.addBatch("insert into employee values(101,'raj')");
       st.addBatch("insert into employee values(102,'satyam')");
       st.addBatch("insert into employee values(103,'wipro')");
       st.addBatch("insert into employee values(104,'suman')");
      
      int count[]=st.executeBatch();
      con.commit();
     
      for(int i=0;i<count.length;i++)
               if(count[i]!=0){con.rollback();break;}
    }
}


CLASSPATH:-Add mysql-connector-java-5.0.8-bin.jar in Classpath

Wednesday, December 21, 2011

Get All the Files and Folders Present inside the Directory

This is one of the way to get the list of all the files and folders present inside a particular folder,
I assume here that you have C:\store  folder in your computer with some subfolders and files inside it.


import java.io.File;
import java.io.IOException;

public class GetAllFilesAndFoldersInDirectory
{
public static void main(String[] args) throws IOException
{
File dir = new File("c:/store");
//All the files and folder names inside C:/store will be stored in this array
String[] list = dir.list();

if (list == null)
{
    // Either dir does not exist or is not a directory
}
else
{
    for (int i=0; i<list.length; i++)
    {
        // Get filename of file or directory
        String filename = list[i];
        System.out.print(filename+"::");
       
        //check if its a file or directory
        File tf = new File(dir.getPath(), list[i]);
        if (tf.isDirectory())
          System.out.println("directory");
          else System.out.println("file");
   
     }//for
}//else
}//main
}//class

Tuesday, December 20, 2011

Create Folders SubFolders using Java

CreateDirectory.java
-------------------------------------------------------------------------------------------------------
import java.io.*;
class CreateDirectory
{
 public static void main(String args[])
  {
  try{
  String myfolder ="c:/test";
  String mySubFolder1="c:/test/dir1";
  String mySubFolder2="c:/test/dir2";
  String mySubFolder3="c:/test/dir3/dir4/dir5";
  // Create folder test under c:
  //return true if created successfully
 
  boolean success = (new File(myfolder)).mkdir();
 
  //create a file inside that folder,returns true if successful
  success = new File("c:/test/myfile.txt").createNewFile();
 
 
  // Create multiple folders inside test
  success = (new File(mySubFolder1)).mkdir();
  success = (new File(mySubFolder2)).mkdir();
  success = (new File(mySubFolder3)).mkdirs();
 
 
System.out.println("Successfull");
  }catch (Exception e){System.err.println("Error: " + e.getMessage());}
  }//main
}//class
-----------------------------------------------------------------------------------------------------------

Create File Using Java

Some times we need to create a File,using java.Here is the code


CreateFile.java
----------------------------------------------------------------------------------------------------
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CreateFile
{
    public static void main(String[] args) throws IOException
    {
        boolean msg=false;
        File f = new File("c:/myfile.txt");
        //check if file is not present
        if (!f.exists()) msg=f.createNewFile();//returns boolean
       
        System.out.println("File Created ?"+msg);
       
        FileWriter fstream = new FileWriter("c:/myfile.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("Hello World2");
        out.close();
        System.out.println("File Written Successfully");
    }
}
-----------------------------------------------------------------------------------------------