Monday, October 10, 2011

Read Excel file using poi-3.0.1-FINAL-20070705.jar

Read Excel file using poi-3.0.1-FINAL-20070705.jar code as below

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
*
* @author user
*/
public class Demo {

public static void main(String arg[]) {
Demo demo = new Demo();
String[][] strCom = {{"A", "String"}, {"B", "String"}, {"E", "String"}};
ArrayList alRTags = demo.readExcelValue("C:\\Documents and Settings\\user\\Desktop\\def.xls", 5, strCom);
for (int i = 0; i < alRTags.size(); i++) {
//int uid = vIAObj.getOPCTagMasterUniqueID();
System.out.println(alRTags.get(i));
}
}

public ArrayList readExcelValue(String strFileName, int len, String[][] strCom) {
ArrayList alRTags = null;
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(strFileName));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
int rows = sheet.getPhysicalNumberOfRows();
row = sheet.getRow(0);
String strTagName = "";

HashMap hmRC = new HashMap();
HashMap hmRCN = new HashMap();
for (int i = 0; i < strCom.length; i++) {
hmRC.put(strCom[i][0], strCom[i][1]);
}

String heading = "";

for (int j = 0; j <= len; j++) //for (int j = 0; j <= 5; j++) //
{
if (row != null) {
cell = row.getCell((short) j);
if (cell != null) {
String strH = String.valueOf(cell.getStringCellValue());
if (hmRC.containsKey(strH)) {
hmRCN.put(j, hmRC.get(strH));
}
heading += strH + ",";
}
}
}

if (heading == null) {
heading = "NoData";
} else if (heading.trim().equals("")) {
heading = "NoData";
}
System.out.println("heading " + heading);

alRTags = new ArrayList();
for (int r = 1; r <= rows; r++) {
row = sheet.getRow(r);
if (row != null) {
for (int i = 0; i < len; i++) {
strTagName = "NA";

if (hmRCN.containsKey(i)) {
cell = row.getCell((short) i);
try {
if (hmRCN.get(i).equals("String")) {
strTagName = String.valueOf(cell.getStringCellValue());
} else {
strTagName = String.valueOf(cell.getNumericCellValue());
}
} catch (Exception e) {
}
alRTags.add(strTagName);
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
}
return alRTags;
}
}

Wednesday, August 17, 2011

How to unistall oracle 10g Completely

I tried for uninstalling Oracle,
First I removed from Add/Remove Programs.. But its not removed entirely..
When I reinstall again ...It's installing on another location...
So really its irritated like anything...

Then I followed below steps then its worked fine...

# Stop any Oracle services that have been left running.
Start->Settings->Control Panel->Services
Look for any services with names starting with 'Oracle' and stop them.

# Run regedit and delete the following keys (some may have slightly different names in your registry):
HKEY_CURRENT_USER\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servic es\EventLog\Application\Oracle.oracle
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servic es\OracleDBConsole
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servic es\Oracle10g_home
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servic es\OraclService

Note that the services control panel will still show the old services until you reboot.

# Delete the Oracle home directory
C:\Oracle

# Delete the Oracle Program Files directory:
C:\Program Files\Oracle

Note: For above steps , while deleting may be some dll files makes some problem
like cant delete access denied ... For that rename and move that specfied dll then restart the m/c then delete


# Delete the Oracle Start Menu shortcuts directory:
C:\Documents and Settings\All Users\Start Menu\Programs\Oracle*
Where * indicates the name of your install. Look for and remove all Oracle directories from that location.

# Remove Oracle refereces from the path. To edit your path go to:
Start->Settings->Control Panel->System->Advanced->Environment Variables
Edit both of the environment variables user PATH and system PATH. Remove any Oracle references in them.

# Remove Oracle.DataAccess and any Polic.Oracle files from the GAC which is at:
C:\Windows\assembly\

Your system is Oracle free after this. So go ahead and now install a new instance of Oracle.

Thursday, July 14, 2011

How do I get process id of a Java application?

import java.lang.management.RuntimeMXBean;

public class GetProcessID {
public static void main(String[] args) {
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

//
// Get name representing the running Java virtual machine.
// It returns something like 6460@AURORA. Where the value
// before the @ symbol is the PID.
//
String jvmName = bean.getName();
System.out.println("Name = " + jvmName);

//
// Extract the PID by splitting the string returned by the
// bean.getName() method.
//
long pid = Long.valueOf(jvmName.split("@")[0]);
System.out.println("PID = " + pid);
}


Note :
Killing process based on Processid
Process p = Runtime.getRuntime().exec("taskkill /pid PROCESSID /f");

Tuesday, June 14, 2011

OpenPDFUsingJava

import java.awt.Desktop;
import java.io.File;

/**
*
* @author R.Amirtharaj
*/
public class OpenPDFUsingJava {

public static void main(String[] args) {

try {

File pdfFile = new File("C:"+File.separator+"MyFile.pdf");
if (pdfFile.exists()) {

if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(pdfFile);
} else {
System.out.println("Awt Desktop is not supported!");
}

} else {
System.out.println("File is not exists!");
}

System.out.println("Done");

} catch (Exception ex) {
ex.printStackTrace();
}

}


}

Thursday, April 21, 2011

Creational Patterns : Prototype

Creational Patterns : Prototype (Make new objects by cloning the objects which you set as prototypes)


When to use ?

Prototype design is one of the design pattern under creational design pattern. This pattern describes how to clone object. Whenever application doesn’t need to create new object or object creation is more expensive than cloning will help to resolve.


Example:

We will consider Product example where we can clone product with Book and Cloths Classes.Product.java is a abstract java class which implements Cloneable interface. Class ’title’ & ‘price’ and there getter & setter methods and also implemeted clone() method. This method creates and return the copy of the super class.


/**
*
* @author R.Amirtharaj
*/
public abstract class Product implements Cloneable {
private String title;
private String price;
public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}

Book.java and Cloths.java extends Product and having separate variables author & size which have getter and setter methods in it.

/**
*
* @author R.Amirtharaj
*/
public class Book extends Product {
private String author;

public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}

/**
*
* @author R.Amirtharaj
*/
public class Cloths extends Product {
private int size;

public int getSize() {
return size;
}

public void setSize(int size) {
this.size = size;
}
}

ProductFactory.java is the factory where it will produce the products and adding in HashMap based on key as product title and value as product.

/**
*
* @author R.Amirtharaj
*/

public class ProductFactory {
private static Hashtable productMap = new Hashtable();

public static Product getProduct(String productCode) {
Product cachedProduct = (Product) productMap.get(productCode);
return (Product) cachedProduct.clone();
}

public static void loadCache() {
Book book = new Book();
book.setTitle("Java best practices");
book.setAuthor("Amirtharaj");
book.setPrice("1000");
productMap.put(book.getTitle(), book);
Cloths cloths = new Cloths();
cloths.setTitle("Jeans");
cloths.setSize(32);
cloths.setPrice("450");
productMap.put(cloths.getTitle(),cloths);
}
}


Demo.java is product outlet, which will load the cashe from the ProductFactory by calling ProductFactory.loadCache(); and clone the product by getting the product from ProductFactory


/**
*
* @author R.Amirtharaj
*/
public class Demo {
public static void main(String[] args) {
ProductFactory.loadCache();

Book clonedBook = (Book) ProductFactory.getProduct("Java best practices");
System.out.println("Product cloned as Book");
System.out.println("Title = " + clonedBook.getTitle());
System.out.println("Author = " + clonedBook.getAuthor());
System.out.println("Price = " + clonedBook.getPrice());

System.out.println("Product cloned as Cloths");
Cloths clonedCloths = (Cloths) ProductFactory.getProduct("Jeans");
System.out.println("Title = " + clonedCloths.getTitle());
System.out.println("Size = " + clonedCloths.getSize());
System.out.println("Price = " + clonedCloths.getPrice());
}
}

Advantage of prototype design pattern

Adding and removing objects at runtime
Creating cloned object based on the values
It reduced the inheritance of the class (sub classing)


Usage of prototype design pattern

When the classes to instantiate are specified at run time.
When you want to avoid building a class hierarchy of factories that parallels the class hierarchy of products.
When instances of a class can have one of only a few combinations of state.

Creational Patterns : Builder Pattern

Creational Patterns - Builder Pattern (Make and return one object various ways)


When to use ?

Builder patten will divide complex in to simple steps. Its nothing but building complex object by simple objects. Its kind of building complex objects in to step by step simple objects.

Example :

Need to build specifications details of cars for specific brand . Lets take example as we need to build specification details for AudiS6 and AudiS7.

I will show in java example how to build car specifications

First need to create Car object this is contains specifications of a car product. It is a POJO object.

/**
*
* @author R.Amirtharaj
*/
public class Car {

public boolean isPowerSteering() {
return powerSteering;
}

public void setPowerSteering(boolean powerSteering) {
this.powerSteering = powerSteering;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}
private double price;
private boolean powerSteering;

@Override
public String toString()
{
String output = "";
output += ("Price = "+price+"\n");
output += ("powerSteering = "+powerSteering+"\n");
return output;
}
}

Now we are going show Car Builder abstract builder class.

/**
*
* @author R.Amirtharaj
*/
public abstract class CarBuilder
{

protected Car car;

public Car getCar() {
return car;
}

public void createNewCar() {
car = new Car();
}

public abstract void setPowerSteering();

public abstract void setPrice();
}


The above java program show abstract builder class contains 2 abstract function which need to be implemented in derived class.
Below example shows how to create concrete class by extending car builder abstract class. We will create AudiS6 & AudiS7 concrete classes

which extends CarBuilder abstract builder class.

Concrete AudiS6 class

/**
*
* @author R.Amirtharaj
*/
public class AudiS6 extends CarBuilder
{

@Override
public void setPowerSteering() {
car.setPowerSteering(true);
}

@Override
public void setPrice() {
car.setPrice(2500000);
}

}


Concrete AudiS7 class

/**
*
* @author R.Amirtharaj
*/
public class AudiS7 extends CarBuilder
{

@Override
public void setPowerSteering() {
car.setPowerSteering(true);
}

@Override
public void setPrice() {
car.setPrice(3000000);
}

}

Now we all set ready by building small building blocks. Now we need to create Specifications director which will build the provided car

specifications.

Below is java code for Specifications director class

/**
*
* @author R.Amirtharj
*/
public class Specification {

private CarBuilder carBuilder;

public void setCarBuilder(CarBuilder aCarBuilder) {
carBuilder = aCarBuilder;
}

public Car getCar() {
return carBuilder.getCar();
}

public void constructSpecifications() {
carBuilder.createNewCar();
carBuilder.setPowerSteering();
carBuilder.setPrice();
}
}


Everything is created. Now we can create example of AudiS6 and AudiS7 car specification builder patten.
Below is example for creating specifications for AudiS6 and AudiS7

/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String arg[])
{
Specification spec = new Specification();

CarBuilder audis6 = new AudiS6();
CarBuilder audis7 = new AudiS7();

// Specification for AudiS6
spec.setCarBuilder(audis6);
spec.constructSpecifications();
Car audis6_car = spec.getCar();
System.out.println("Specifiction for AudiS6");
System.out.println(audis6_car.toString());

// Specification for AudiS7
spec.setCarBuilder(audis7);
spec.constructSpecifications();
Car audis7_car = spec.getCar();
System.out.println("Specifiction for AudiS7");
System.out.println(audis7_car.toString());

}
}


