Thursday, December 22, 2011

Inner class and Anonymous classes in Java

Nested Classes in Java

A nested class is a class defined inside the definition (body) of another enclosing class. 
A nested class can be of two types - static or non-static. A nested class is treated as a 
member of the enclosing class. A static nested class is not very tightly integrated with 
the enclosing class and it lives its own independent life as well i.e., a static nested 
class can be instantiated like any other class from just about anywhere. 
They are defined inside the definition of an enclosing class just to get a logical grouping 
of the classes, which in turn increases readability and provides better packaging convenience.

A static nested class can't directly access the members of the enclosing class. Like any other 
top-level class it needs to access the members of the enclosing class via object references only.

Example: a static nested class

class EnclosingClass {
 ...
 ...
 static class StaticNestedClass{
  //...definition of the static nested class
  ...
  ...
 }
 ...
 ...
}

A static nested class is accessed using the enclosing class name as follows:
EnclosingClass.StaticNestedClass staticNestedObjectRef = new EnclosingClass.StaticNestedClass();

Inner Classes in Java
A non-static nested class is called an inner class and it's tightly integrated with the enclosing 
class unlike a static nested class. An inner class instance can't exist independent to the enclosing 
class instance. An inner class instance always exist within the instance of the enclosing class. 
Since, it's always associated with the enclosing class instance and it has direct access to all the 
members of the enclosing class - even the private members.

Example: an inner class
class EnclosingClass {
 ...
 ...
 class InnerClass{
 //...definition of the inner class
 ...
 ...
 }
 ...
 ...
}

Since, an instance of an inner class always exists within an instance of the enclosing class, hence 
we must instantiate the enclosing class first and then on that instance we can instantiate the inner class:-

EnclosingClass enclosingObjectRef = new EnclosingClass();
EnclosingClass.InnerClass innerObjectRef = enclosingObjectRef.new InnerClass();

Can an Inner Class declare static members?
No. Because any instance of an inner class is always associated with an instance of the enclosing class.

Can we have private or protected access for classes in Java?
Yeah... but only for nested classes and not for top-level classes. Nested classes 
are treated as members of the enclosing classes and hence we can specify any of the 
four access specifiers - private, package, protected, or public. We don't have this luxury 
with top-level classes - they can only be declared public or package.

Local Inner Classes in Java
If an inner class has been defined within a code block (typically within the body of a method), 
then such an inner class is called a local inner class. A local inner class is not a member 
of the enclosing class and hence it can not have any access specifier. A local inner class 
will have access to all the members of the enclosing class and it'll have access to the local 
final variables in the scope it's defined.

Example: a typical local inner class
public class EnclosingClass{
...
 public methodName(){
  //...definition of the local inner class
   class LocalInnerClass {
    ...
   }
 ...
 }
}

Anonymous Inner Classes in Java
If an inner class has been declared without a name and within a code block (typically within the 
body of a method) then such an inner class is called an anonymous inner class. 
Since such an inner class doesn't have a name associated, so it'll be accessible only at the point 
where it is defined.

Example: a very common usage of an anonymous inner class
import java.awt.event.*;
public class GUI extends JFrame{
...
    public void buildComponents(){
        ...
        button1 = newJButton();
        ...
        button1.addActionListener(new ActionListener(){
          public void actionPerformed(java.awt.event.ActionEvent ae){
           ...
           ...
          }
        });
        ...
        ...
   }
}

Since, an anonymous inner class doesn't have a name, so it can't have a named constructor. 
But, it can have an instance initializer. Access rules for anonymous inner classes are same as that of 
local inner classes. Similar to a local inner class, an anonymous inner class can also not have 
any access specifier attached to it.

Are anonymous inner classes same as local inner classes?
Yeah..., an anonymous inner class is a local inner class in all means except that it doesn't 
have a name and hence it can't be used at any other point except at the point where it has 
been defined. The other difference is that it can't have a named constructor again for the 
same reason that it doesn't have a name.

Tuesday, December 13, 2011

Deadlock in Java

How to avoid Deadlock in Java is one of the question which is flavor of the season for multithreading, 
asked more at a senior level and with lots of follow up questions, though question looks very basic 
but most of the developer get stuck once you start going deep.

Questions starts with "What is deadlock ?"
Answer is simple: When two or more threads waiting for each other to release lock and get stuck for 
infinite time, situation is called deadlock. It will only happen in case of multitasking.

How do you detect deadlock in Java ?
Though this could have many answers, my version is first I would look the code if I see 
nested synchronized block or calling one synchronized method from other or trying to get 
lock on different object then there is good chance of deadlock if developer is not very careful.

other way is to find it when you actually get locked while running the application, try to 
take thread dump, in Linux you can do this by command "kill -3", this will print status of 
all the thread in application log file and you can see which thread is locked on which object.

Another way is to use "jconsole", "jconsole" will show you exactly what are the threads get 
locked and on which object.

Once you answer this, they may ask you to write code which will result in deadlock ?
Here is one of my version
===========================================================
//ThreadB.java
public class ThreadB extends Thread {
    public void run(){
        method1();
    }
    public void method1(){
        synchronized(Integer.class){
            System.out.println("ThreadB: Aquired lock on Integer.class object");
            //Nested synchronized block
            synchronized (String.class) {
                System.out.println("ThreadB: Aquired lock on String.class object");
            }
        }
    }
}
//ThreadC.java
public class ThreadC extends Thread {
    public void run(){
        method2();
    }
    public void method2(){
        synchronized(String.class){
            System.out.println("ThreadC: Aquired lock on String.class object");
            //Nested synchronized block
            synchronized (Integer.class) {
                System.out.println("ThreadC: Aquired lock on Integer.class object");
            }
        }
    }
}
//MainExample.java
public class MainExample {
    public static void main(String[] args){
        new ThreadB().start();
        new ThreadC().start();
    }
}
//Output with System/Java console Hanged:
ThreadB: Aquired lock on Integer.class object
ThreadC: Aquired lock on String.class object
===========================================================
If method1() and method2() both will be called by two or more threads, there is a good chance of 
deadlock because if Thread1 aquires lock on Sting object while executing method1() and Thread2 
acquires lock on Integer object while executing method2() both will be waiting for each other to 
release lock on Integer and String respectively to proceed further which will never happen.

Now interviewer comes to final part, one of the most important in my view, How to fix deadlock? 
or How to avoid deadlock in Java ?

If you have looked above code carefully you may have figured out that real reason for deadlock is 
not multiple threads but the way they access lock, if you provide an ordered access then problem 
will be resolved, here is the fixed version.

===========================================================
public void method1(){
    synchronized(Integer.class){
        System.out.println("Aquired lock on Integer.class object");
        //Nested synchronized block
        synchronized (String.class) {
            System.out.println("Aquired lock on String.class object");
        }
    }
}

public void method2(){
    synchronized(Integer.class){
        System.out.println("Aquired lock on Integer.class object");
        //Nested synchronized block
        synchronized (String.class) {
            System.out.println("Aquired lock on String.class object");
        }
    }
}
===========================================================
Now deadlock is fixed!!!!! There would not be any deadlock because both method is accessing 
lock on Integer and String object in SAME ORDER. So if Thread A acquires lock on Integer object, 
Thread B will not proceed until Thread A releases Integer lock. Same way Thread A will not be 
blocked even if Thread B holds String lock because now Thread B will not expect Thread A to 
release Integer lock to proceed further.

Hope this would be useful. Contents are copied from Internet but Example is modified and tested. Link can be seen here: 
http://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.html

Thursday, December 8, 2011

Acre, Metre and Foot Conversion guide

Dear Reader,
Adding some contents here which is a land measurement on 
Acre, Foot and Metre. It definitely will help you.
========================================================
1 Acre = 43560 Sq.Foot

1 Metre = 3.280 Feet
1 Foot  = 0.3048 Metre (1.0/3.280).
1 Square Metre = 10.76 Sq.Feet (3.28 * 3.28 = 10.76)

1 Square Feet = 0.09290304 Square Metre (0.3048 mtr * 0.3048 mtr)  
1000 Square Feet = 92.903 Square Metre

1 Cubic Metre = 35.3 Cubic Feet (3.28 * 3.28 * 3.28)

1 Foot = 30.48 Centimeters
1 Square Feet = 929.03 Centimeters (30.48 * 30.48 = 929.03) 

1 Square Yard = 0.836 Square Metre
1 Square Metre = 1.196 Square Yards

1 Bigha = 0.4 Hectare.

1 Bigha = .625 Acre = 5/8 Acre (This is different in different parts of World, but mostly used).
1.6 Bigha = 1 Acre

1 Square Mile = 2.59 Square KM = 259 Hectares
1 Mile = 1.6 KM.
=========================================================

Thursday, December 1, 2011

String functions in Oracle

Dear reader, 
Writing few String functions available in Oracle:

--------------LENGTH------------------
SELECT EMPNAME, LENGTH(EMPNAME), LENGTH('MANAGER') FROM EMPLOYEE;
//Output
EMPNAME     LENGTH(EMPNAME)  LENGTH('MANAGER')
-------     --------------   -----------------
Saikumar        8            7
Deepak          6            7

--------------TRIM------------------
SELECT Length('deepak '), TRIM('deepak '),Length(TRIM('deepak ')) FROM tab;
7  deepak  6

SELECT TRIM(LEADING '#' FROM 'rajesh##') FROM dual;    //rajesh##
SELECT TRIM(LEADING '#' FROM '##rajesh##') FROM dual;  //rajesh##
SELECT TRIM('#' FROM '##rajesh##') FROM dual;          //rajesh
SELECT TRIM('#' FROM '##raj##esh##') FROM dual;        //raj##esh

--------------SUBSTR----------------
Source_Str, Start_Pos, End_Pos

Value of Start_Position     
Positive ==    Counts forward from the first character in source_string
Zero (0) ==    Counts forward from the first character in source_string (that is, 
            treats a start_position of 0 as equivalent to 1)
Negative ==    Counts backward from an origin that immediately follows the last character in source_string A 
            value of -1 returns the last character in source_string.

SELECT SUBSTR('ABCDEFG',0,6)  FROM dual; //ABCDEF
SELECT SUBSTR('ABCDEFG',0,7)  FROM dual; //ABCDEFG
SELECT SUBSTR('ABCDEFG',2,3)  FROM dual; //BCD
SELECT SUBSTR('ABCDEFG',6)  FROM dual;   //FG
SELECT SUBSTR('ABCDEFG',7)  FROM dual;   //G
SELECT SUBSTR('ABCDEFG',-2,7)  FROM dual; //FG
SELECT SUBSTR('ABCDEFG',-3,7)  FROM dual; //EFG

