Saturday 31 December 2011

JDBC connection for mysql

Copy the below given code to a file and save it as Connect.java
package com.test1.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author HOME
 */
public class Connect {
    public static Connection connectDb(){
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", DB_LOGINID, DB_LOGIN_PASSWORD);
            System.out.println("Connection Established");
            return conn;
        } catch (Exception ex) {
            return null;
        }      
    }
}

NOTE:
DATABASE – Name of the database
DB_LOGINID – Login Id for the data base
DB_LOGIN_PASSWORD – Login password for the data base

User defined Exception in java

Create the below given java classes.
Class Name :exceptionTest.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class exceptionTest{
                        public static void main(String arg[]) throws MainException, NumberFormatException, IOException{
                                                //This is a example for user defined exception
                                                System.out.print("Please enter Employee Number form 1 to 10 : ");
                                                InputStreamReader istream = new InputStreamReader(System.in) ;         
                                                BufferedReader bufRead = new BufferedReader(istream) ;
                                                int userEntry = Integer.parseInt(bufRead.readLine());
                                                if(userEntry > 10){
                                                   throw new EmpNotFoundException("Please Enter a value from 1 to 10");
                                                }else{
                                                                        System.out.println("You have entered the value: "+ userEntry);
                                                }
                        }
}

Class Name : MainException.java

 public class MainException extends Exception {

                        private static final long serialVersionUID = -6452702088031438499L;
                        private String errorKey;
                         
                        public void setErrorKey(String errorKey) {
                                                this.errorKey = errorKey;
                        }
                       
                        public String getErrorKey() {
                                                return errorKey;
                        }

                        public MainException() {
                                                super();
                        }

                        public MainException(String errorKey, Throwable cause) {
                                                super(errorKey,cause);
                                                this.errorKey = errorKey;
                        }

                        public MainException(String errorKey) {
                                                super(errorKey);
                                                this.errorKey = errorKey;
                        }

}


Class Name : EmpNotFoundException.java
  
public class EmpNotFoundException extends MainException {

                        private static final long serialVersionUID = 1L;
                        private String errorKey;
                       
                        public void setErrorKey(String errorKey) {
                                                this.errorKey = errorKey;
                        }
                       
                        public String getErrorKey() {
                                                return errorKey;
                        }
                       
                        public EmpNotFoundException(String errorKey, Throwable cause) {
                                                super(errorKey, cause);
                        }

                        public EmpNotFoundException(String errorKey) {
                                                super(errorKey);
                        }

}

Now run the exceptionTest.java. If you enter a value greater than 10, then user defined exception will be triggered and the message appears in the console.
Try it !!!

Java Array List

ArrayList holds array of elements. In situations you may not know the actual size of the array, in that case the collection frame work has Array List. Its size increases dynamically as you add or delete the elements in the array. The elements in ArrayList are not sorted.
Class name:  ArrayList.java
import java.util.*;

class ArrayList {
       public static void main(String args[]) {

              // Creating an object of arrayList
              List<Integer> num = new ArrayList<Integer>();

              // adding elements to list
              num.add(6);
              num.add(3);
              num.add(1);
              num.add(4);
              num.add(5);
              num.add(2);
              System.out.println("Contents of num: " + num);
             
              //Change value of num at position 1
              num.add(1, 7);
             
              // After changing num value at position 1
              System.out.println("Size of num after addition: " + num.size());
              System.out.println("Contents of num after addition: " + num);
             
              // Removing elements from list
              num.remove(6);
              num.remove(2);
              System.out.println("Final size of num after deletion: " + num.size());
              System.out.println("Contents of num after deletion: " + num);
       }
}

OUTPUT:
Contents of num: [6, 3, 1, 4, 5, 2]
Size of num after addition: 7
Contents of num after addition: [6, 7, 3, 1, 4, 5, 2]
Final size of num after deletion: 5
Contents of num after deletion: [6, 7, 1, 4, 5]

Java HashMap

The Hash Map uses <Key, value> pair to store data. The Key is unique for each data in a map. There can be one NULL key in a map.
Class Name:  HashMapExample.java
import java.util.*;

public class HashMapExample1 {
       public static void main(String[] args) {
              Map<String,Integer> map1 = new HashMap<String,Integer>();
      
              //Map to store name and age Map<Key,Value>
              map1.put("SAM", 18);
              map1.put("DONALD", 26);
              map1.put("BILLY", 24);
              map1.put("TRINITY", 18);
              map1.put("JIM", null);
              map1.put(null, 24);
              System.out.println("Contents of Map : "+map1);
             
              //KeySet() returns all key in the Map
              System.out.println("Keyset : "+map1.keySet());
             
              //Remove a value from map
              map1.remove("JIM");
              System.out.println("Contents of Map after removing : "+map1);
             
              //Getting particular value using key
              System.out.println("Value of map at given KEY : "+map1.get("SAM"));
             
              //Size of map
              System.out.println("Size of the give map : "+map1.size());
             
              //Getting all values in the map
              System.out.println("Values in map : "+map1.values());
             
              //To check if the map is empty - returns true if map is empty
              System.out.println("Is the map empty : "+map1.isEmpty());
       }
}
OUTPUT:
Contents of Map : {null=24, DONALD=26, SAM=18, TRINITY=18, JIM=null, BILLY=24}
Keyset : [null, DONALD, SAM, TRINITY, JIM, BILLY]
Contents of Map after removing : {null=24, DONALD=26, SAM=18, TRINITY=18, BILLY=24}
Value of map at given KEY : 18
Size of the givem map : 5
Values in map : [24, 26, 18, 18, 24]
Is the map empty : false

Creating Thrift generated File

Follow the below steps to download thrift.exe
·                Download Thrift.exe from  apache
·                Save this exe file in a location (ex: D:/apache/thrift.exe)
·                Now create follow below given steps to create .thrift file
Example for .thrift file,
namespace java example
strut Employee {
  1: string    id,
  2: string name,
  3: string address,
  4: string phoneNumber
}
struct EmployeeId {
  1: string    id
}
service EmployeeService {
  Employee getEmployee(1:EmployeeId id)
}
·                Copy this to a file and save it as empDetails.thrift ( ex: in location D:/thrift/ empDetails.thrift)
·                Open command prompt
·                In command prompt go to the thrift file location (D:/thrift/ empDetails.thrift)
·                Now type D:/apache/thrift.exe -gen java empDetails.thrift
·                Now you will get java thrift generated files