Usage of builder patten in real time

* Build the complex objects by specifying there behavior and specifications . This object will be used as wrapper for constructing of building objects.
* It will avoid process of building complex objects form

Wednesday, April 13, 2011

Design Pattern : Abstract Factory Pattern

Creational Patterns - Abstract Factory Pattern ( Sets of methods to make various objects )

This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes.

Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.

When to use ?
One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.


Example :

Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for. The different parts of computer are, say RAM and Processor. The different types of computers are PC and Server.

So, here we have an abstract base class Computer.

/**
*
* @author R.Amirtharaj
*/
public abstract class Computer {
public abstract Parts getRAM();
public abstract Parts getProcessor();
}


This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The

specification of Parts will be different for different types of computers. Let’s have a look at the class Parts.

/**
*
* @author R.Amirtharaj
*/
public class Parts {

private String specification;

public Parts(String specification) {
this.specification = specification;
}

public String getSpecification() {
return specification;
}
}

And now lets go to the sub-classes of Computer.

/**
*
* @author R.Amirtharaj
*/
public class PC extends Computer {

/**
* Method over-ridden from Computer, returns the Parts ideal for
* PC
* @return Parts
*/
public Parts getRAM() {
return new Parts("512 MB");
}

/**
* Method over-ridden from Computer, returns the Parts ideal for
* PC
* @return Parts
*/
public Parts getProcessor() {
return new Parts("Celeron");
}
}



