Wednesday, November 7, 2012

sql in shot

SQL in shot

Scanner in Java

package com.scanner;

import java.util.Scanner;
/**
 * 
 * @author Thanooj K
 *
 */
class ConsoleMe {

 static Scanner sc = new Scanner(System.in);

 public static EnterMe askYorN(String prompt) {
  while (true) {
   String input;
   System.out.print("\n" + prompt + " (Y or N) ");
   input = sc.next();
   if (input.equalsIgnoreCase("Y"))
    return new EnterMe("Y", true);
   else if (input.equalsIgnoreCase("N"))
    return new EnterMe("N", false);
   ;
  }
 }
}

class EnterMe {

 private String yOrN;
 private boolean status;

 public EnterMe(String yOrN, boolean status) {
  super();
  this.yOrN = yOrN;
  this.status = status;
 }

 public boolean isStatus() {
  return status;
 }

 public String getyOrN() {
  return yOrN;
 }

}

public class ScannerMe {
 public static void main(String[] args) {
  EnterMe enterMe = ConsoleMe.askYorN("Keep going?");
  if (enterMe != null && enterMe.isStatus()) {
   System.out.println("You have chosen :: " + enterMe.getyOrN() + " ,"
     + enterMe.isStatus());
  } else {
   System.out.println("You have chosen :: " + enterMe.getyOrN() + " ,"
     + enterMe.isStatus());
  }
 }
}

output:

Keep going? (Y or N) :: Y
You have chosen :: Y ,true
 
 
 
------------------------------------------------


package com.scanner;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

class ConsoleMeForSearchText {

 

 public void consoleMeForSearchText(Path dirPath) {
  DirectoryStream < Path > dirStream = null;
  try {
      
      // 2. Create a DirectoryStream instance using
      // Files.newDirectoryStream(). The instance
      // is created by passing the Path of the directory
      // to be searched and the type of files as a filter
      // here we are using filter to search all pdf files
      // in the directory
      dirStream = Files.newDirectoryStream(dirPath, "*.pdf");
    
      // 3. Looping each file and printing the name
      // on the console
      for (Path entry : dirStream) {
    
       System.out.println(entry.getParent() + "\\" +entry.getFileName());
    
      }
     } catch (IOException e) {
    
      System.out.println(e.getMessage());
    
     } finally {
      // 4. Closing the DirectoryStream
      try {
    
       dirStream.close();
    
      } catch (IOException e) {
    
       e.printStackTrace();
      } 
     }
 }
}
 
public class SearchFilesInDirectory {
 
 static Scanner sc = new Scanner(System.in);
 
 
 public static void main(String[] args) {
 
  String dirPathStr = sc.next(); 
  Path dirPath = Paths.get(dirPathStr);
  ConsoleMeForSearchText consoleMeForSearchText = new ConsoleMeForSearchText(); 
  
  consoleMeForSearchText.consoleMeForSearchText(dirPath);
 
   
 }
}
 output: (give the folder path to search for all PDFs)
C:\Users\Thanooj\Downloads\desktopNotes



C:\Users\Thanooj\Downloads\desktopNotes\A-Business-Case-for-Ajax-with-GWT-JAOO-2006.pdf
C:\Users\Thanooj\Downloads\desktopNotes\getstartderby_JavaDB.pdf
C:\Users\Thanooj\Downloads\desktopNotes\GWT in Practice.pdf
C:\Users\Thanooj\Downloads\desktopNotes\head_first_sql.pdf
C:\Users\Thanooj\Downloads\desktopNotes\Manning_GWT_in_Action.pdf
C:\Users\Thanooj\Downloads\desktopNotes\microsoft_sql_server_2008_high_availability.pdf
C:\Users\Thanooj\Downloads\desktopNotes\MR. K THANOOJ-12032013 - 11042013.pdf
C:\Users\Thanooj\Downloads\desktopNotes\Prentice.Hall.Google.Web.Toolkit.Applications.Dec.2007.pdf
C:\Users\Thanooj\Downloads\desktopNotes\Pro Web 2.0 - Application Development with GWT.pdf
C:\Users\Thanooj\Downloads\desktopNotes\professional_microsoft_sql_server_2008_programming.pdf
C:\Users\Thanooj\Downloads\desktopNotes\sams_teach_yourself_sql_in_24_hours_5th_edition.pdf
C:\Users\Thanooj\Downloads\desktopNotes\SQL Server Essential Guide FINAL.pdf
C:\Users\Thanooj\Downloads\desktopNotes\sql_pocket_guide_third_edition.pdf
C:\Users\Thanooj\Downloads\desktopNotes\Writing-Big-Apps-with-GWT-TSSJS-Vegas-2007.pdf