--------------INSTR------------------
INSTR is used to find the position of any particular character in a word which 
returns numeric value. It IS CASE sensitive.

SELECT instr('KUMAR','e') FROM dual;  //0, e IS NOT present
SELECT instr('KUMAR','m') FROM dual;  //0, NOT matched, CASE sensitive
SELECT instr('KUMAR','M') FROM dual;  //3, INDEX starts FROM 1 here.

--------------REPLACE----------------
Source_Str, OLD_VAL, NEW_VAL
SELECT REPLACE('Deepak kumar', 'De', 'Ra')  FROM dual; //Raepak kumar

--------------LPAD-------------------
Source_Str, Total_No_Char, Filling_Char
SELECT LPAD('Here we are', 11, '-_') FROM dual;  //Here we are
SELECT LPAD('Here we are', 16, '-_') FROM dual;  //-_-_-Here we are  
//SIMILAR is RPAD

Generating Secure Numbers or Random Numbers like PIN/OTP

Dear Reader,

I am writing a useful post here: How to generate Secure Number sequences or Random Number sequences like PIN/One time
passwords or any number sequence for Temporary passwords which are numeric. I have explained the complete tutorial by
giving first a practical example that we use in our coding practices. The complete theory is given at the below section
after coding example.

At first, I have written code to generate simple Random Number based on given length, then the secure one:


//Basic Random Generator
package com.dmodi.utils;
import org.apache.commons.lang.RandomStringUtils;
//Add commons-lang-2.4.jar
public class RandomNumberGenerator {
    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            System.out.println(generateRandomNumber(6));
            System.out.println(generateRandomNumber(12));
        }

    }
    public static String generateRandomNumber(int length){
        String randomNumber="";
        randomNumber = RandomStringUtils.randomNumeric(length);
        return randomNumber;
    }
}

===========================================

//Secure Random Generator
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
//Add commons-lang-2.4.jar
import org.apache.commons.lang.RandomStringUtils;

public class OTP_Generation {
    public static void main(String[] args) {
        int otpLength=4;
        for(int i=0; i<10;i++) {
            System.out.println("OTP using SecureRandomGenerator: "+(i+1)+"==>"+generateOTP(otpLength));
        }
        System.out.println("==========================");
        for(int i=0; i<10;i++) {
            System.out.println("OTP using RandomNumberGenerator: "+(i+1)+"==>"+generateRandomOTP(otpLength));
        }
    }

    public static String generateOTP(int otpLengthNumber){
        String otp = new String();
        int otpSample=0;
        for(int i=0;i<otpLengthNumber;i++){
            otp=otp+"9";
        }

        otpSample=Integer.parseInt(otp);

        SecureRandom prng;
        try {
            prng = SecureRandom.getInstance("SHA1PRNG"); //Number Generation Algorithm
            otp = new Integer(prng.nextInt(otpSample)).toString();
            otp = (otp.length() < otpLengthNumber) ? padleft(otp, otpLengthNumber, '0') : otp;
        } catch (NoSuchAlgorithmException e) {
        }

//        If generated OTP exists in DB -regenerate OTP again
        boolean otpExists=false;
        if (otpExists) {
            generateOTP(otpLengthNumber);
        } else {
            return otp;
        }
        return otp;
    }
    private static String padleft(String s, int len, char c) { //Fill with some char or put some logic to make more secure
        s = s.trim();
        StringBuffer d = new StringBuffer(len);
        int fill = len - s.length();
        while (fill-- > 0)
            d.append(c);
        d.append(s);
        return d.toString();
    }
    public static String generateRandomOTP(int otpLengthNumber){
        String otp = RandomStringUtils.randomNumeric(otpLengthNumber);
        return otp;
    }
}

While generating random numbers in Java for Security purposes, we use java.security.SecureRandom class or
org.apache.commons.lang.RandomStringUtils class. SecureRandom class is designed to provide cryptographically secure
random numbers, however sometime it's become quite predictable if not used properly. I explained below:

SecureRandom class uses Pseudo Random Number Generator (PRNG) implementation for generating numbers. The PRNGs are
part of Cryptographic Service Providers (CSP) (here SUN for JAVA) is default CSP. On Windows env, SUN CSP uses "SHA1PRNG"
algorithm. On Unix env it is using something else, not mentioning here. At present, we use this Window's environment only.

SecureRandom sr1 = new SecureRandom();
//The following will create SUN SHA1PRNG if the highest priority CSP is SUN
SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG");

//The following will always create SUN SHA1PRNG
SecureRandom sr3 = SecureRandom.getInstance("SHA1PRNG", "SUN");

The PRNG tries to ensure that the output does not reveal any information about the seed, and that somebody observing the
output cannot predict future outputs without knowing the seed.

What is SEED?
An early computer-based PRNG, suggested by John von Neumann in 1946, is known as the middle-square method. The algorithm
is as follows: take any number, square it, remove the middle digits of the resulting number as the "random number", then
use that number as the seed for the next iteration.

For example, squaring the number "1111" yields "1234321", which can be written as "01234321", an 8-digit number being the
square of a 4-digit number. This gives "2343" as the "random" number. Repeating this procedure gives "4896" as the next
result, and so on. "Von Neumann" used 10 digit numbers, but the process was the same.
A problem with this "middle square" method is that all sequences eventually repeat themselves, some very quickly, such
as "0000". Von Neumann was aware of this, but he found the approach sufficient for his purposes, and was worried that
mathematical "fixes" would simply hide errors rather than remove them.


Note that according to Sun’s documentation, the returned java.security.SecureRandom instance is not seeded by any of these
calls. If after one of these calls, java.security.SecureRandom.nextBytes(byte[]) is called, then the PRNG is seeded using a
secure mechanism provided by the underlying operating system (starting with JRE 1.4.1 in Windows and JRE 1.4.2 in Linux and Solaris).

If java.security.SecureRandom.setSeed(long) or java.security.SecureRandom.setSeed(byte[]) is called before a call to
java.security.SecureRandom.nextBytes(byte[]), then the internal seeding mechanism is bypassed, and only the provided seed is used
to generate random numbers.

By bypassing the internal secure seeding mechanism of the SHA1PRNG, you may compromise the security of your PRNG output. If you
seed it with anything that an attacker can potentially predict (e.g. the time when the PRNG instance was created), then using
java.security.SecureRandom may not provide the level of security that you need.

Finally, regardless of how well the PRNG is seeded, it should not be used indefinitely without reseeding. There are two approaches
that can be used for longer-term security of PRNG output:

Periodically throw away the existing java.security.SecureRandom instance and create a new one. This will generate a new instance
with a new seed.
Periodically add new random material to the PRNG seed by making a call to
::::>>> java.security.SecureRandom.setSeed( java.security.SecureRandom.generateSeed(int) ).

In summary, keep the following in mind when using java.security.SecureRandom: Always specify the exact PRNG and provider that you
wish to use. If you just use the default PRNG, you may end up with different PRNGs on different installations of your application that
may need to be called differently in order to work properly. Using the following code to get a PRNG instance is appropriate:

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");

When using the SHA1PRNG, always call java.security.SecureRandom.nextBytes(byte[]) immediately after creating a new instance of the PRNG.
This will force the PRNG to seed itself securely. If for testing purposes, you need predictable output, ignoring this rule and seeding
the PRNG with hard-coded/predictable values may be appropriate. Use at least JRE 1.4.1 on Windows and at least JRE 1.4.2 on Solaris and Linux.

Earlier versions do not seed the SHA1PRNG securely. Periodically reseed your PRNG as observing a large amount of PRNG output generated
using one seed may allow the attacker to determine the seed and thus predict all future outputs.

Some of the theoretical contents are taken from few websites but are tuned as per my way of writing, however the coding example is
completely mine. Please read and leave the comment if found useful.

Another Example with Seeding:

try {
    // Create a secure random number generator
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // Get 1024 random bits
    byte[] bytes = new byte[1024/8];
    sr.nextBytes(bytes);

    // Create two secure number generators with the same seed
    int seedByteCount = 10;
    byte[] seed = sr.generateSeed(seedByteCount);

    sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
} 
catch (NoSuchAlgorithmException e) {
}
==========================END==========================

Friday, November 11, 2011

Error: "java.lang.NoSuchMethodError"

Dear reader,
I am explaining a very good topic here on Java. You may be aware about this error 
"java.lang.NoSuchMethodError" which comes while developing java applications.

The reason to write this tiny topic in my blog is because we have faced a major issue in production 
because of this. We have deployed a Hotfix (a JAR) in production which has dependency on another jar. 
The Hotfix was taken from a QA/Testing env where the Method Signature was different than production 
(I have explained below) and since there were no compilation issues, we deployed the hotfix in 
production which caused problem after deployment at runtime.

We noticed this after 1 day and you know: Shit happens as again Re-deploying in production for 
same issue will cause a trust deficit between client and Developer organization and necessary 
Approvals for production RESTART makes things worse...

Here is the below simple explanation of code failure:
I am writing two SIMPLE java classes, one is having main method calling other's method.

----------------------------------
//Topup.java
public class Topup {
    public static void main(String[] args) {
        Nokia nk=new Nokia();   //See this class below
        System.out.println("Before");
        nk.reverse();
        System.out.println("After");
    }
}
-----------------------------------
//Nokia.java (NOTE: Note the return type of reverse() method in below class)
public class Nokia {
public void reverse(){  //void return type
        System.out.println("Nokia before, with Void return type.");
}
}
-----------------------------------
//Compile these two files, both are in the same directory
    javac Nokia.java
    
    javac Topup.java

//Now run the main file
    java Topup

//Output:
Before
Nokia before, with Void return type.
After
--------------------------------------------------

Now change the Nokia.java like this (NOTE: Note the return type of reverse() method in below class):
public class Nokia {
    public String reverse(){  //String return type
        String ret="Old reverse";
        System.out.println("Nokia before, with String return type");
        return ret;
    }
}
--------------------------------------------------
Now again compile only Nokia.java, so that Nokia.class gets replaced with new one.
Now run again Topup.java