/**
*
* @author R.Amirtharaj
*/
public class Server extends Computer {

/**
* Method over-ridden from Computer, returns the Parts ideal for
* Server
* @return Parts
*/
public Parts getRAM() {
return new Parts("4 GB");
}

/**
* Method over-ridden from Computer, returns the Parts ideal for
* Server
* @return Parts
*/
public Parts getProcessor() {
return new Parts("Intel P 4");
}
}

Now let’s have a look at the Abstract factory which returns a factory “Computer”

/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String arg[])
{
Demo abstarcfactorydemo = new Demo();
Computer pc = abstarcfactorydemo.getComputer("PC");
System.out.println("PC Specification ");
System.out.println("RAM = "+pc.getRAM().getSpecification());
System.out.println("Processor ="+pc.getProcessor().getSpecification());

Computer server = abstarcfactorydemo.getComputer("Server");
System.out.println("Server Specification ");
System.out.println("RAM = "+server.getRAM().getSpecification());
System.out.println("Processor ="+server.getProcessor().getSpecification());
}

public Computer getComputer(String computerType) {
Computer comp = null;
if (computerType.equals("PC")) {
comp = new PC();
} else if (computerType.equals("Server")) {
comp = new Server();
}
return comp;
}
}

Monday, April 11, 2011