Enum in Java


package com;

interface MyEnum {

 public abstract String inString();

}

public class MyMonth {

 public enum Months implements MyEnum {

  JAN(1) {

   @Override
   public String inString() {

    return "JANUARY";

   }
  },
  FEB(2) {

   @Override
   public String inString() {

    return "FEBRUARY";

   }
  },
  MAR(3) {

   @Override
   public String inString() {

    return "MARCH";

   }
  },
  ARL(4) {

   @Override
   public String inString() {

    return "APRIL";

   }
  };

  private int value;

  private Months(int value) {

   this.value = value;

  }

  public int getValue() {

   return value;

  }

 };

 public static void main(String[] args) {

  for (MyMonth.Months month : MyMonth.Months.values()) {

   System.out.println("month:- " + month + " :: " + month.getValue()
     + " :: " + month.inString());

  }

  switch (MyMonth.Months.ARL) {

  case JAN:

   System.out.println("JANUARY");

   break;

  case FEB:

   System.out.println("FEBRUARY");

   break;

  case MAR:

   System.out.println("MARCH");

   break;

  case ARL:

   System.out.println("APRIL");

  }

 }

}
OUTPUT
---------


Tuesday, September 11, 2012

Short explain of Externalization


Externalization is nothing but serialization but by implementing Externalizable interface to persist and restore the object. To externalize your object, you need to implement Externalizable interface that extends Serializable interface. Here only the identity of the class is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances which means you will have complete control of what to serialize and what not to serialize. But with serialization the identity of all the classes, its superclasses, instance variables and then the contents for these items is written to the serialization stream. But to externalize an object, you need a default public constructor.
Unlike Serializable interface, Externalizable interface is not a marker interface and it provides two methods - writeExternal and readExternal. These methods are implemented by the class to give the class a complete control over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate with the supertype to save its state. These methods supersede customized implementations of writeObject and readObject methods.
How serialization happens? JVM first checks for the Externalizable interface and if object supports Externalizable interface, then serializes the object using writeExternal method. If the object does not support Externalizable but implement Serializable, then the object is saved using ObjectOutputStream. Now when an Externalizable object is reconstructed, an instance is created first using the public no-arg constructor, then the readExternal method is called. Again if the object does not support Externalizable, then Serializable objects are restored by reading them from an ObjectInputStream.
 
/**
 * Externalizable Impl
 */
package com;

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 * @author thanooj
 *
 */
public class Employee implements Externalizable {

    private int empId;
    private String firstName;
    private String lastName;
    private int age;
   
    public Employee() {}
   
    public Employee(int empId, String firstName, String lastName, int age) {
        super();
        this.empId = empId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    /* (non-Javadoc)
     * @see java.io.Externalizable#readExternal(java.io.ObjectInput)
     * Note: we need to follow the order of writeExternal did.
     */
    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        empId = in.readInt();
        firstName = (String)in.readObject();
        age = in.readInt();
    }

