access SQL Server 2008 from SQL Developer
Tuesday, February 5, 2013
Wednesday, November 7, 2012
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());
}
}
--------
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
Subscribe to:
Posts (Atom)