Design Pattern : Factory Pattern

Creational Patterns - Factory Pattern ( Methods to make and return components of one object various ways):


When to use ?

If we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.

The Factory patterns can be used in following cases:

1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.


Example:

Below Example have Person as a Super class and Male and Female extends Person.Finally in main program we can create person object based on Male or Female.


/**
*
* @author R.Amirtharaj
*/
public class Person {

// Name of the Person
private String strName;
// Gender : M or F
private String strGender;

public String getStrGender() {
return strGender;
}

public void setStrGender(String strGender) {
this.strGender = strGender;
}

public String getStrName() {
return strName;
}

public void setStrName(String strName) {
this.strName = strName;
}

}



/**
*
* @author R.Amirtharaj
*/
public class Male extends Person {

public Male(String strName) {
System.out.println("Hello Mr. " + strName);
}
}

/**
*
* @author R.Amirtharaj
*/
public class FeMale extends Person {

public FeMale(String strName) {
System.out.println("Hello Ms. " + strName);
}
}

/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String args[]) {
Demo factoryDemo = new Demo();
factoryDemo.getPerson(args[0], args[1]);
//factoryDemo.getPerson("Amir", "M");

}

public Person getPerson(String strName, String strGender) {
if (strGender.equals("M")) {
return new Male(strName);
} else if (strGender.equals("F")) {
return new FeMale(strName);
} else {
return null;
}
}
}

Friday, April 8, 2011

Design Pattern : Singleton Pattern

Creational Patterns - Singleton Pattern(A class distributes the only instance of itself)



When to use ?
There are some instances in the application where we have to use just one instance of a particular class.


Below Example, Display and FDisplay Class having printwithDateandTime method , it will print with currentTime

APPROACH 1:
We use Singleton pattern for this and instantiate the Display when the first request hits

import java.sql.Timestamp;
/**
*
* @author R.Amirtharj
*/
public class Display {

// singleton - pattern
private static Display display = null;

public static Display getDisplay() {
return display;
}

// initialises the display, creates an object
public static void initialize() {
if(display == null) display = new Display();
}

/**
* Private constructor
*/
private Display() {
display = this;
}

public void printwithDateandTime(String strMsg)
{
System.out.println(strMsg+" Date:"+new Timestamp(System.currentTimeMillis()));
}
}

APPROACH 2:
Create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.


import java.sql.Timestamp;

/**
*
* @author R.Amirtharj
*/
public final class FDisplay {
public static void printwithDateandTime(String strMsg)
{
System.out.println(strMsg+" Date:"+new Timestamp(System.currentTimeMillis()));
}
}


Main Class:


/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String arg[])
{
// Approach 1
Display.initialize();
Display.getDisplay().printwithDateandTime(" Singleton test Approach 1 ");

// Approach 1
FDisplay.printwithDateandTime(" Singleton test Approach 2");
}

}

Note : The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.

Wednesday, March 23, 2011

MultiSocketServer Example with Thread

ServerCode:

import java.net.ServerSocket;
import java.util.HashMap;