    /* (non-Javadoc)
     * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
     */
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(empId);
        out.writeObject(firstName);
        out.writeInt(age);
    }

    @Override
    public String toString() {
        return empId + " "+firstName+" "+lastName+" "+age;
    }
   
    public static void main(String[] args) {
        Employee empSe = new Employee(1, "rama", "sri", 29);
        Employee empDe = null;
        //serialize the car
        try {
            FileOutputStream fo = new FileOutputStream("tmp");
            ObjectOutputStream so = new ObjectOutputStream(fo);
            so.writeObject(empSe);
            so.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // de-serialize the Car
        try {
            FileInputStream fi = new FileInputStream("tmp");
            ObjectInputStream si = new ObjectInputStream(fi);         
            empDe = (Employee) si.readObject();
            System.out.println(empDe);
        }
        catch (Exception e) {
             e.printStackTrace();
        }
    }
}

output:
--------
1 rama null 29

Tuesday, September 4, 2012

Explained Singleton with SeDe of the Emp instance




/**
 * SeDe
 * Explained Cloning, Singleton and SeDe of the Emp instance.
 *
 * for readResolve() and writeReplace() method explanations look-
 * http://docs.oracle.com/javase/1.3/docs/guide/serialization/spec/serialTOC.doc.html
 *
 */
package com.sede;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * @author u2fv
 *
 */
class Test {

}

class Emp implements Serializable, Cloneable {
private int eNo;
private String eName;
private transient float sal;
private Test test;
private static Emp emp;

private Emp() {
this.eNo = 0;
this.eName = null;
this.sal = 0.0f;
}

private Emp(int eNo, String eName, float sal) {
super();
this.eNo = eNo;
this.eName = eName;
this.sal = sal;
}

public static synchronized Emp getInstance() {
System.out.println("inside getInstance()");
if (emp == null) {
emp = new Emp();
}
return emp;
}

public static synchronized Emp getInstance(int i, String name, float sal) {
System.out.println("inside getInstance(1,2,3)");
if (emp == null) {
emp = new Emp(1, "rama", 3.4f);
}
return emp;
}

private Object readResolve() throws ObjectStreamException {
System.out.println("inside readResolve()");
return emp;
}

private Object writeReplace() throws ObjectStreamException {
System.out.println("inside writeReplace()" + " " + emp);
return emp;
}

@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException(
"You have no privileges to clone Emp instance");
}

@Override
public String toString() {
return eNo + " " + eName + " " + sal;
}

}

