Interview Preperation

sorting the employee based on salary(acending and descending order) using Comparator Interface
=======================================================================
Employee1.java
--------------
import java.util.Date;

public class Employee1 {
public int id;
public String name;
public int salary;
public int age;
public Employee1(int id, String name,int salary,int age) {
 this.id=id;
 this.name=name;
 this.age=age;
 this.salary=salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}
Employee1Comparator.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class Employee1Comparator {
public static void main(String[] args) {
Employee1 e1 = new Employee1(1, "A", 4000, 32);
        Employee1 e2 = new Employee1(2, "AB", 3000, 22 );
        Employee1 e3 = new Employee1(3, "B", 5000, 42 );
        Employee1 e4 = new Employee1(4, "CD", 1000, 23);
        Employee1 e5 = new Employee1(5, "AAA", 2000, 26 );
 
        List<Employee1> listOfEmployees = new ArrayList<Employee1>();
        listOfEmployees.add(e1);
        listOfEmployees.add(e2);
        listOfEmployees.add(e3);
        listOfEmployees.add(e4);
        listOfEmployees.add(e5);
        System.out.println("Unsorted List : " + listOfEmployees);
        for(Employee1 employee :listOfEmployees)
        {
         System.out.println(employee.getId()+" "+employee.getName()+" "+employee.getAge()+" "+employee.getSalary());
        }
 
        Collections.sort(listOfEmployees,new Employee1SalComparator() );      //Sorting by natural order
        System.out.println("Unsorted List : " + listOfEmployees);
        for(Employee1 employee :listOfEmployees)
        {
         System.out.println(employee.getId()+" "+employee.getName()+" "+employee.getAge()+" "+employee.getSalary());
        }
}
}
class Employee1SalComparator implements Comparator<Employee1>{
@Override
public int compare(Employee1 o1, Employee1 o2) {
 return o1.salary - o2.salary; //ascending order
              //return o1.salary - o2.salary; //descending order

}
}
=======================================================================
Writing the data into propetiesfile(config.properties)-Refresh on the project to see the config.properties file
------------------------------------------------------
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class writingIntoPropertiesFile {
  public static void main(String[] args) {

Properties prop = new Properties();
OutputStream output = null;

try {

output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
  }
}
======================================================================


========================================================================
reading the data into propetiesfile(config.properties)
------------------------------------------------------
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class ReadingPropertiesFille {
public static void main(String[] args) {
try (
FileReader reader = new FileReader("config.properties")) {
Properties properties = new Properties();
properties.load(reader);
String url = properties.getProperty("dbpassword");
System.out.println(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
========================================================================
StingPool.java
-------------
public class StringPool {
public static void main(String[] args) {
String s1 = "Cat";
    String s2 = "Cat";
    String s3 = new String("Cat");
    System.out.println("s1 hascode="+s1.hashCode());
    System.out.println("s2 hascode="+s2.hashCode());
    System.out.println("s3 hascode="+s3.hashCode());
    System.out.println("s1 == s2 :"+(s1==s2));//true
    System.out.println("s1 == s3 :"+(s1==s3));//false
    if(s1.equals(s2))
     System.out.println("s1 contentent equals to s2");//prints
    if(s2.equals(s3))
     System.out.println("s2 contentent equals to s3");//prints
}
}
========================================================================
String tokeniser with multiple delimeters-space is the default delimeter so no need to specify
-----------------------------------------
import java.util.StringTokenizer;

public class test {
public static void main(String args[])
{
String str = "Hello !ra12^there mate whats up";
int i = 0;
StringTokenizer st = new StringTokenizer(str,"!*^/");
while (st.hasMoreTokens()) {
i++;
System.out.println(st.nextToken());
}
}

}
========================================================================
Reading from a file and writing into anoter file(fis.read()-once end of the file reach it returns -1)
-----------------------------------------------------------
public class FileStreamsReadnWrite {
public static void main(String[] args) throws FileNotFoundException {
        try {
               File stockInputFile = new File("C:\\workspace\\Sample\\SampleCalc\\src\\com\\swing\\samples\\samplein.txt");
               File StockOutputFile = new File("C:\\workspace\\Sample\\SampleCalc\\src\\com\\swing\\samples\\sampleout.txt");
               FileInputStream fis = new FileInputStream(stockInputFile);
               FileOutputStream fos = new FileOutputStream(StockOutputFile);
               int count;
               while ((count = fis.read()) != -1) {
                     fos.write(count);
               }
               fis.close();
               fos.close();
        } catch (FileNotFoundException e) {
               System.err.println("FileStreamsReadnWrite: " + e);
        } catch (IOException e) {
               System.err.println("FileStreamsReadnWrite: " + e);
        }

}
========================================================================
Runnable Interace implementing run() Method example for thread
------------------------------------------------------------
class MyRunnableThread implements Runnable{

    public static int myCount = 0;
    public MyRunnableThread(){
     
    }
    public void run() {
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
        }
    }
}
public class RunMyThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        MyRunnableThread mrt = new MyRunnableThread();
        Thread t = new Thread(mrt);
        t.start();
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}
========================================================================
Extending Thread Class :-run() Method example for thread
------------------------------------------------------------
class MySmpThread extends Thread{
    public static int myCount = 0;
    public void run(){
        while(MySmpThread.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++MySmpThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
        }
    }
}
public class RunThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        MySmpThread mst = new MySmpThread();
        mst.start();
        while(MySmpThread.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++MySmpThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}
=======================================================================
Serilization and deserilization(transient object state will not be persist)
---------------------------------------------------------------------------
public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("C:/workspace/Sample/Sampleemployee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("C:/workspace/Sample/Sampleemployee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

=====================================================
UserDefinedException.java
-------------------------
class UserDefinedException extends Exception {
public UserDefinedException(String msg){
super(msg);
}
public static void main(String[] args) /*throws Exception*/   {

try {
/**
 * Throw user defined exception
 */
 throw new UserDefinedException("age must not be less than 18");

 } catch (Exception e) {
 System.out.println("catch exception");
 e.printStackTrace();
 }
 }
}
===============================================================
Reading from console and writing into file and from that file displaying in the console
--------------------------------------------------------------------------------------------
public class ConsoleToFile {
public static void main(String[] args) throws IOException {

InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);

System.out.println("Enter how many employees you want to enter");
int employeeCount=Integer.parseInt(br.readLine());

Employee e[] = new Employee[employeeCount];
int empID;
String fName, lName, emailId, mobile;

for(int i=0;i<employeeCount;i++)
{
// Employee e1=new Employee(1, "rajesh", "boggavarapu1", "mygmail1@gmail.com", "9176438661");
System.out.println(i+"Enter the EmployeeId :");
empID=Integer.parseInt(br.readLine());
System.out.println(i+"Enter the EmployeeFName :");
fName=br.readLine();
System.out.println(i+"Enter the EmployeelName :");
lName=br.readLine();
System.out.println(i+"Enter the EmployeeemailId :");
emailId=br.readLine();
System.out.println(i+"Enter the Employee mobile :");
mobile=br.readLine();
e[i]=new Employee(empID, fName, lName, emailId, mobile);
}
    FileWriter writer = new FileWriter("C:\\workspace\\Sample\\Sample\\src\\com\\hcl\\files\\temp1.txt");
    BufferedWriter bufferedWriter = new BufferedWriter(writer);
    for(int i=0;i<employeeCount;i++)
{
     bufferedWriter.write("empID");
     bufferedWriter.write("=");
     bufferedWriter.write(String.valueOf(e[i].getEmpID()));
     bufferedWriter.newLine();
    
     bufferedWriter.write("fName");
     bufferedWriter.write("=");
     bufferedWriter.write(e[i].getfName());
     bufferedWriter.newLine();
    
     bufferedWriter.write("lName");
     bufferedWriter.write("=");
     bufferedWriter.write(e[i].getlName());
     bufferedWriter.newLine();
    
     bufferedWriter.write("emailId");
     bufferedWriter.write("=");
     bufferedWriter.write(e[i].getEmailId());
     bufferedWriter.newLine();
    
     bufferedWriter.write("mobile");
     bufferedWriter.write("=");
     bufferedWriter.write(e[i].getMobile());
     bufferedWriter.newLine();
        bufferedWriter.newLine();
}
    bufferedWriter.close();
    writer.close();
    br.close();
    isr.close();

     System.out.println("===reading from file and display the file convent in the console=========================================");
    //reading from file and display the file convent in the console
 // FileReader reads text files in the default encoding.
    FileReader fileReader =  new FileReader("C:\\workspace\\Sample\\Sample\\src\\com\\hcl\\files\\temp1.txt");
    // Always wrap FileReader in BufferedReader.
    BufferedReader bufferedReader =  new BufferedReader(fileReader);
    String line = null;
    while((line = bufferedReader.readLine()) != null) {
        System.out.println(line);
    }
    // Always close files.
    bufferedReader.close();
    System.out.println("========================================================");
}
}

class Employee{
private int empID;
private String fName;
private String lName;
private String emailId;
private String mobile;

public Employee(int empID, String fName, String lName, String emailId,
String mobile) {
super();
this.empID = empID;
this.fName = fName;
this.lName = lName;
this.emailId = emailId;
this.mobile = mobile;
}
//stters and getters
}
=========================================================
Jsp implicit objects(9)
-------------------
1)Request
2)Response
3)pageContext
4)application
5)session
6)out
7)config
8)page
9)exception
============================================================
JSP scopes(Request,page,session,application)
===========================================================
JDK1.5 features
---------------
1)varargs
2)foreach
3)autoboxing\un-autoboxing
4)static import
5)generics
6)annotation
7)scanner
8)Enum
9)co-varient return types in the overriding