/**
*
* @author R.Amirtharaj
*/
public class Server implements Runnable {

// Storing Clients in HashMap
public static HashMap hmClients = new HashMap();
ServerSocket server = null;
boolean sFlag = false;

public void initializeServer() throws Exception {
server = new ServerSocket(5010);
}

public void run() {
try {
initializeServer();
System.out.println("SERVER STARTTED");
sFlag = true;
while (sFlag) {
new ClientWorker(server.accept());
System.out.println("client accepted");
}
} catch (Exception e) {
e.printStackTrace();
closeConnection();
}
}

public void closeConnection() {
try {
hmClients.clear();
if (server != null) {
server.close();
}
server = null;
} catch (Exception e) {
e.printStackTrace();
}

}

public static void clearClients(String cName) {
try {
ClientWorker tcw = (ClientWorker) hmClients.get(cName);
if (tcw != null) {
tcw.closeConnection(2);
tcw = null;
}

} catch (Exception e) {
e.printStackTrace();
}
}
}


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

public class ClientWorker extends Thread {

private Socket client;
private DataInputStream din = null;
private DataOutputStream dout = null;
boolean rFlag = false;

ClientWorker(Socket client) {
try {
this.client = client;
din = new DataInputStream(client.getInputStream());
dout = new DataOutputStream(client.getOutputStream());
String strC = din.readUTF();
Server.clearClients(strC);
Server.hmClients.put(strC, this);
rFlag = true;
start();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public void run() {

while (rFlag) {
try {
String line = din.readUTF();
System.out.println("MSG = " + line);
} catch (Exception e) {
e.printStackTrace();
closeConnection(1);
}
}
}

public void closeConnection(int i) {
System.out.println("closing " + i);
try {
rFlag = false;
if (client != null) {
client.close();
}
if (din != null) {
din.close();
}
if (dout != null) {
dout.close();
}
client = null;
din = null;
dout = null;
Thread.currentThread().interrupt();

} catch (Exception e) {
}
}

public void sendMessage(String strMsg) {
try {
dout.writeUTF(strMsg);
} catch (Exception e) {
e.printStackTrace();
}
}
}


For Client 1:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

/**
*
* @author R.Amirtharaj
*/
public class Client1 implements Runnable {
public Socket soc = null;
DataOutputStream dout = null;
DataInputStream din = null;
boolean rFlag = false;

public void initializeSocket() throws Exception
{
soc = new Socket("192.168.0.40", 5010);
dout = new DataOutputStream(soc.getOutputStream());
din = new DataInputStream(soc.getInputStream());
dout.writeUTF("CLIENT_1");
}

public void run() {
try {
initializeSocket();
System.out.println("CLIENT_1 started");
rFlag = true;
while (rFlag) {
String msg = din.readUTF();
System.out.println("CLIENT_1 read : "+msg);
}
}
catch(Exception e)
{
e.printStackTrace();
closeConnection();
}
}

public void sendMessage(String strMsg)
{
try {
System.out.println("CLIENT_1 write : "+strMsg);
dout.writeUTF(strMsg);
} catch (Exception e) {
e.printStackTrace();
closeConnection();
}
}

public void closeConnection()
{
System.out.println("CLIENT_1 closing");
try
{
rFlag = false;
if(din != null) din.close();
if(dout != null) dout.close();
if(soc != null) soc.close();
din = null;
dout = null;
soc = null;
}
catch(Exception e)
{
//e.printStackTrace();
}
}

}

For Client 2:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

/**
*
* @author R.Amirtharaj
*/
public class Client2 implements Runnable {
public Socket soc = null;
DataOutputStream dout = null;
DataInputStream din = null;
boolean rFlag = false;

public void initializeSocket() throws Exception
{
soc = new Socket("192.168.0.40", 5010);
dout = new DataOutputStream(soc.getOutputStream());
din = new DataInputStream(soc.getInputStream());
dout.writeUTF("CLIENT_2");
}

public void run() {
try {
initializeSocket();
System.out.println("CLIENT_2 started");
rFlag = true;
while (rFlag) {
String msg = din.readUTF();
System.out.println("CLIENT_2 read : "+msg);
}
}
catch(Exception e)
{
e.printStackTrace();
closeConnection();
}
}

public void sendMessage(String strMsg)
{
try {
System.out.println("CLIENT_2 write : "+strMsg);
dout.writeUTF(strMsg);
} catch (Exception e) {
e.printStackTrace();
closeConnection();
}
}

public void closeConnection()
{
System.out.println("CLIENT_2 closing");
try
{
rFlag = false;
if(din != null) din.close();
if(dout != null) dout.close();
if(soc != null) soc.close();
din = null;
dout = null;
soc = null;
}
catch(Exception e)
{
//e.printStackTrace();
}
}

}

Tuesday, March 22, 2011

JTextField Validation

case 1: Int field (TextField can allow only numbers and length of numbers to be 5)

JTextField tfInt = new JTextField();

// Validation part
tfInt.setDocument( new PlainDocument() {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
if(str == null) return;
//accept only number
ch = str.charAt(0);
if (!((ch >47)&&(ch<58))) {
return;
}

// For length validation
if(offs > 4) return;
// While copy paste then below length validation required
if(str.length()>5) return;
super.insertString(offs, str, a);
}
});


// For Number validation
public class OnlyNumberValidator extends javax.swing.text.PlainDocument {
@Override
public void insertString(int offs, String str,
javax.swing.text.AttributeSet a)
throws javax.swing.text.BadLocationException {
StringBuffer buf = new StringBuffer(str);
int size = buf.length();
char c;
for (int i = 0; i < size; i++) {
c = buf.charAt(i);
if (!Character.isDigit(c)) {
buf.deleteCharAt(i);
}
}

super.insertString(offs, buf.toString(), a);
}
}

Thursday, February 17, 2011

ORDER BY AND ROWNUM ISSUE IN ORACLE

Example :

WRONG ONE :
1. select * from table where rownum <= 2 order by 1 desc
2.select xam from ho_aa where ROWNUM = 1 ORDER BY LOG_TIME DESC
CORRECT ONE :
1. select * from (select * from table order by 1 desc) where rownum <= 2
2.select xam from (select xam from ho_aa ORDER BY LOG_TIME DESC) where ROWNUM = 1

REASON : Rownum is assigned after the row is selected BUT BEFORE ORDER BY

Monday, February 14, 2011

Dress code for feb 14.

Blue - free
Green -waiting
Orange -going to propose
Pink - accepted proposal
Black - rejected proposal
White - all ready booked
Yellow - broke up
Gray - not interested
Red- leave me alone.

Thursday, January 27, 2011

Timestampdemo

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
*
* @author R.Amirtharaj
*/
public class TimestampDemo {
public static void main(String arg[])
{
try {
long ct = System.currentTimeMillis();
Timestamp ts = new Timestamp(ct);
System.out.println("starttime =" + getStartTimeoftheDay(ts));
// New timestamp
Timestamp nts = getStartTimeoftheDay(ts);
// New Timestamp + 10 mins
Timestamp n10ts = getNextTimestamp(nts, 10);
System.out.println("n10ts =" + n10ts);
Timestamp n10lessts = getPrevTimestamp(nts, 10);
System.out.println("n10lessts =" + n10lessts);
} catch (Exception ex) {
ex.printStackTrace();
}

}


public static Timestamp getStartTimeoftheDay(Timestamp ts)
{
String fts = null;
Timestamp fts1 = null;
try {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
fts = formatter.format(ts);
fts1 = new Timestamp(formatter.parse(fts).getTime());
//System.out.println("fts = "+fts);
} catch (Exception ex) {
}
return fts1;
}


public static Timestamp getPrevTimestamp(Timestamp cts, int prevTime)
{
long ols = cts.getTime()-(prevTime*60*1000);
Timestamp ots = new Timestamp(ols);
return ots;
}

public static Timestamp getNextTimestamp(Timestamp cts, int prevTime)
{
long ols = cts.getTime()+(prevTime*60*1000);
Timestamp ots = new Timestamp(ols);
return ots;
}

// For Geeting Oracle Dateformat
public static String getOracleDateFormat(Timestamp ts)
{
String fts = null;
try {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
fts = formatter.format(ts);
//fts = new Timestamp(formattedcurTime);
//System.out.println("fts = "+fts);
} catch (Exception ex) {
ex.printStackTrace();
}
return fts;
}

public static Timestamp getRounded15Mins(Timestamp ts)
{
long ct = ts.getTime();
long diff = ct % (1000*60*15);
long nct = ct- diff;
Timestamp fts = new Timestamp(nct);
return fts;
}

public static Date getDateString(String str) {
Date fts = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
fts = formatter.parse(str);
} catch (Exception ex) {
ex.printStackTrace();
}
return fts;
}

public static Date addHoures(String str, int nofHrs)
    {
        Date fts = null;
        try {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            fts = formatter.parse(str);
            long ols = fts.getTime()+(nofHrs*60*60*1000);
            fts = new Date(ols);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return fts;
    }


}