class SeDe {

public void doSe(Emp emp) {
try {
FileOutputStream fOS = new FileOutputStream("Myfile.ser");
ObjectOutputStream oOS = new ObjectOutputStream(fOS);
oOS.writeObject(emp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public Emp doDe(Emp emp) {
try {
FileInputStream fOS = new FileInputStream("Myfile.ser");
ObjectInputStream oOS = new ObjectInputStream(fOS);
emp = (Emp) oOS.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return emp;
}

public Emp doDeSecondTime(Emp emp) {
try {
FileInputStream fOS = new FileInputStream("Myfile.ser");
ObjectInputStream oOS = new ObjectInputStream(fOS);
emp = (Emp) oOS.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return emp;
}
}

public class TestSeDe {

/**
* @param args
*/
public static void main(String[] args) {
// Emp emp = Emp.getInstance();
Emp emp = Emp.getInstance(1, "rama", 2.3f);
SeDe seDe = new SeDe();
seDe.doSe(emp);
emp = null;
emp = seDe.doDe(emp);
System.out.println(emp + " || hashCode: " + emp.hashCode());
Emp emp1 = null;
emp1 = seDe.doDeSecondTime(emp1);
System.out.println(emp1 + " || hashCode: " + emp1.hashCode());
}

}

Output:
--------

Tuesday, July 3, 2012

A quick way to output the fields of an object

The Apache Jakarta Commons Lang project has many useful classes, including the ToStringBuilder class. This class has a very handy set of static reflectionToString methods that use reflection to read the values of an object's fields and then display their values.


/** * Code snippet to work with ToStringBuilder from commons-lang jar with log4j */ 
package com; 
import org.apache.commons.lang.builder.ToStringBuilder; 
import org.apache.commons.lang.builder.ToStringStyle; 
import org.apache.log4j.Logger; 
/** * @author thanooj * */ 
class Test {
 private int eno; 
 private String ename; 
 private float sal; 
 public Test(int eno, String ename, float sal) {
  super(); 
  this.eno = eno; 
  this.ename = ename; 
  this.sal = sal; 
  } 
  // setters and getters 
  } 
public class ToStringBuilderTest {
/** * @param args */ 
public static void main(String[] args) {
 Logger logger = Logger.getLogger(ToStringBuilderTest.class); 
 Test test = new Test(1, "rama", 45000.0f); 
 logger.debug("Test object is created."); 
 String str1 = ToStringBuilder.reflectionToString(test, ToStringStyle.DEFAULT_STYLE); 
 logger.debug("Test object is displed in : " + str1); 
 String str2 = ToStringBuilder.reflectionToString(test, ToStringStyle.MULTI_LINE_STYLE); 
 logger.debug("Test object is displed in : " + str2); 
 String str3 = ToStringBuilder.reflectionToString(test, ToStringStyle.NO_FIELD_NAMES_STYLE); 
 logger.debug("Test object is displed in : " + str3); 
 String str4 = ToStringBuilder.reflectionToString(test, ToStringStyle.SHORT_PREFIX_STYLE); 
 logger.debug("Test object is displed in : " + str4); 
 String str5 = ToStringBuilder.reflectionToString(test, ToStringStyle.SIMPLE_STYLE); 
 logger.debug("Test object is displed in : " + str5); 
} 
}
 
 
log4j.properties :


 
# Root logger option
log4j.rootLogger=DEBUG, stdout
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 

package structure:


Output:


Design Patterns in JAVA

1. Flyweight Design Pattern 

Discussion


The Flyweight pattern describes how to share objects to allow their use at fine granularities without prohibitive cost. Each “flyweight” object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked.
/**
 * Interface Flyweight to provide extrinsic operations for the client.
 */
package com.flyweight;

public interface Flyweight {

    void doMath(int a, int b);
}
------------
/**
 * Class implement Flyweight to provide add operation.
 */
package com.flyweight;

public class FlyweightAdder implements Flyweight {

    String operation;

    public FlyweightAdder() {
        operation = "adding";
        try {
            System.out.println(operation);
            System.out.println(System.currentTimeMillis());
            Thread.sleep(3000);
            System.out.println(System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.flyweight.Flyweight#doMath(int, int)
     */
    @Override
    public void doMath(int a, int b) {
        System.out.println(operation + " " + a + " and " + b + ": " + (a + b));
    }

}
------------------
/**
 * Class implement Flyweight to provide subtract operation.
 */
package com.flyweight;

public class FlyweightSubtractor implements Flyweight {

    String operation;

    public FlyweightSubtractor() {
        operation = "subtracting";
        try {
            System.out.println(operation);
            System.out.println(System.currentTimeMillis());
            Thread.sleep(3000);
            System.out.println(System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.flyweight.Flyweight#doMath(int, int)
     */
    @Override
    public void doMath(int a, int b) {
        System.out.println(operation + " " + a + " and " + b + ": " + (a - b));
    }

}
---------------------
/**
 * Class FlyweightFactory is a singleton pattern contains Flyweight pool. 
 * picks requested Flyweight instance from pool and provides operations by client.   
 */
package com.flyweight;

import java.util.HashMap;
import java.util.Map;

public class FlyweightFactory {

    private static FlyweightFactory flyweightFactory;

    private Map flyweightPool;

    private FlyweightFactory() {
        flyweightPool = new HashMap();
    }

    public static FlyweightFactory getInstance() {
        if (flyweightFactory == null) {
            flyweightFactory = new FlyweightFactory();
        }
        return flyweightFactory;
    }

    public Flyweight getFlyweight(String key) {
        if (flyweightPool.containsKey(key)) {
            return flyweightPool.get(key);
        } else {
            Flyweight flyweight;
            if ("add".equals(key)) {
                flyweight = new FlyweightAdder();
            } else {
                flyweight = new FlyweightSubtractor();
            }
            flyweightPool.put(key, flyweight);
            return flyweight;
        }
    }

}
-------------------
/**
 *Code Snippet to get flyweight object from pool 
 */
package com.flyweight;

public class FlyweightDemo {

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

        FlyweightFactory flyweightFactory = FlyweightFactory.getInstance();

        for (int f = 1; f < 6; f++) {
            Flyweight flyweightAdder = flyweightFactory.getFlyweight("add");
            flyweightAdder.doMath(f, f);

            Flyweight flyweightSubtractor = flyweightFactory.getFlyweight("subtract");
            flyweightSubtractor.doMath(f, f);
        }
    }
}
----------

Check list

  1. Ensure that object overhead is an issue needing attention, and, the client of the class is able and willing to absorb responsibility realignment.
  2. Divide the target class’s state into: shareable (intrinsic) state, and non-shareable (extrinsic) state.
  3. Remove the non-shareable state from the class attributes, and add it the calling argument list of affected methods.
  4. Create a Factory that can cache and reuse existing class instances.
  5. The client must use the Factory instead of the new operator to request objects.
  6. The client (or a third party) must look-up or compute the non-shareable state, and supply that state to class methods.

Rules of thumb


  1. Whereas Flyweight shows how to make lots of little objects, Facade shows how to make a single object represent an entire subsystem.
  2. Flyweight is often combined with Composite to implement shared leaf nodes.
  3. Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight.
  4. Flyweight explains when and how State objects can be shared.

Thursday, June 28, 2012

Online Java Simple Editor

Here is the simple and user friendly Online Java Editor/IDE.  - Compilr
Below here we can see the sample code which is ready to RUN.














After running the sample code, we can the output on console



Wednesday, June 27, 2012

How HashMap works in Java

A collection allows key+value pair and
HashMap accept null while Hashtable doesn't.
HashMap is not synchronized, hashMap is fast, etc.,
Hashtable based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Do you Know how HashMap works in Java
or
How does get () method of HashMap works in Java

HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from HashMap. When we pass an object to put () method to store it on HashMap, it's implementation calls hashcode() method by applying that hashcode on its own hashing funtion it identifies a bucket location for storing key+value pair, important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic.

What will happen if two different objects have same hashcode?

Remember, equals and hashCode() contract that two unequal object in Java very much can have equal hashcode.
"Since hashcode () is same, bucket location would be same and collision occurs in hashMap,
Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list.
How will you retrieve if two different objects have same hashcode?

get() method uses keys hashcode to find bucket location and retrieves value object.
In the case of collision that there are two objects are stored in same bucket, by traversal in linked list until it will find the value object.

















 Collision resolution -

1. Chaining :

Hash collision resolved by chaining.





2. Open addressing :

Hash collision resolved by linear probing (interval=1).

Hashtable
HashMap
Introduced with JDK 1.0 version, the starting version of Java
Introduced with JDK 1.2
Part of legacy classes (the data structures of JDK 1.0 are known as legacy classes)
Methods of Hashtable are synchronized by default
Methods are not synchronized by default
Does not permit null values (trying to add, throwsNullPointerException)
Permits null values (either key or value)
Enumeration interface is used for iterating keys
Iterator is used for iterating the keys
Enumerator is not fail-fast
Iterator is fail-fast
Safe for multithreaded applications
Better for non-threaded applications
Low performance due to synchronization
High performance
Hashtable is serialized
HashMap is not serialized