[dmodi@nbodevapp1 Confusion]$ javac Nokia.java
[dmodi@nbodevapp1 Confusion]$ java Topup
Before
Exception in thread "Main Thread" java.lang.NoSuchMethodError: reverse
        at Topup.main(Topup.java:5)
[dmodi@nbodevapp1 Confusion]$

!!!!!!!!!!!!!!You see exception here, please note there is no compilation issues,if you open this code 
base in MyEclipse. As in java calling a method with any return type doesn't make any sense if you 
don't require the returned value.

!!!!!!!!!!!!!!It means next time onwards if you do any hotfix, deployment into production, 
make sure the Other supporting jars are not modified in TESTING env compare to Production, 
else you will face the same big issue, what we have faced.

----------------------------------------------------
HOW to Confirm that the Hotfix Jar (Particular class or classes) are compiled with Other Method signatures 
rather than expected:
For this, there is a command in JAVA: javap -verbose. Here is example:

In Previous case (Topup, compiled with void reverse() in Nokia.java)
============
[dmodi@nbodevapp1 Confusion]$ javap -verbose Topup
Compiled from "Topup.java"
public class Topup extends java.lang.Object
  SourceFile: "Topup.java"
  minor version: 0
  major version: 49
  Constant pool:
const #5 = String       #23;    //  Before
const #6 = Method       #24.#25;        //  java/io/PrintStream.println:(Ljava/lang/String;)V
const #7 = Method       #2.#26; //  Nokia.reverse:()V
const #8 = String       #27;    //  After
const #12 = Asciz       ()V;
const #26 = NameAndType #36:#12;//  reverse:()V
const #27 = Asciz       After;
   17:  invokevirtual   #7; //Method Nokia.reverse:()V
   23:  ldc     #8; //String After
   25:  invokevirtual   #6; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   28:  return

========================In Modified case (Topup, compiled with String reverse() in Nokia.java)
[dmodi@nbodevapp1 Confusion]$ javap -verbose Topup
Compiled from "Topup.java"
public class Topup extends java.lang.Object
  SourceFile: "Topup.java"
  minor version: 0
  major version: 49
const #5 = String       #23;    //  Before
const #6 = Method       #24.#25;        //  java/io/PrintStream.println:(Ljava/lang/String;)V
const #7 = Method       #2.#26; //  Nokia.reverse:()Ljava/lang/String;
const #8 = String       #27;    //  After
const #26 = NameAndType #36:#37;//  reverse:()Ljava/lang/String;
const #27 = Asciz       After;
const #36 = Asciz       reverse;
const #37 = Asciz       ()Ljava/lang/String;;
   11:  ldc     #5; //String Before
   17:  invokevirtual   #7; //Method Nokia.reverse:()Ljava/lang/String;
   24:  ldc     #8; //String After
   29:  return

============================================================
Please see the difference, you will notice JAVA says that Topup.java is compiled with what type of
method signatures (reverse()) in Nokia.java


========================================End=======================================

Monday, August 29, 2011

Loggers in Java, Redirecting Log contents in a Log file in Java

Loggers in Java, Redirecting Log contents in a Log file in Java

Dear reader,
Here is the complete coding where we can configure a logger and redirect the logger contents
into a separate file for proper tracing.

//LoggerTest.java
package com.ewp.services;
import java.util.logging.*;
import java.io.*;

public class LoggerTest {

public static Logger logger;

static {
    try {
      boolean append = true;
      FileHandler fh = new FileHandler("D://Temp//log.properties", append);
      fh.setFormatter(new Formatter() {
         public String format(LogRecord rec) {
            StringBuffer buf = new StringBuffer(1000);
            buf.append(new java.util.Date());
            buf.append("===>");
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
            }
          });
      logger = Logger.getLogger("TestLog");
      logger.addHandler(fh);
    }
    catch (IOException e) {
      e.printStackTrace();
    }
}

public static void main(String args[]) {
    logger.severe("Severe category messages");
    logger.warning("Warning categary messages");
    logger.info("Info level messages");
    }
}

//Output in file "D:\Temp\log.properties"
/*
Mon Aug 29 15:39:48 IST 2011===>Severe category messages
Mon Aug 29 15:39:49 IST 2011===>Warning categary messages
Mon Aug 29 15:39:49 IST 2011===>Info level messages
*/

Monday, August 22, 2011

Stored Procedure in Hibernate

//Calling Stored procedure from Hibernate

XXXX.hbm.xml
<sql-query name="del_logged_users" callable="true">
        {call del_logged_users()}
</sql-query>

//Java code to call the stored procedure
public void deleteAllUsersDAO() throws Exception {
        String sql = "{call del_logged_users()}";
        Object[] inputParams = {};
        try    {    
            QueryInput queryInput = PersistenceHelper.createQuery("del_logged_users");
            PersistenceHelper.executeNamedQuery(queryInput);
            
            DatabaseUtil dbUtil = new DatabaseUtil();   //See this class below
            dbUtil.setup(getDataSourceName());
            dbUtil.runCall(sql, inputParams);
        } catch (Exception e) {
            StringBuffer message = new StringBuffer("Error while updating data. Original error message: ").
                append(e.getMessage());
            LogHelper.error(CLASS_NAME, METHOD_NAME, message.toString());
        
            throw new InternalException(
                    BusinessServiceMessageConstants.INT_ERRCODE_JDBC_QUERY_ERROR,
                    message.toString(), e);
        }
}

//Supporting class DatabaseUtil.java
private static HashMap datasourceCache = null;

public void setup(String datasource Name) throws NamingException {
        try {
            synchronized (this) {
                if( datasourceCache == null ) {
                    datasourceCache = new HashMap();
                }
                datasource = (DataSource)datasourceCache.get(datasourceName);
                if( datasource == null ){
                    InitialContext context = new InitialContext();
                    datasource = (DataSource)context.lookup(datasourceName);
                    datasourceCache.put(datasourceName, datasource);
                }
            }   // end synchronized block
        }
        catch(NamingException e) {
            e.printStackTrace();
            //Rethrow the exception
            throw e;
        }
}

public void runCall(String sql, Object[] params) throws SQLException, PersistenceException, 
                                                               RequiredParameterException {
    CallableStatement statement = null;
    Connection connection = getConnection();    
    try {
        statement = connection.prepareCall(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++)    {
                Object par = params[i];
                if (par == null)
                    statement.setNull(i + 1, Types.VARCHAR);
                if (par instanceof String)
                    statement.setString(i + 1, (String) par);
                else if (par instanceof Long)
                    statement.setLong(i + 1, ((Long) par).longValue());
                else if (par instanceof Timestamp)
                    statement.setTimestamp(i + 1, (Timestamp) par);
                else if (par instanceof java.util.Date)
                    statement.setDate(i + 1, new java.sql.Date(((java.util.Date) par)
                            .getTime()));
                else if (par instanceof Integer)
                    statement.setInt(i + 1, ((Integer) par).intValue());
                else if (par instanceof java.math.BigDecimal)
                    statement.setLong(i + 1, ((java.math.BigDecimal) par).longValue());
                // st.setBigDecimal(i+1, (java.math.BigDecimal)par);
            }
        }
        statement.execute();
      //connection.commit(); 
    }
    catch (SQLException e) {
        throw e;
    }
    finally {
        try {            
            if ( statement != null ) {
                statement.close();
            }
            if ( connection != null ) {
                connection.close();
            }
        }
        catch (SQLException e) {        
        } 
    }
}

-----------------------------END----------------------------------------

Thursday, June 30, 2011

Security concepts while developing web applications in Java

Few Security concepts while developing web applications in Java

1) Difference between Hashing and Encryption:
 Hashing takes any amount of data (binary or text) and creates a constant-length hash representing 
 a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce 
 different size hashes. You obviously cannot re-create the original data from the hash, but you can 
 hash the Original data again to see if the same hash value is generated. 
 Ex: Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, 
 the password you type is hashed, and the hash value is compared against the hash of the real password. 
 If they match, then you must've typed the correct password. 

 Encryption: Encryption means you are encrypting the Original Data into some un-readable format
 using some Key or Algorithms and store it or send through Network. Again you can decrypt the same
 un-readable data using same Key or Algorithm and generates Original Data.

2) Points to be taken while writing Dynamic Queries in application to prevent Hacking:
 a) SQL injection example one:

 SELECT * FROM admin_auth_user WHERE Firstname='Obopay' AND FamilyName='Admin';
 //8 records returned

 SELECT * FROM admin_auth_user WHERE Firstname='Obopay' AND FamilyName='Admin' OR '1'=1;
 //ALL 26 records returned, adding the OR clause makes WHERE clause condition always TRUE, so this query becomes:
 SELECT * FROM admin_auth_user;


 b) SQL injection example two:
 //Your application query:
 SELECT * FROM items WHERE owner = '" +hackerName+ "' AND itemname = '" +name+"'";

 //Query is modified by Hackers using some script in URL and added something like below,
 //This will delete all records from table on those DB which supports Batch Execution, eg: SQL server-2000, 
 //Oracle doesn't support this.
 SELECT * FROM items WHERE owner = '" +hackerName+ "' AND itemname = '" +name+ "';DELETE FROM items;SELECT * FROM 
 items WHERE 'a'='a'";

 #######################################
 A safe version of the above SQL statement could be coded in Java as:

 String firstname = req.getParameter("firstname");
 String lastname = req.getParameter("lastname");
 //FIXME: Do your own validation to detect attacks
 String query = "SELECT id, firstname, lastname FROM authors WHERE forename = ? and surname = ?";
 PreparedStatement pstmt = connection.prepareStatement( query );
 pstmt.setString( 1, firstname );
 pstmt.setString( 2, lastname );
 try {
    ResultSet results = pstmt.execute( );
 }
 catch(Exception e){}
 ########################################

 c) Visible Content
 Having a simple page, which displays article with given ID as the parameter, the attacker may 
 perform a couple of simple tests if a page is vulnerable to SQL Injection attack.
 
 Example URL:
    http://newspaper.com/items.php?id=2
 Sends the following query to the database:
    SELECT title, description, body FROM items WHERE ID = 2;   //Assume: Returns 1 record

 The attacker may try to inject any (even invalid) query, that may cause the query to return no results:
    http://newspaper.com/items.php?id=2 and 1=2
 Now the SQL query should looks like this:
    SELECT title, description, body FROM items WHERE ID = 2 and 1=2;   //No records will return as 1=2 is False.

 Which means that the query is not going to return anything. Use Again PreparedStatements to fetch only Id.