JDK1.7 features
----------------
Strings in switch Statement
Type Inference for Generic Instance Creation
Multiple Exception Handling
Support for Dynamic Languages
Try with Resources
Java nio Package
Binary Literals, underscore in literals
Diamond Syntax
Automatic null Handling
==================================================================
Example on Jdk1.5Features
-----------------------------
import static java.lang.Integer.*;
import static java.lang.String.format;
/**
 *
1)Generics
2)Enhanced for Loop
3)Autoboxing/Unboxing
4)Typesafe Enums
5)Varargs
6)Static Import
7)Metadata (Annotations):it allows to ovveride properly(it will check, the formal parameter datatypes,return types, (so that we will ensure that it is override not the overloading))
8)Formatting
9)Instrumentation
 * */
public class Jdk1.5Features{
public static void main(String[] args)
    {
System.out.println("===============Generics===============");
        List<String> names = new ArrayList<String>();
        names.add("Ram");
        names.add("Peter");
        names.add("Khan");
        names.add("Singh");
        System.out.println("================For -each============================");
        for (String name : names) {
            System.out.println(" Name = " + name);
        }
   
        System.out.println("=================Autoboxing==================");
        Integer age = 31;  // Autoboxing: 31 => Integer.valueOf(31)
        List<Double> weights = new ArrayList<Double>();
        weights.add(64.5);  // Autoboxing: 64.5 => Double.valueOf(64.5)
        weights.add(73.2);  // Autoboxing: 73.2 => Double.valueOf(73.2)
   
        System.out.println("===================Unboxing===================");
        if (age > 25) {  // Unboxing: age => age.intValue()
     // do something
             }
   
        double totalWeight = weights.get(0) + weights.get(1); // 137.7
        // Unboxing: weights.get(0).doubleValue()
        //           + weights.get(1).doubleValue()
        System.out.println("===================var args========================");
        System.out.println(" Sum = " + sum(41, 22, 58));
        System.out.println("====================== import static====================");
        int num = parseInt("526"); // => Integer.parseInt()
        Integer num2 = valueOf("123"); // => Integer.valueOf()
        // => String.format()
        System.out.println(format("Numbers: %d, %d", num, num2));
        // => Integer.MAX_VALUE
        System.out.println(" Integer MAX value = " + MAX_VALUE);
        System.out.println("===========================Formatting=======================");
        int m1 = 78, m2 = 93, m3= 85;
        int total = m1 + m2 + m3;
        double avg = total / 3.0;
        String result = String.format("Marks: %d, %d, %d. Total: %d, Avg: %.2f", m1, m2, m3, total, avg);
        System.out.println(result);
        /*
         *
        */
        System.out.println("=========Scanner=used to convert primitive or strings===========================");
        //we can use scanner for console ,files,network streams into appripriate variables like int,float,byte,long,double,boolean
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        System.out.println("Enter your name:");
        String name = scanner.next();
        System.out.println("Enter your age:");
        int age1 = scanner.nextInt();
        System.out.println("Enter  date of joining");

        System.out.printf("Name = %s, age = %d", name, age1);
   
    }
 static int sum(int... numbers) {// varargs
 System.out.println("===================var args======================================");
         int sum = 0;
         for (int i = 0; i < numbers.length; i++) {
             sum += numbers[i];
         }
         return sum;
     }

}
============================================================
Object class methods(9)
----------------------
1)tostring()
2)getclass()
3)equals()
4)hashcode()
5)wait()
6)notify()
7)notifyAll()
8)clone()
9)finalize()
==============================================
String,string Buffer,string builder
----------------------------------
String -immutable(not able to modify)
String buffer-mutable(able to modify)-syncronized-Theadsafe-means we can use in threads
String builder-mutable(able to modify)-non syncronized
when we have repeatable modifications useing string means it will create another object each time(un-neccessary heap will be full)
so,we can use string buffer.
String buffer and string builder are same except ,string builder is non-syncrinized
===============================================
remove() -in iterator class why we need to use (as remove () in the arraylist)
------------------------------------------------------------------------------
while iterating over on the array list ,if we want to remove some object in the arraylist ,
Then we should use iterator.remove().if we use arraylist.remove() then  we will get concurrent modification Exception at run time
(as that whole copy of the arraylist is get by iterator, it will not allow the arraylist.remove())
=======================================================
How many ways to create a object in java
----------------------------------------
There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:

