02 April, 2012

Simulate Oracle Built-in Functions in Java

All PL/SQL developers always use below function  a lot anywhere in their codes
NVL , NVL2 , DECODE and COALESCE

Previous function aren't available directly in Java, So I will develop simulation to them in Java.
All functions return Object so you should cast it to your class in using.

 public class MahmoudUtils {  
   public static Object decode(Object[] args) throws Exception {  
     Object compareItem = args[0];  
     int maxIndex = args.length - 1;  
     int indx = 1;  
     if (compareItem != null) {  
       for (; indx < maxIndex; indx += 2) {  
         if (compareItem.equals(args[indx])) {  
           return args[indx + 1];  
         }  
       }  
     } else {  
       throw new Exception("MahmoudUtils.decode :: First Element in array is null value");  
     }  
     return indx == maxIndex ? args[indx] : null;  
   }  
   public static Object coalesce(Object[] args) {  
     for (int indx = 0; indx < args.length; indx++) {  
       if (args[indx] != null) {  
         return args[indx];  
       }  
     }  
     return null;  
   }  
   public static Object nvl(Object firstParameter, Object secondParameter) {  
     return (firstParameter != null ? firstParameter : secondParameter);  
   }  
   public static Object nvl2(Object firstParameter, Object secondParameter, Object thirdParameer) {  
     return (firstParameter != null ? secondParameter : thirdParameer);  
   }  
   public static void main(String[] args) throws Exception {  
     System.out.println("====Test decode");  
     System.out.println(MahmoudUtils.decode(new Object[] { "mah", 1, null, 3, 4, "mah", "Yes, Iam Mahmoud", 9 }));  
     System.out.println("====Test NVL");  
     System.out.println(MahmoudUtils.nvl(null, "First Parameter is null"));  
     System.out.println(MahmoudUtils.nvl("First Parameter is not null", "First Parameter is null"));  
     System.out.println("====Test coalesce");  
     System.out.println(MahmoudUtils.coalesce(new Object[] { null, 1, null, 3, 4, "mah", "Yes, Iam Mahmoud", 9 }));  
     System.out.println("====Test NVL2");  
     System.out.println(MahmoudUtils.nvl2("First Value is not null", "Not null value", "Null value"));  
   }  
 }  

Conclusion
You can develop all important Oracle built-in function that don't exists directly in Java.

Thanks
Recommended Post Slide Out For Blogger