3) Writing and Inserting Java Script to steal SessionId for a user and use it:

 It is easy to steal SessionId cookies with javascript functions planted in trusted sites by 
 other users. Here we are discussing the possible counter-measures for this kind of attack.

 How Hackers do this:
 <script>document.cookie</script>

 Help is taken from this site (Open Web Application Security Project):
 https://www.owasp.org/index.php/HttpOnly
---------------------END---------------------

Tuesday, June 28, 2011

Regex: Pattern and Matcher in Java

Java provides the java.util.regex package for pattern matching with regular expressions.
A regular expression defines a search pattern for strings that helps you match or find 
other strings or sets of strings, using a specialized syntax held in a pattern. They can be 
used to search, edit, or manipulate text and data.

The java.util.regex package primarily consists of the following three classes:
   Pattern Class: A Pattern object is a compiled representation of a regular expression. 
   The Pattern class provides no public constructors. To create a pattern, you must first 
   invoke one of its public static compile methods, which will then return a Pattern object. 
   These methods accept a regular expression as the first argument.

   Matcher Class: A Matcher object is the engine that interprets the pattern and performs 
   match operations against an input string. Like the Pattern class, Matcher defines no public 
   constructors. You obtain a Matcher object by invoking the matcher method on a Pattern object.

   PatternSyntaxException: A PatternSyntaxException object is an unchecked exception that indicates 
   a syntax error in a regular expression pattern.

Starting with Example:
==================
package regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatcher {
    private static String weeks[] = {"monday","tuesday","wednesday","thursday","friday","saturday","sunday"};

    static Pattern p;
    static Matcher m;

    public static void main(String[] args) {
        System.out.println(isNumeric("9916473353"));  //true
        System.out.println(isNumeric("ad9916473353"));  //false

        System.out.println(weekPassword("monday123"));  //true
        System.out.println(weekPassword("ad9916473353"));  //false

        System.out.println(checkAlphabetPassword("monday123"));  //true
        System.out.println(checkAlphabetPassword("AbCd12"));  //true
        System.out.println(checkAlphabetPassword("12"));  //false
        
        System.out.println(check3DigitNumber("dd1d23"));  //false
        System.out.println(check3DigitNumber("45"));  //false
        System.out.println(check3DigitNumber("-124"));  //false
        System.out.println(check3DigitNumber("124"));  //true
    }
    public static boolean isNumeric(String mobNumber){
        p = Pattern.compile("[^\\d]");  //Matches only all digits [0-9]
        //p = Pattern.compile("^[0-9]");  //Matches single non-digit: [^0-9]
        //p = Pattern.compile("[0-9]");  //Matches a single digit [0-9]
        m = p.matcher(mobNumber);
        while (m.find()) {                
            return false;
        }
        return true;
    }

    public boolean isTrue(String s){ 
        return s.matches("true"); //Returns true if the string matches exactly "true"
    }

    public boolean isTrueVersion2(String s){
        return s.matches("[tT]rue"); //Returns true if the string matches exactly "true" or "True"
    }

    //Returns true if the string matches exactly "true" or "True" or "yes" or "Yes"
    public boolean isTrueOrYes(String s){
        return s.matches("[tT]rue|[yY]es");   
    }

    public boolean containsTrue(String s){
        return s.matches(".*true.*");  //Returns true if the string CONTAINS exactly "true"
    }

    public boolean isThreeLetters(String s){
        return s.matches("[a-zA-Z]{3}"); //Returns true if the string contains of three letters
        //return s.matches("[a-Z][a-Z][a-Z]");  //Same as this.
    }

    public boolean isNoNumberAtBeginning(String s){
        return s.matches("^[^\\d].*"); //Returns true if the string does not have a number at the beginning
    }

    public static boolean weekPassword(String password){
        for(int i=0;i<7;i++){  //7 days of week, takes input from week days name array
            p = Pattern.compile(weeks[i], 2); //2 is Pattern.CASE_INSENSITIVE means case-insensitive search
            m = p.matcher(password);          //1 means case sensitive
            while (m.find()) {                
                return true;    
            }
        }
        return false;
    }
    public static boolean checkAlphabetPassword(String password){
        p = Pattern.compile(".??[a-z]"); //Dangling meta char
        m = p.matcher(password);
        while(m.find()) {
            return true;    
        }
        return false;
    }
    public static boolean check3DigitNumber(String s){
        //Pattern pattern = Pattern.compile("\\d{3}");  //Contains minimum 3 consecutive numerics
        Pattern pattern = Pattern.compile("^[0-9]{3}");  //Contains exact 3 numerics
        Matcher matcher = pattern.matcher(s);
        if(matcher.find()){
            return true; 
        } 
        return false; 
    }
}
========================
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pattern1 {
    public static void main(String[] args) {
        String source="a1b2c3dBCD45Fee6743";
        String destination=null;  

        Pattern p = Pattern.compile("[^a-z]");  //Pick all except a-z
        //Pattern p = Pattern.compile("[^0-9]");  //Pick all except 0-9
        //Pattern p = Pattern.compile("[^A-Z]");  //Pick all except A-Z
        
        Matcher m = p.matcher(source);

        boolean result = m.find();        
        while(result) {
            destination=m.replaceAll("");       //Replace above match with empty characters.
            result = m.find();
        }
       System.out.println(destination); //Print after replacement. 
    }
}

//Uncomment line 11, output: BCDF
//Uncomment line 10, output: 123456743
//Uncomment line  9, output: abcdee

-----------------------------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pattern2 {
    public static void main(String[] args) {
        String source="9916473353";
        String sourceWithChar="99r16d4e73353";
        String destination=null;  

        Pattern p = Pattern.compile("[0-9]{7}");  
        //Input only Digits, picks first 7 digits for replacement. 
        //If any character is not number, will return null;
        
        Matcher m = p.matcher(source);  //Without Character
        Matcher mWithChar = p.matcher(sourceWithChar); //With Character

        boolean result = m.find();        
        while(result) {
            destination=m.replaceAll("");  //Replace above match with empty characters.
            result = m.find();
        }
        System.out.println(destination); //Print after replacement. 

        destination=null;
        result = mWithChar.find();   //no match here, as source contains Characters too.            
        while(result) {              //Not entering inside while loop.      
            destination=mWithChar.replaceAll("");  //Replace above match with empty characters.
            result = mWithChar.find();
        }
        System.out.println(destination); //Print after replacement. 
    }
}
//Output:
353
null
========================================================

More help: 
http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/
http://www.ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-1/
http://www.regular-expressions.info/email.html

Thursday, June 23, 2011

Normalization in Database

Normalization
It is a process of refining the data model by ER diagram.

It includes
  --> Refinement of ER model.
  --> Segregation of data over groups, entities/tables with min redundancy).
  --> Converts ER diagram to tables.

Advantages
  --> min data redundancy.
  --> retreieve information easily.

Need for normalization
*) improves data base design.
*) ensures min redundancy of data
*) reduces need to reorganize data when design is deleted/enhanced.

Unnormalized tables
--> contain redundant data
--> disorganized data
--> problems arise with insertion,updation and deletion.


First Normalization 
Steps
1) identify repeating groups of fields.
2) remove repeating groups of fields to a seperate table.
3) identify the keys for the table.
4) key of parent table is brought as a part of concatenated key of second table.

Second Normalization
Steps
1) check if all fields are dependent on whole key.
2) remove fields that are dependent on partial key.
3) group partially dependent fields as a seperate table.
4) name the table.
5) identify key / keys of the table.

Third Normalization
Steps
1) removes fields that depend on other non key attribute 
2) can be calculated or derived from logic.
3) group independent fields as seperate tables,identify the key.

Oracle programming code_Part2

//Oracle tutorial_part2
//Cursor programming
==========================================
//Explicit cursor
/* using cursor display the details of all those emp from emp whose sum of sal and comm is>3000; */
declare
 vempno emp.empno%type;
 vename emp.ename%type;
 vsal emp.sal%type;
 vdeptno emp.deptno%type;
 cursor c1 is 
   select empno,ename,sal,deptno from emp where sal+nvl(comm,0)>3000;
 begin
   open c1;
   loop
     fetch c1 into vempno,vename,vsal,vdeptno;
     if c1%FOUND then
       dbms_output.put_line(vempno||'    '||vename||'    '||vsal||'       '||vdeptno);
     else
       exit;
     end if;
   end loop;
  close c1;
end;
-----------------------------
declare
 name emp.ename%type;
 no  emp.empno%type;
 cursor empc is select ename,empno from emp;
begin
 open empc;
 dbms_output.put_line('rowcount '||empc%ROWCOUNT);
 loop
  fetch empc into name,no;
  dbms_output.put_line('name '||name||' no'||no);
  exit when empc%NOTFOUND;
 end loop;
 dbms_output.put_line('rowcount'||empc%ROWCOUNT);
 close empc;
end;
-----------------------------
//Implicit cursor (here cursor keyword is not used):
begin
 delete from dept where deptno=100;
 if sql%notfound then
  raise_application_error(-20303,'No such department in the dept table'); 
 end if;
end;
/
//Other commands used in implicit cursor==> sql%FOUND
==========================================

Table creation with constraints:
create table Doctors(
doctor_id number(6) primary key,
doctor_name varchar2(20) not null,
doct_address varchar2(35),
doct_ph_no number(10)
);

create table Test (
test_id number(4) primary key,
test_name varchar2(20),
doctor_id number(6),
constraint fk_doctor_id foreign key(doctor_id) references Doctors
);
==========================================

//Defining values
DEFINE P_SALARY=50000;
DEFINE P_BONUS=10;
DECLARE
RESULT NUMBER:=0;
BEGIN
RESULT:=(P_SALARY*P_BONUS/100)+P_SALARY;
DBMS_OUTPUT.PUT_LINE(RESULT);
END;
/
==========================================
//Stored Procedures:
CREATE OR REPLACE PROCEDURE Prof_Chng_Merchant_To_Silver(INPUT_MOBILENUMBER VARCHAR2)
AS
  Src_memberid   NUMBER(24);
  Src_account_id NUMBER(24);
  Src_programnameref VARCHAR(20);
  Check_programnameref VARCHAR(20);
BEGIN
  SELECT mac.memberid,acc.id INTO Src_memberid,Src_account_id FROM account acc, memberaccountrole mac
  WHERE acc.id = mac.accountid AND acc.devicenumber LIKE INPUT_MOBILENUMBER;

  SELECT Value INTO Check_programnameref FROM account_dtl WHERE code='OP_FR_PROG' AND account_id IN
  (SELECT id FROM account WHERE devicenumber=INPUT_MOBILENUMBER);

  IF Check_programnameref='MERCHANTSVA' then

    SELECT programnameref INTO Src_programnameref FROM account WHERE devicenumber LIKE INPUT_MOBILENUMBER;
    UPDATE ACCOUNT SET PROGRAMNAMEREF = Decode(Src_programnameref,'MBILL','MBILL','SILVER') 
 WHERE DEVICENUMBER LIKE INPUT_MOBILENUMBER;

    IF SQL%ROWCOUNT = 1 THEN     
      UPDATE account_dtl SET Value = 'SILVER' WHERE code LIKE'OP_FR_PROG' AND ACCOUNT_ID = Src_account_id;
      UPDATE bank_temp_upload_customer  SET PRODUCT = 'SILVER' WHERE ACCOUNT_ID = Src_account_id
        AND customer_id = (SELECT Max(customer_id) FROM bank_temp_upload_customer WHERE account_id = Src_account_id);
      Insert into ACCOUNT_LOCK_LOG (id, account_id, reason_code, lock_reason, createdt,
        createdby, modifydt, modifiedby, auth_user_id, locked_by_user_type, action_type)
      Values
        ((SELECT Max(id)+1 FROM ACCOUNT_LOCK_LOG), Src_account_id, 'NOTE', 
  'Coverted the Product type from MERCHANT to SILVER', sysdate, NULL, sysdate, 'PROCEDURE', NULL, NULL, 'NOTE');
    END IF;
  END IF;

  dbms_output.put_line ('No MerchantSVA customer found with this mobile number');

  EXCEPTION
  WHEN OTHERS THEN
    INSERT INTO AUDIT_LOG (
      AUDIT_LOG_ID, TRANSACTION_ID, TRANSACTION_DATE,
      OBJECT_NAME, EVENT_CATEGORY, EVENT_TYPE, OBJECT_PK_VALUE,
      COLUMN_NAME, OLD_VALUE, NEW_VALUE,ADMIN_USER, EVENT_DATA)
    VALUES ( seq_audit_log_id.nextval, null, SYSDATE
      ,'Prof_Chng_Merchant_To_Silver','PLEXCEPTION', 'PROFILE',NULL
      ,'OTHERS' ,NULL, NULL, 'PROCEDURE', INPUT_MOBILENUMBER);

END Prof_Chng_Merchant_To_Silver;
/

//Way to execute
EXEC Prof_Chng_Merchant_To_Silver('919902029064');
COMMIT;
==========================================
create or replace procedure area(length in number,breadth in number)
is
v_area number;
begin
v_area:=length*breadth;
dbms_output.put_line('The area is '||v_area);
end area;
/
-----------------------------
CREATE or replace procedure proc1(p_id in number)
is
emp_record emp%rowtype;
begin
select * into emp_record from emp where empno =p_id;
dbms_output.put_line(emp_record.ename||'   '||emp_record.job);
end proc1;
/
-----------------------------
//Way to execute
begin
  area(6,6);
  proc1(80);
end;
/
OR
Execute area(4,5);
-----------------------------
//Calling another stored procedure
create or replace procedure up_fees(id number)
is
begin
update stud set fees=fees+500
where sl=id;
end up_fees;
/
-----------------------------
create or replace procedure proc7(pid number)
is
begin
up_fees(pid);
exception
when no_data_found then
dbms_output.put_line('No Such data in student table');
end proc7;
/
==========================================

//Function
CREATE or replace function func3(psal number)
return number
is
begin 
insert into emp (empno,ename,job,sal,deptno) values(3455,'Deepak','SSE',4500,20);
return (psal+500);
end func3;
/
-----------------------------
create or replace function day(num IN number)
return varchar2 
is
begin
  case num
           when 1 then return  'SUNDAY'
           when 2 then return  'MONDAY'
           when 3 then return 'TUESDAY'
           when 4 then return 'WENESDAY'
           when 5 then return 'THURSDAY'
           when 6 then return 'FRIDAY'
           when 7 then return 'SATURDAY'
         else return 'INVALID NUMBER'
  END;
 END day;
/
-----------------------------
create or replace function wish(name varchar2)
return varchar2
is
begin
if name='deepak' or name='kumar' or name='modi' then
 return 'Welcome to the creation of function in oracle';
else
return 'Not a valid user of scott';
end if;
end wish;
/
==========================================
declare
 pName bank_temp_upload_customer.product%type;
 PPID  bank_temp_upload_customer.PROGRAM_PROFILE_ID%type;
 custId  bank_temp_upload_customer.CUSTOMER_ID%type;
 custIdMax NUMBER(24);
 mobNumber bank_temp_upload_customer.mobile_number%TYPE; 
 cursor tempCursor is 
    select product,program_profile_id,mobile_number,customer_id from bank_temp_upload_customer 
    WHERE mobile_number IN ('919686680837','919686680836') AND
    pi_master_id=(SELECT pi_master_id FROM PI_MASTER WHERE pi_code='YBL') 
    ORDER BY mobile_number desc;
begin
 open tempCursor; 
 loop
  fetch tempCursor into pName,PPID,mobNumber,custId;
  SELECT Max(customer_id) INTO custIdMax FROM bank_temp_upload_customer WHERE mobile_number=mobNumber;
  IF custId=custIdMax then
     dbms_output.put_line('ProductName ==>'||pName||', Profile_ID==>'||PPID||', Max_Customer_Id==>'||custId||',
  Mobile_Number==>'||mobNumber);     
  UPDATE bank_temp_upload_customer SET PROGRAM_PROFILE_ID=(SELECT ID FROM program_profile WHERE 
  partner_code='YBL' AND PROGRAM_NAME =pName) 
      WHERE MOBILE_NUMBER=mobNumber AND customer_id=custIdMax; 
  END IF;
  exit when tempCursor%NOTFOUND;
 end loop;
 dbms_output.put_line('Task completed');
 close tempCursor;
end;

==========================================

//Triggers in Oracle
Can be seen here too: http://deepakmodi2006.blogspot.com/2011/01/database-triggers-in-oracle.html
CREATE OR REPLACE TRIGGER SECURE_EMP
 BEFORE INSERT ON EMPLOYEES
 BEGIN
 IF
 (TO_CHAR(SYSDATE,'DY') IN  ('THU','FRI')) OR
 (TO_CHAR(SYSDATE,'HH24:MI') NOT BETWEEN '08:00' AND '17:00')
 THEN RAISE_APPLICATION_ERROR(-20500,'YOU MAY INSERT INTO EMPLOYEES TABLE ONLY DURING BUSINESS HOURS');
 END IF;
 END;
/
------------------------------
CREATE OR REPLACE TRIGGER SECURE_EMP1
 BEFORE INSERT OR UPDATE OR DELETE ON EMPLOYEES
 BEGIN
  IF
   (TO_CHAR(SYSDATE,'DY') IN  ('WED','SUN')) OR
   (TO_CHAR(SYSDATE,'HH24:MI') NOT BETWEEN '08:00' AND '18:00')
  THEN 
IF DELETING THEN 
RAISE_APPLICATION_ERROR(-20501,'YOU MAY DELETE INTO EMPLOYEES TABLE ONLY DURING BUSINESS HOURS');
ELSIF INSERTING THEN 
RAISE_APPLICATION_ERROR(-20502,'YOU MAY INSERT INTO EMPLOYEES TABLE ONLY DURING BUSINESS HOURS');
ELSIF UPDATING ('DATEOFJOINING') THEN
RAISE_APPLICATION_ERROR(-20503,'YOU MAY UPDATE DOJ INTO EMPLOYEES TABLE ONLY DURING BUSINESS HOURS');
ELSE
RAISE_APPLICATION_ERROR(-20504,'YOU MAY DO TRANSACTION INTO EMPLOYEES TABLE ONLY DURING BUSINESS HOURS');
 END IF;
END IF;
END;
/
------------------------------
create or replace trigger tri_emp
after insert or update or delete on employee
for each row
begin
  insert into audit_table values(user,sysdate,:old.empno,:old.ename,:new.ename,
  :old.job,:new.job,:old.sal,:new.sal);
end;
/
==========================================

//Package and Package body
//Package is like Interface in java, only declaration. Package body is having basically details of those.
//One full example to start with:
create or replace package summul as
  procedure pr1(a number,b number);
  function fr1(a number,b number)return number;
  c number;
end summul;

create or replace package body summul
 as
procedure pr1 (a number,b number) 
 is
 sumValue number(4);
 begin
  sumValue:=a+b;
  dbms_output.put_line(sumValue);
end pr1;

function fr1(a number,b number) return number is
mul number;
begin
 mul:=a*b;
 return (mul);
end fr1;
end summul;

//execute summul.pr1(10,20);
//select summul.fr1(10,20) from dual;
SQL> execute summul.pr1(10,20);
     PL/SQL procedure successfully completed.
SQL> set serveroutput on;
SQL> execute summul.pr1(10,20);
30
PL/SQL procedure successfully completed.
SQL> select summul.fr1(12,34) from dual;
SUMMUL.FR1(12,34)
-----------------
408
==========================================

create or replace package var_pack
is
function g_del return number;
procedure set_g_del (p_val in number);
end var_pack;
/
-------------------
create or replace package body var_pack is
gv_del number :=0;

function g_del return number is 
begin
 return gv_del;
end;

procedure set_g_del (p_val in number) is 
begin
if p_val=0 then
  gv_del := p_val;
else 
  gv_del :=gv_del +1;
end if;
end set_g_del;
end var_pack;
/
------------------------------
//Another package and package body
create or replace package dept_pack
 is 
 v_dept number;
 procedure dept_proc;
 end dept_pack;
/
-------------------
create or replace package body dept_pack
 is
 procedure dept_proc
  is
  v_name varchar2(20);
  v_loc varchar2(30);
 begin
  select dname,loc into v_name,v_loc from dept where deptno=v_dept;
  dbms_output.put_line(v_name||'  '||v_loc);
 end dept_proc;
 begin
  select deptno into v_dept from emp where ename='FORD';end dept_pack;
/
==================END=======================

Generating Reports in Oracle

sql * plus allows the user the flexibility for formatting the results in the form of reports.

It uses sql to retrieve information from the oracle data base and lets the user create polished,well formatted reports.
//Commands used in generation of reports
1. REM
SQLPlus ignores anything on a line that begins with the letters REM. It is used to add comments,
documnetation and explanations etc to a FILE.

2. SET HEAD SEP
SET HEAD SEP is used for head seperator .SQLPLUS will indicate to break a page title
or a column heading that no longer than one line.

3. TTILE AND BTITLE
TTITLE is used to set header for each page and BTITLE is used to set the footer for each page.

4. COLUMN
Column allows us to change the heading and format of any column in a select statement.

5. BREAKON <Column- name> SKIP page <n>
breakon to skip n lines every time the item is changed. breakon command and order by clause must be used together.

6. computesum
compute sum command used to calculate the sum for a particular column and always works with
breakon command.

7. set linesize
set Line size determines the max no of characters that appear in a single line.

8. set pagesize
set page size command sets the total no of lines PLSQL will place on each page including 
ttitle,btitle,column headingsand blank lines it prints.

9. set NewPage
set new page print blank lines before the top line of each page of the reports.

10. list<n>
list command list the buffer contents depending on n.

11. set pause on 
set pause on command is used to view the contents page by page.

12. set pause off
set pause off command is used to disable the pause  on command.

13. spool <file-name>  all the information displayed on the screen is displayed in the specified file
After setting all the above formatting commands if we execute the select query then those commands
will be applied to sql query and will generate a report.

14. spool off : will stop spooling.

15. spool out : close the listed file and prints the file to the system printer.

To reset all the above statements ,execute the following
16. ttitle off;
17. btitle off;


//Sample Example:
ttitle 'Deepak writes a good blog having Account report | Account report';
btitle 'Day begins with hello, good morning';
column Name heading 'Name';
column ProductType heading 'Product Type';
column Status heading 'Status';
break on Status;
spool Account_report.doc;
select Name, ProductType,Status from Account where ProductType='PLATINUM';
spool off;
spool out;
ttitle off;
btitle off;
column Name clear;
column ProductType clear;
column Status clear;
clear breaks;
------------------------------End-----------------------

Wednesday, June 22, 2011

Oracle programming code_Part1

Oracle programming codes_Part_1

//If-else block
declare
a number;
b number;
begin
a := &a;  --input from console
b := &b;  --input from console
if a<b  then
   dbms_output.put_line('a is smallest');
else
   dbms_output.put_line('b is smallest');
end if;
end;
-----------------------
declare
a number;
b number;
c number;
begin
 a := &a;
 b := &b;
 c := &c;
 if a>b and a>c then
   dbms_output.put_line('a is  >');
 elsif b>c then
   dbms_output.put_line('b is  >');
 elsif a=b and b=c then
   dbms_output.put_line('a=b=c');
 else
   dbms_output.put_line('c is  >');
 end if;
end;
========================

//Simple input output
declare
a number;
b number;
c number;
begin
  a := &a;
  b := &b;
  c := a+b;
  dbms_output.put_line('a+b = ' || c);
end;
=========================

//Loop programs
declare
 c number;
begin
 c := 0;
 loop
  c := c+1;
  dbms_output.put_line(c);
  if c = 10 then exit;
  end if;
 end loop;
end;
--------------------
declare
c number;
begin
 c := 0;
 until c>11 loop
  c:=c+1;
  dbms_output.put_line(c);
 end loop;
end;
--------------------
declare
c number;
begin
for c in 1..10  loop
 dbms_output.put_line(c);
end loop;
end;
---------------------
declare
 c number;
begin
 c := 0;
 loop
  c := c+1;
  dbms_output.put_line(c);
  exit when c = 10;
 end loop;
end;

==========================

//Rowtype
declare
x emp%rowtype;
begin
 select * into x from emp where empno=7839;
 if(x.sal >3000) then
  update temp2 set comm=300 where x.empno=7839;
 elsif (x.sal < 6000) then
  update temp2 set comm=600 where x.empno=7839;
 else
  update temp2 set comm=100 where x.empno=7839;
 end if;
 
 dbms_output.put_line('job done');
end;
--------------------------
//Type
declare
 x emp.sal%type;
 e emp.ename%type;
 eno  emp.empno%type;
begin
 eno := &eno;
 select sal into x from emp where empno=eno;
 select ename into e from emp     where empno=eno;
 if x>3000 then
  dbms_output.put_line(e||'s salary is greater than 3000'); 
 else
  dbms_output.put_line(e||'s salary is less than 3000'); 
end if;
end;
==========================
//Exception in oracle
//User defined exception
declare
 a number;
 b number;
 c number;
 my_zero_divide exception;
begin
 a := &a;
 b := &b;
 if b=0 then
   raise my_zero_divide; 
 else
   c := a/b;
   dbms_output.put_line('a/b = ' || c);
 end if;

Exception
when my_zero_divide then
  dbms_output.put_line('you tried to divide a number by zero');

dbms_output.put_line('There was an exception');
end;
--------------------------
//System defined exception
declare
 vename emp.ename%type;
 vjob emp.job%type;
begin
 select ename ,job into vename,vjob from emp where sal>2000;

 Exception
 when NO_DATA_FOUND then
    dbms_output.put_line('NO_DATA_FOUND SQLCODE '||SQLCODE||'SQLERRM '||SQLERRM);
 when TOO_MANY_ROWS then
    dbms_output.put_line('TOO_MANY_ROWS'||'sqlcode   '||sqlcode||'   SQLERRM '||SQLERRM);
 when others then 
    dbms_output.put_line('other Exception');
end;
==========End of chapter1==================

Tuesday, June 21, 2011

JUnit Tutorial with Examples

//JUnit test case
Functional testing, or integration testing, is concerned with the entire system, not just small 
pieces (or units) of code. It involves taking features that have been tested independently, combining 
them into components, and verifying if they work together as expected. For Java, this testing is 
typically performed using the JUnit framework.

This article introduces and demonstrates the following strategy for building an effective JUnit functional test suite:

    1. Identify use cases that cover all actions that your program should be able to perform.
    2. Identify the code's entry points - central pieces of code that exercise the functionality 
       that the code as a whole is designed to undertake.
    3. Pair entry points with the use cases that they implement.
    4. Create test cases by applying the initialize/work/check procedure.
    5. Develop runtime event diagrams and use them to facilitate testing. 
    6. Tests can rely on each other, but no single test should verify two things.

Translating Test Cases:
Each test case is divided into two parts: input and expected output. The input part lists all the test 
case statements that create variables or assign values to variables. The expected output part indicates 
the expected results; it shows either assertions or the message 'no exception' (when no assertions exist).

The basic input/output format is the simplest, easiest to understand model to follow for test cases. 
It follows the pattern of normal functions (pass arguments, get return value), and most user actions 
(press this button to start this test action). The pattern, then, is to:

   1. Initialize: Create the environment that the test expects to run in. The initialization code can 
      either be in the beginning of the test or in the setUp() method.
   2. Work: Call the code that is being tested, capturing any interesting output and recording any 
      interesting statistics.
   3. Check: Use assert statements to ensure that the code worked as expected. 
   
Example For Testing TOPUP transactions:
======================
//TestData.java
package com.ewp.test.data;
public class TestData {
    private String mobileNumber;
    private String targetMobileNumber;
    
    public String getMobileNumber() {
        return mobileNumber;
    }
    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }
    public String getTargetMobileNumber() {
        return targetMobileNumber;
    }
    public void setTargetMobileNumber(String targetMobileNumber) {
        this.targetMobileNumber = targetMobileNumber;
    }
}

======================
//testContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
        <property name="url"><value>jdbc:oracle:thin:@10.200.101.45:1521:obdbdev</value></property>
        <property name="username"><value>nkq4dev</value></property>
        <property name="password"><value>nkq4dev</value></property>
    </bean>
    
    <bean id="testData" class="com.ewp.test.data.TestData">
        <property name="mobileNumber" value="919686691376"/> 
        <property name="targetMobileNumber" value="919752890670"/>
    </bean>
</beans>
======================
//TopUpTest.java
import java.math.BigDecimal;
import java.util.Random;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import com.ewp.test.data.TestData;
import junit.framework.TestCase;

public class TopUpTest extends TestCase {
    final String PIN = "1111";
    private static ApplicationContext context;
    private static JdbcTemplate jdbcTemplate;
    private static TestData testData;
    private static DataSource dataSource;
    private static String mobileNumber = null;
    private static String targetMobileNumber = null;
    private static String topupAmount = 40;    

    static {
        context = new ClassPathXmlApplicationContext("testContext.xml");
        testData = (TestData) context.getBean("testData");        
        mobileNumber = testData.getMobileNumber();
        targetMobileNumber = testData.getTargetMobileNumber();    
    }
    /** ************ IMPLEMENTATION LEVEL TESTING *************** */

    @Override
    protected void setUp() throws Exception {
        dataSource = (DataSource) context.getBean("dataSource");
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    protected void tearDown() throws Exception {
        if (dataSource != null) {
            dataSource.getConnection().close();
        }
    }

    private TopUpServiceInterface getTopUpProxy() {
        TopUpServiceInterface paySvc = null;
        paySvc = (TopUpServiceInterface) ServiceProxy.getServiceProxy(TopUpServiceInterface.SERVICE_NAME);
        return paySvc;
    }

    //Mbill/Silver/Merchant,Correct pin
    public void testTopUpNumberCorrectPin() {
        TopUpServiceInterface impl = (TopUpServiceInterface) getTopUpProxy();
        try {
            TopUpSummary summary = impl.processTopup(mobileNumber,PIN, new BigDecimal(topupAmount), targetMobileNumber);
            int status = Integer.parseInt(summary.getStatus());
            assertEquals(summary.getErrorMessage(), 1, status);
        } catch (Exception exception) {
            fail(exception.toString()); //fail() is a method of Assert class in JUnit lib.
        }

    }
}
======================================
//Another test case methods with different return types/features
===============================
public void testUpgradeAccountForLockedAssistant()    throws EWPServiceException {
        try {
            token = TestUtility.getSecurityToken(testData.getTargetMobileNumber(), PIN);
            upgradeAcct(testData.getMobileNumber());
        } 
        catch (EWPServiceException e) {
            e.printStackTrace();
            assertEquals("BE2311", e.getErrorCode());            
        }
}
==============================
public void testDeleteBiller() {
        Boolean retVal = null;
        try {
            retVal = billPayServiceInterface.deleteBiller(testData.getMobileNumber(), new Long(12));
            LogHelper.error(CLASS_NAME, METHOD_NAME, "Delete Biller Status :["+ retVal+"]");
        } catch (com.ewp.core.exceptions.BusinessException e) {
            assertTrue(e instanceof com.ewp.core.exceptions.BusinessException);
        } catch (Exception e) {
            fail();
            e.printStackTrace();
        }
}
=============================
public void testIssueCard() {
        try {    
            NokiaPayAtmCardTest securitytoken = new NokiaPayAtmCardTest();            
            test.isAssistantActiveByMobileNumber(CommonHelpers.normalizePhoneNumber(assistantMobileNumber));
            test.issueCard(assistantMobileNumber, PIN,assistantMobileNumber, silverMobile, cardRefNumber1);
            assertTrue(true);
        }
        catch (Exception e) {

            e.printStackTrace();
            fail(e.getMessage());
        }
}
==============================

Now Again JUnit details:
junit.framework.Test (Interface)
Method Summary (only two methods):
 int     countTestCases()       ==> Counts the number of test cases that will be run by this test.
 void     run(TestResult result) ==> Runs a test and collects its result in a TestResult instance.

All Known Implementing Classes:
    ActiveTestSuite, JUnit4TestAdapter, JUnit4TestCaseFacade, 
    RepeatedTest, TestCase, TestDecorator, TestSetup, TestSuite 

==============================
public abstract class TestCase extends Assert implements Test

A test case defines the fixture to run multiple tests. To define a test case 
 1. implement a subclass of TestCase
 2. define instance variables that store the state of the fixture
 3. initialize the fixture state by overriding setUp()
 4. clean-up after a test by overriding tearDown().

Each test runs in its own fixture so there can be no side effects among test runs. Here is an example:

public class MathTest extends TestCase {
    protected double fValue1;
    protected double fValue2;

    protected void setUp() {
       fValue1= 2.0;
       fValue2= 3.0;
    }
}

For each test implement a method which interacts with the fixture. Verify the expected results with 
assertions specified by calling Assert.assertTrue(String, boolean) with a boolean.

    public void testAdd() {
       double result= fValue1 + fValue2;
       assertTrue(result == 5.0);
    }
====================================================

Once the methods are defined you can run them. The framework supports both a static type safe and 
more dynamic way to run a test. In the static way you override the runTest method and define the method 
to be invoked. A convenient way to do so is with an anonymous inner class.

TestCase test= new MathTest("add") {
    public void runTest() {
       testAdd();
    }
};
test.run();
--------------- 
The dynamic way uses reflection to implement runTest(). It dynamically finds and invokes a method. 
In this case the name of the test case has to correspond to the test method to be run.

TestCase test= new MathTest("testAdd");
test.run();
--------------- 

The tests to be run can be collected into a TestSuite. JUnit provides different test runners which 
can run a test suite and collect the results. A test runner either expects a static method suite as 
the entry point to get a test to run or it will extract the suite automatically.

//public class TestSuite extends java.lang.Object implements Test

A TestSuite is a Composite of Tests. It runs a collection of test cases. Here is an example using the 
dynamic test definition.

TestSuite suite= new TestSuite();
suite.addTest(new MathTest("testAdd"));
suite.addTest(new MathTest("testDivideByZero"));
 
Alternatively, a TestSuite can extract the tests to be run automatically. To do so you pass the class 
of your TestCase class to the TestSuite constructor.

TestSuite suite= new TestSuite(MathTest.class);

This constructor creates a suite with all the methods starting with "test" that take no arguments.
A final option is to do the same for a large array of test classes.

Class[] testClasses = { MathTest.class, AnotherTest.class }
TestSuite suite= new TestSuite(testClasses);

//Another example
public class TestA extends UITestCase { ... }

public class TestB extends UITestCase { ... }

public class TestC extends UITestCase { ... }

//Putting them in a suite is as simple as defining a class like this:
public class MyTestSuite extends TestCase {
        public static TestSuite suite() {
            TestSuite suite = new TestSuite();       
            suite.addTestSuite(TestA.class);
            suite.addTestSuite(TestB.class);
            suite.addTestSuite(TestC.class);
            return suite;
        }
}
-----------------------------------------------
Few more Test methods:
    fail(String)     :  Let the method fail, might be usable to check that a certain part of the code is not reached.
    assertTrue(true) :    True

    assertsEquals([String message], expected, actual):    Test if the values are the same. Note: for 
                                                    arrays the reference is checked not the content of the arrays
    assertsEquals([String message], expected, actual, tolerance): Usage for float and double; the tolerance 
                                                    are the number of decimals which must be the same
    assertNull([message], object):    Checks if the object is null
    assertNotNull([message], object):    Check if the object is not null
    assertSame([String], expected, actual):    Check if both variables refer to the same object
    assertNotSame([String], expected, actual):    Check that both variables refer not to the same object
    assertTrue([message], boolean condition):    Check if the boolean condition is true.
==============================================END====================================================

Friday, June 3, 2011

Primitive data types in Java

Java's Primitive Data Types

boolean
    1-bit. May take on the values true and false only.
    "true" and "false" are defined constants of the language and are not the same as 
    True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. 
    Booleans may not be cast into any other type of variable nor any other variable can be cast into a boolean.

byte
    1 signed byte (two's complement). Covers values from -128 to 127 (From 2^8 to 2^7).

short
    2 bytes, signed (two's complement), -32,768 to 32,767  (From 2^16 to 2^15)

int
    4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types integers may 
    be cast into other numeric types (byte, short, long, float, double). When lossy casts are done 
    (e.g. int to byte) the conversion is done modulo the length of the smaller type.

long
    8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float
    4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).
    Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). 
    When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and 
    the conversion is done modulo the length of the smaller type.

double
    8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). 

char
    2 bytes, unsigned, Unicode, 0 to 65,535
    Chars are not the same as bytes, ints, shorts or Strings.

Tuesday, May 31, 2011

java.lang.IllegalArgumentException: host parameter is null

Dear reader,

While working with Apache HttpClient you may face this error:

java.lang.IllegalArgumentException: host parameter is null
        at org.apache.commons.httpclient.HttpConnection.<init>(HttpConnection.java:206)
        at org.apache.commons.httpclient.HttpConnection.<init>(HttpConnection.java:155)
        at org.apache.commons.httpclient.SimpleHttpConnectionManager.getConnectionWithTimeout(SimpleHttpConnectionManager.java:175)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:153)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)

This comes in a multi-threaded stress test, when under heavy load concurrently opening many HttpClient connections, 
intermittently receives an IllegalArgumentException with the following stack trace:

java.lang.IllegalArgumentException: host parameter is null
at org.apache.commons.httpclient.HttpConnection.<init>(HttpConnection.java:206)
at org.apache.commons.httpclient.HttpConnection.<init>(HttpConnection.java:155)
at org.apache.commons.httpclient.SimpleHttpConnectionManager.getConnectionWithTimeout(SimpleHttpConnectionManager.java:175)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:153)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)


Again, this issue comes only intermittently under heavy connect load. There appears some sort of timing-related error in HttpClient. 
This comes in a “multi threaded environment when there are too many instances of HttpClient” created and system is not able to resolve HostName quickly.

Solution: Set explicitly the HostConfiguration before creating the GetMethod:

    PostMethod method = null;
    HttpClient httpclient = new HttpClient();
    String theURL = YOUR_PREPARED_URL;

    HostConfiguration hf=new HostConfiguration();
    hf.setHost("http://localhost", 22);
    
    method = new PostMethod(theURL);
    method.setHostConfiguration(hf);

    LogHelper.logMessage("Before sending SMS Message: "+message);
    int respCode = httpclient.executeMethod(method);
    System.out.println("Response code:"+respCode);  //200 means successful.

So far this will eliminate this intermittent failure.

//Code is tested and works fine..

Singleton pattern and Volatile in java

Dear reader,
Here is the complete example with test cases of Singleton Pattern in java. 

Conditions of Singleton pattern:
1) One and only one instance of that Class.
2) Can't be cloned as cloning creates a new object violating Design principles of SingletonPattern.

3) Any sub-class of Singleton class should not be allowed as there is a default constructor in Sub-class 
   and using that multiple objects can be created. So Singleton class should have private default 
   constructor to avoid getting invoked using super() from sub-class constructor.
   
4) Make instance variable as Volatile. volatile ensures that multiple threads handle the object correctly 
   when it is being initialized in the SingletonPattern. For more details about "volatile", please see
   at the end of this article.
   
5) Also, it should be designed in such a way that even after De-Serialization too, same object should be 
   returned. As making serialization and de-serialization multiple instances can be created. I have given 
   an example for this too.
   

//Full example (SingletonPattern.java)
public class SingletonPattern {
    private volatile static SingletonPattern object=null;
    private SingletonPattern(){}   //No subclass can be created because of this private default constructor.

    public static SingletonPattern getInstance(){ //Never put synchronized in method, else other threads will be 
                                                  //blocked for getting object.
        if(object==null){                         //Check instance, if there isn't one, enter a synchronized block.
          synchronized (SingletonPattern.class) {  //We only synchronized the first time through.
               if(object==null){                   //Once in the block, double check for null and create an instance.   
                  object=new SingletonPattern();
             }
          }
        }
        return object;
    }
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Cloning of this class is not allowed");  
    }
}

//Main test class (SingletonMain.java)
================Tries to extend SingletonClass: Prohibited================
/*public class SingletonMain extends SingletonPattern {
    public SingletonMain(){}   //Not allowed, as super class constructor is private.
    public static void main(String[] args) {
        SingletonPattern obj=SingletonPattern.getInstance();
        System.out.println(obj);

    }
}
*/
/*public class SingletonMain extends SingletonPattern { //Not allowed as it assumes a default constructor 
    //Constructor code is not written here.             //should be there in super class.
    public static void main(String[] args) {
        SingletonPattern obj=SingletonPattern.getInstance();
        System.out.println(obj);

    }
}
*/

================Tries to clone SingletonClass: Prohibited================
//Now your class need to implement Cloneable Interface and then only use the below
//code, else it will throw exception. Because if a class doesn't implement Cloneable,
//it can't be cloned.

public class SingletonMain implements Cloneable {                                
    public static void main(String[] args) throws Exception {
        SingletonPattern obj=SingletonPattern.getInstance();
        System.out.println(obj);
        SingletonPattern main=(SingletonPattern)(obj.clone()); //Will throw exception, cloning is prohibited.
        System.out.println(main);
    }
}

//Output when run SingletonMain class
SingletonPattern@360be0
Exception in thread "main" java.lang.CloneNotSupportedException: Cloning of this class is not allowed
    at SingletonPattern.clone(SingletonPattern.java:17)
    at SingletonMain.main(SingletonMain.java:25)
    

============================volatile===========================
Making instance volatile ensures that mulitple threads handle the object correctly when it is being 
initialized to the SingletonPattern class.

To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see 
double checked locking in Singleton with Volatile and without volatile keyword in java.
------------------
//This example is representation of Singleton Pattern discussed above

public class SingletonPattern {
    private static volatile SingletonPattern _instance;
    public static SingletonPattern getInstance() {
        if(_instance == null){
            synchronized(SingletonPattern.class){
                if(_instance == null)
                    _instance = new SingletonPattern();
            }
        }
    return _instance;
    }
}
------------------
If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creating _instance of SingletonPattern is 
not able to communicate other thread, that instance has been created until it comes out of the SingletonPattern 
block, so if Thread A is creating SingletonPattern instance and just after creation lost the CPU, all other 
threads will not be able to see value of "_instance" as not null and they will believe its still null.

Why because reader threads are not doing any locking and until writer thread comes out of synchronized 
block, memory will not be synchronized and value of _instance will not be updated in main memory. With 
Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader 
threads.


=======Last point to get the same object afer De-Serialization============
Now suppose we want the above Singleton class to be serializable. We can implement the Serializable interface 
for the above class and be done with it. But in that case we won’t be able to protect the singleton nature 
of the instance, such that after de-serialization there will be more than one instance of the class. 
This can be proved as follows:

Writing again the singleton pattern class:
////////////SingletonPattern.java
================================================
import java.io.ObjectStreamException;
import java.io.Serializable;
public class SingletonPattern implements Cloneable, Serializable{
    private volatile static SingletonPattern object=null;
    private SingletonPattern(){}   //No subclass can be created because of this private default constructor.

    public static SingletonPattern getInstance(){ //Never put synchronized in method, else other threads will be 
                                                  //blocked for getting object.
        if(object==null){                         //Check instance, if there isn't one, enter a synchronized block.
          synchronized (SingletonPattern.class) {  //We only synchronized the first time through.
               if(object==null){                   //Once in the block, double check for null and create an instance.   
                  object=new SingletonPattern();
             }
          }
        }
        return object;
    }
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Cloning of this class is not allowed");  
    }    
}
================================================
//////Main class to fetch SingletonPattern Object and do Serialization:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestMain {
    public static void main(String[] args) throws Exception{
        SingletonPattern object=SingletonPattern.getInstance();
        System.out.println("Original Singleton Object: "+object);
        
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("out3.dat")));  
        out.writeObject(object);  
        out.close();  

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("out3.dat")));  
        SingletonPattern deserObject = (SingletonPattern) in.readObject();  

        //After de-serialization we will get different object
        System.out.println("Deserialized Singleton Object: "+deserObject);
        in.close();  
        
        //Returning false, should return true.
        System.out.println("This shows false, should be true: "+(object == deserObject));  
        
        //Returning true.
        System.out.println("This shows true: "+(object == SingletonPattern.getInstance()));  
    }
}
////Output:
Original Singleton Object: SingletonPattern@164eee
Deserialized Singleton Object: SingletonPattern@16a04a
This shows false, should be true: false
This shows true: true
================================================

You can analyze the output, two different Singleton Objects are there and equality shows FALSE.
This breaks the rule of Singleton class. The way to avoid this is using another hook, the readResolve() 
method. The readResolve() method is called when the  ObjectInputStream has read an object from the 
stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the 
object defines the readResolve() method. If the method is defined, the readResolve method is called to 
allow any changes in the object before it is returned.

So now we will add the readResolve() method in SingletonPattern.java, the modified code is:

================================
import java.io.ObjectStreamException;
import java.io.Serializable;
public class SingletonPattern implements Cloneable, Serializable{
    private volatile static SingletonPattern object=null;
    private SingletonPattern(){}   //No subclass can be created because of this private default constructor.

    public static SingletonPattern getInstance(){ //Never put synchronized in method, else other threads will be 
                                                  //blocked for getting object.
        if(object==null){                         //Check instance, if there isn't one, enter a synchronized block.
          synchronized (SingletonPattern.class) {  //We only synchronized the first time through.
               if(object==null){                   //Once in the block, double check for null and create an instance.   
                  object=new SingletonPattern();
             }
          }
        }
        return object;
    }
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Cloning of this class is not allowed");  
    }
    private Object readResolve() throws ObjectStreamException {  
        return getInstance();  
    } 
}
================================

Now if you run the TestMain program again you will see output (it will show equality as TRUE) and
objects are equal. It means that even after de-serialization, we still have only one instance of the class in 
our JVM.
==============
//Output
Original Singleton Object: SingletonPattern@164efe
Deserialized Singleton Object: SingletonPattern@164efe
This shows false, should be true: true   
This shows true: true
==============

--------------------------------END-----------------------------------

Friday, May 27, 2011

Transaction related Query to display two immediate transaction time difference

Transaction related Query to display two immediate transaction time difference

SELECT *

FROM
(
SELECT mt.transnumber
      ,LEAD(mt.transnumber, 1, 1) OVER (PARTITION BY TRNTYPE ORDER BY id) next_transnumber
      ,mt.trntype 
      ,mt.modifiedtimestamp transaction_time
      ,LEAD(mt.modifiedtimestamp, 1, SYSDATE) OVER (PARTITION BY TRNTYPE ORDER BY id)  next_transaction_time
      ,floor(((LEAD(mt.modifiedtimestamp, 1, SYSDATE) OVER (PARTITION BY TRNTYPE ORDER BY id) - mt.modifiedtimestamp)*24*60*60)/3600) time_diff
  FROM mastertxn mt 
WHERE trntype = 'TOPUP' 
ORDER BY ID
)
WHERE time_diff >= 1


//Output pattern
                                                                                        
TRANSNUMBER  NEXT_TRANSNUMBER TRNTYPE    TRANSACTION_TIME      NEXT_TRANSACTION_TIME    TIME_DIFF 
1244           1360            TOPUP     05.10.2010 23:58:39   07.10.2010 10:48:43        34
1360           1408            TOPUP     07.10.2010 10:48:43   07.10.2010 16:34:55         5
1442           1507            TOPUP     07.10.2010 19:19:33   08.10.2010 11:26:43        16 

Tuesday, May 17, 2011

How to fix "java.io.EOFException: Response contained no data"

How to fix "java.io.EOFException: Response contained no data"
Some time while working in Weblogic server environment, we are getting this exception intermittently:

java.io.EOFException: Response contained no data
        at weblogic.net.http.MessageHeader.isHTTP(MessageHeader.java:222)
        at weblogic.net.http.MessageHeader.parseHeader(MessageHeader.java:143)
        at weblogic.net.http.HttpClient.parseHTTP(HttpClient.java:475)
        at weblogic.net.http.HttpURLConnection.getInputStream(HttpURLConnection.java:368)
        at weblogic.net.http.SOAPHttpURLConnection.getInputStream(SOAPHttpURLConnection.java:36)        

The root cause of this is, You might be using a code base like this:

    URLConnection con = url.openConnection();
    con.setUseCaches(false); 
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setRequestProperty("Content-Type", "text/xml");
            
    //now construct the parameter data.
    OutputStream os = con.getOutputStream();
    os.write(formattedParams);
    os.flush();
          
    BufferedInputStream is = new BufferedInputStream(con.getInputStream());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    buff = new byte[1024];    
    int bytesRead = -1;
    while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
        bos.write(buff, 0, buff.length);
    }
    retval = bos.toByteArray();

//Reason is: URLConnection is an Abstract class, so when your application runs on any server, Server specific URLConnection
API is getting used, here "weblogic.net.http.SOAPHttpURLConnection".
So "URLConnection.getInputStream()" is getting replaced with "weblogic.net.http.HttpURLConnection.getInputStream()".
And so some time it will go fine, other time it won't work. So this comes intermittently.

//Fix: Replace URLConnection API with Concrete class Apache's HttpClient API, so application will be server independent.
//Fix code base (You need “commons-httpclient-3.1.jar” for compiling this code snippet):

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

    PostMethod method=null;
    HttpClient httpclient=null;
    try {
        String theURL = "URL";  //Constuct URL here.
        httpclient = new HttpClient();

        method = new PostMethod(theURL);
        //If you want to add some header info
        String encoding = new sun.misc.BASE64Encoder().encode("userPassword".getBytes());
        method.setRequestHeader("Authorization","Basic " + encoding);
            
        LogHelper.logMessage("Before sending SMS Message: "+message);

        int respCode = httpclient.executeMethod(method);
        if(respCode != HttpStatus.SC_OK) {
            LogHelper.error("Http Method failed for URL :").append(theURL).toString()+", HTTPStatusCode:"+respCode);
        }
        else {
            String responseString = method.getResponseBodyAsString(); //Give response as String.

            /*
                        //Get response as Stream.  
            BufferedReader br = null;
            FileWriter fw = null;
            br = new BufferedReader(new InputStreamReader(httpPost.getResponseBodyAsStream()));
            String tmp = null;
            StringBuffer httpResponseBuffer = new StringBuffer();
            int i = 0;
            while ((tmp = br.readLine()) != null) {
                if (i++ > 0) {
                    httpResponseBuffer.append(System.getProperty("line.separator"));
                    }
                httpResponseBuffer.append(tmp);
            }
            if (writeToFile) {
                fw=new FileWriter(pathToFile);
                fw.write(httpResponseBuffer.toString());
                fw.flush();
            }
            retval = httpResponseBuffer.toString();
                        */

            LogHelper.logMessage("Decoded Response String: "+responseString);

            status = parseSMSResponse(responseString);
            if (status != null) {
                    sendFlag = isStatusOK(status);
            }


NOTE: Definitely it should work, tested code and we have used in our application.
---------------Definitely -----------------