1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
.
MyObject object = new MyObject();

2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

3. Using clone()
The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();

4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
=======================================================
Nothing should be there in between the method Name and return type 
======================================================================
Consumer and Producer Problem
------------------------------
ProducerConsumerTest.java
Resource.java
Producer.java
Consumer.java

1)ProducerConsumerTest.java
---------------------------
public class ProducerConsumerTest {
public static void main(String[] args) {
Resource r = new Resource();
Producer producer = new Producer(r);
Consumer consumer =new Consumer(r);
Thread t1 = new Thread(producer);//shared resources given to producer thread
Thread t2 = new Thread(consumer);//shared resources given to Consumer thread
t1.start();t2.start();

}
}
2)Resource.java
-------------
class Resource {
private int food;
private ArrayList al=new ArrayList();
private boolean foodAvailable = false;
public synchronized void produceFood(int food){
if(!foodAvailable){//no food
    this.food= food;
    al.add(food);
System.out.println("producer produced food : "+food);
foodAvailable = true;
notify();
}
else{
try {
wait();//food is there
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized int consumeFood(){
if(!foodAvailable){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
foodAvailable = false;
notify();
return food;

}
/*public synchronized ArrayList consumeFood(){
if(!foodAvailable){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
foodAvailable = false;
notify();
return al;


}*/
}
Producer.java
------------
public class Producer implements Runnable{
Resource r; 
Producer(Resource r){
this.r = r;
}
public void run(){
int i =0;
while(true){
i++;
r.produceFood(i);
if(i==10)
break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}
Consumer.java
-------------
public class Consumer implements Runnable{
Resource r;
Consumer(Resource r){
this.r = r;
}
public void run(){
int i = 0;
// List l=new ArrayList();
while(true){
i = r.consumeFood();
/*for(Object tempList:r.consumeFood())
{
System.out.print(tempList);
}*/
System.out.println("Consumer consumed food :"+i);
try {

Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==10)
break;
}
}

}
=======================================================================
Nothing should be there in between the method Name and return type 
=====================================================
when to override equals() and hashcode() : example
equals() and hascode() override when using HashMap
--------------------------------------------------
public class Car {
private String name, company;
    
    @Override
    public boolean equals(Object o) {
    Car m = (Car) o;
    return m.company.equals(this.company) && m.name.equals(this.name);
    }

    @Override
    public int hashCode() 
    {
        return name.hashCode() + company.hashCode();
    }
//public setters and getters methods
}

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

Car c1 = new Car();
c1.setCompany("Astin martin");
c1.setName("DB9");

Car c2 = new Car();
c2.setCompany("Mazda");
c2.setName("Ryuga");

Car c3 = new Car();
c3.setCompany("BMW");
c3.setName("M5");

Car c4 = new Car();
c4.setCompany("Mazda");
c4.setName("Ryuga");

HashMap<Car, String> map = new HashMap<Car, String>();

map.put(c1, "carOne");

map.put(c2, "carTwo");

map.put(c3, "carThree");

map.put(c4, "carTwoDuplicate");// this will present and previous,c2 will
// not be there (as hashmap behaviour)

// Iterate over HashMap

for (Car cr : map.keySet()) {

System.out.println(map.get(cr).toString());
/*
 * without overriding the hascode and euals 2,2d
 */

}

}

===================================================================
====================================================================
public class SingleObject {
private static    SingleObject singleObject=null;
private SingleObject(){}
public static  synchronized SingleObject getSingleInstance()
{
/*synchronized (SingleObject.class) {*/
if(singleObject==null)
{
singleObject =new SingleObject();
 System.out.println(singleObject.hashCode());
}
System.out.println(singleObject.hashCode());
return singleObject;
/*}*/
}

}
class Sing {
 public static void main(String[] args) {
 SingleObject e= SingleObject.getSingleInstance();
 System.out.println(e.hashCode());
}
}
========================================================
public class CheckedExceptionDemo {
public static void main(String[] args) {
System.out.println("starting of main method");
try {
ma();
} catch (Throwable e) {
System.out.println("Main Catch Throwable");
e.printStackTrace();
}

}
public static void ma()throws Throwable{
System.out.println("begin of ma method");
try {
throw new Throwable();
} catch (Error e) {
e.printStackTrace();
System.out.println("end of catch block");
}
catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("end of catch block");
throw new Exception();
}
System.out.println("End of ma method");
}
}
//throw new object in a method : 
Note:No exception of type Object can be thrown; an exception type must be a subclass of Throwable

2)throw new Throwable():Compile time it will resolve


when we go for abstract class or interface?
when the relation is (is-a) then,we choose abstract class
when we have relation (has-a) then we choose interface

prefer composition(has-a)  over the Inheritance(is-a)

diffrence between wait() and sleep()
wait()-it is present in Object class,
once we call wait() on current object then object level lock will be released ,and goes to blocked state
sleep()-it only causes the current thread to move into Blocked state,

without releasing any type of lock(class level,object level)
=====================================================================
samplefile.txt
-------------
id:name:IO_group_id:IO_group_name:status:mdisk_grp_id:mdisk_grp_name:capacity:type:FC_id:FC_name:RC_id:RC_name:vdisk_UID:fc_map_count:copy_count:fast_write_state:se_copy_count:RC_change:compressed_copy_count
0:vdisk0:0:io_grp0:degraded:0:mdiskgrp0:10.00GB:striped:::::60050768018300003000000000000000:0:1:empty:0:no:0
1:vdisk12:10:io_grp10:upgraded:10:mdiskgrp10:110.00GB:striped:::::60050768018300003000000000000011:10:11:empty:01:no:10

//here 2 objects in a arraylist .each object has property and the state
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;

class CommandExecutionSeparator4 
{
 
public static ArrayList getCLIList() throws IOException 
{
//Temorary START reading the data from a file and store it in a string and again store it into the file(due to unable to store multiple lines in the string) 
FileReader fileReader = new FileReader("E:\\workspaces\\sonoma\\Sample\\src\\com\\hcl\\command\\samplefile.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
int count = 1;
ArrayList headers = new ArrayList();
ArrayList valueList = new ArrayList();
ArrayList valuesLists = new ArrayList();
StringBuffer stringBuffer = new StringBuffer();

while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("\n");
}
String cliOutputString = stringBuffer.toString();
System.out.println(cliOutputString);
String[] cliOutputRows=cliOutputString.split("\n");
for (String headerOrValue : cliOutputRows)
{
if (count == 1) 
{// list
String[] header = headerOrValue.split(":");
for (int x = 0; x < header.length; x++) 
{
valueList.add(header[x]);
if (x == (header.length - 1))
count++;
}


else if (count > 1) 
{// list of list to store the values
String[] values = headerOrValue.split(":");
valueList = new ArrayList();
for (int x = 0; x < values.length; x++)
{
if (values[x].toString().equals("")) 
{
valueList.add(null);// setting the default values if value not exist
} else 
{
valueList.add(values[x]);// value to the pojo
}
if (x == (values.length - 1))// 19 properties
count++;
}
}
valuesLists.add(valueList);
}

bufferedReader.close();
return valuesLists;
}

public static void main(String[] args) throws Exception 
{
int count = 1;
ArrayList headers = null;
ArrayList valuesList = new ArrayList();
ArrayList cliList = CommandExecutionSeparator4.getCLIList();
ArrayList returnValueObjs = new ArrayList();

for (Object object : cliList)
{
if (count == 1)
{
headers = new ArrayList();
headers.addAll((ArrayList) object);
count++;
System.out.println(object);

else if (count > 1)
{
valuesList.add(object);
count++;
System.out.println(object);
}
}
Method[] methods = VolumeInfo.class.getMethods();
ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
String classNameToBeLoaded = "com.hcl.command.VolumeInfo";// package and
// class
Iterator listofvalues = valuesList.iterator();
while (listofvalues.hasNext())
{
ArrayList rowList = (ArrayList) listofvalues.next();
Class myClass = myClassLoader.loadClass(classNameToBeLoaded);
Object whatInstance = myClass.newInstance();// object of that class
for (int counter = 0; counter < headers.size(); counter++)
{
Object column = headers.get(counter);
for (Method method : methods) 
{
if (("set" + column).equalsIgnoreCase(method.getName())) //
{
method.invoke(whatInstance, new Object[] { rowList.get(counter) });//
}
}
}
returnValueObjs.add(whatInstance);
}
}
}


======================================================================
web service 
---------------
Bottom - up aproach (.java =>wsdl) using JAX-WS Command :
(D:\>wsgen -verbose -keep -cp . com.mkyong.ws.ServerInfo)-Server Producing 

Top -Down approach(wsdl=>.java)using JAX-WS command
 (C:\>wsimport -keep -verbose http://compA.com/ws/server?wsdl)-Client consuming the Web service
=======================================================================
Calculator using Swing
===============
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class Calculator extends JFrame {
    private static final String NUMBER_PROPERTY = "NUMBER_PROPERTY";
    private static final String OPERATOR_PROPERTY = "OPERATOR_PROPERTY";
    private static final String FIRST = "FIRST";
    private static final String VALID = "VALID";

    // These would be much better if placed in an enum,
    // but enums are only available starting in Java 5.
    // Code using them isn't back portable.
    private static interface Operator{
        static final int EQUALS = 0;
        static final int PLUS = 1;
        static final int MINUS = 2;
        static final int MULTIPLY = 3;
        static final int DIVIDE = 4;
    }

    private String status;
    private int previousOperation;
    private double lastValue;
    private JTextArea lcdDisplay;
    private JLabel errorDisplay;

    public static void main(String[] args) {
        // Remember, all swing components must be accessed from
        // the event dispatch thread.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Calculator calc = new Calculator();
                calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                calc.setVisible(true);
            }
        });
    }

    public Calculator() {
        super("Calculator");

        JPanel mainPanel = new JPanel(new BorderLayout());
        JPanel numberPanel = buildNumberPanel();
        JPanel operatorPanel = buildOperatorPanel();
        JPanel clearPanel = buildClearPanel();
        lcdDisplay = new JTextArea();
        lcdDisplay.setFont(new Font("Dialog", Font.BOLD, 18));
        mainPanel.add(clearPanel, BorderLayout.SOUTH);
        mainPanel.add(numberPanel, BorderLayout.CENTER);
        mainPanel.add(operatorPanel, BorderLayout.EAST);
        mainPanel.add(lcdDisplay, BorderLayout.NORTH);

        errorDisplay = new JLabel(" ");
        errorDisplay.setFont(new Font("Dialog", Font.BOLD, 12));

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(mainPanel, BorderLayout.CENTER);
        getContentPane().add(errorDisplay, BorderLayout.SOUTH);

        pack();
        resetState();
    }

    private final ActionListener numberListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JComponent source = (JComponent)e.getSource();
            Integer number = (Integer) source.getClientProperty(NUMBER_PROPERTY);
            if(number == null){
                throw new IllegalStateException("No NUMBER_PROPERTY on component");
            }

            numberButtonPressed(number.intValue());
        }
    };

    private final ActionListener decimalListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            decimalButtonPressed();
        }
    };

    private final ActionListener operatorListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JComponent source = (JComponent) e.getSource();
            Integer opCode = (Integer) source.getClientProperty(OPERATOR_PROPERTY);
            if (opCode == null) {
                throw new IllegalStateException("No OPERATOR_PROPERTY on component");
            }

            operatorButtonPressed(opCode);
        }
    };

    private final ActionListener clearListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            resetState();
        }
    };

    private JButton buildNumberButton(int number) {
        JButton button = new JButton(Integer.toString(number));
        button.putClientProperty(NUMBER_PROPERTY, Integer.valueOf(number));
        button.addActionListener(numberListener);
        return button;
    }

    private JButton buildOperatorButton(String symbol, int opType) {
        JButton plus = new JButton(symbol);
        plus.putClientProperty(OPERATOR_PROPERTY, Integer.valueOf(opType));
        plus.addActionListener(operatorListener);
        return plus;
    }

    public JPanel buildNumberPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 3));

        panel.add(buildNumberButton(7));
        panel.add(buildNumberButton(8));
        panel.add(buildNumberButton(9));
        panel.add(buildNumberButton(4));
        panel.add(buildNumberButton(5));
        panel.add(buildNumberButton(6));
        panel.add(buildNumberButton(1));
        panel.add(buildNumberButton(2));
        panel.add(buildNumberButton(3));

        JButton buttonDec = new JButton(".");
        buttonDec.addActionListener(decimalListener);
        panel.add(buttonDec);

        panel.add(buildNumberButton(0));

        // Exit button is to close the calculator and terminate the program.
        JButton buttonExit = new JButton("EXIT");
        buttonExit.setMnemonic(KeyEvent.VK_C);
        buttonExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        panel.add(buttonExit);
        return panel;

    }

    public JPanel buildOperatorPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 1));

        panel.add(buildOperatorButton("+", Operator.PLUS));
        panel.add(buildOperatorButton("-", Operator.MINUS));
        panel.add(buildOperatorButton("*", Operator.MULTIPLY));
        panel.add(buildOperatorButton("/", Operator.DIVIDE));
        return panel;
    }

    public JPanel buildClearPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1, 3));

        JButton clear = new JButton("C");
        clear.addActionListener(clearListener);
        panel.add(clear);

        JButton CEntry = new JButton("CE");
        CEntry.addActionListener(clearListener);
        panel.add(CEntry);

        panel.add(buildOperatorButton("=", Operator.EQUALS));

        return panel;
    }

    public void numberButtonPressed(int i) {
        String displayText = lcdDisplay.getText();
        String valueString = Integer.toString(i);

        if (("0".equals(displayText)) || (FIRST.equals(status))) {
            displayText = "";
        }

        int maxLength = (displayText.indexOf(".") >= 0) ? 21 : 20;
        if(displayText.length() + valueString.length() <= maxLength){
            displayText += valueString;
            clearError();
        } else {
            setError("Reached the 20 digit max");
        }

        lcdDisplay.setText(displayText);
        status = VALID;
    }

    public void operatorButtonPressed(int newOperation) {
        Double displayValue = Double.valueOf(lcdDisplay.getText());

//        if(newOperation == Operator.EQUALS && previousOperation != //Operator.EQUALS){
//            operatorButtonPressed(previousOperation);
//        } else {
            switch (previousOperation) {
                case Operator.PLUS:
                    displayValue = lastValue + displayValue;
                    commitOperation(newOperation, displayValue);
                    break;
                case Operator.MINUS:
                    displayValue = lastValue - displayValue;
                    commitOperation(newOperation, displayValue);
                    break;
                case Operator.MULTIPLY:
                    displayValue = lastValue * displayValue;
                    commitOperation(newOperation, displayValue);
                    break;
                case Operator.DIVIDE:
                    if (displayValue == 0) {
                        setError("ERROR: Division by Zero");
                    } else {
                        displayValue = lastValue / displayValue;
                        commitOperation(newOperation, displayValue);
                    }
                    break;
                case Operator.EQUALS:
                    commitOperation(newOperation, displayValue);
//            }
        }
    }

    public void decimalButtonPressed() {
        String displayText = lcdDisplay.getText();
        if (FIRST.equals(status)) {
            displayText = "0";
        }

        if(!displayText.contains(".")){
            displayText = displayText + ".";
        }
        lcdDisplay.setText(displayText);
        status = VALID;
    }

    private void setError(String errorMessage) {
        if(errorMessage.trim().equals("")){
            errorMessage = " ";
        }
        errorDisplay.setText(errorMessage);
    }

    private void clearError(){
        status = FIRST;
        errorDisplay.setText(" ");
    }

    private void commitOperation(int operation, double result) {
        status = FIRST;
        lastValue = result;
        previousOperation = operation;
        lcdDisplay.setText(String.valueOf(result));
    }

    /**
     * Resets the program state.
     */
    void resetState() {
        clearError();
        lastValue = 0;
        previousOperation = Operator.EQUALS;

        lcdDisplay.setText("0");
    }
}
------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment