Monday, December 02, 2013

Parse SOAP Message Using PL/SQL

Suppose we want to parse bellow SOAP message :

   
   
      
         SOAP-ENV:Client
         The security token could not be authenticated or authorized; nested exception is org.apache.ws.security.WSSecurityException: The security token could not be authenticated or authorized
      
   


To parse this SOAP we can write script like :
CREATE TABLE XMLMESSAGE(

  message XMLTYPE

  serial  number,
)


--before running bellow script insert the message in previously created table

select atts.faultcode,atts.faultstring 

   from XMLMESSAGE,
        xmltable(xmlnamespaces('http://schemas.xmlsoap.org/soap/envelope/' as
                               "SOAP-ENV"
                       
                           ),
                 '/SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault'
                 passing XMLMESSAGE.MESSAGE columns 
                 faultcode varchar2(1000) path ''faultcode',
                 faultstring varchar2(1000) path ''faultstring'
                 ) atts where serial = 1;
  

Saturday, November 30, 2013

PL/SQL Custom Exception Handaling


DECLARE

  v_Return VARCHAR2(5000);

  custom_exception EXCEPTION;

BEGIN

  v_Return := 'A';
  
  
  IF v_Return = 'A' THEN
    RAISE custom_exception;
  END IF;

EXCEPTION
  WHEN custom_exception THEN
    DBMS_OUTPUT.PUT_LINE('error');
  
END;

Thursday, November 28, 2013

Script to Create PL/SQL Pakcgage

Creating pl/sql package has two simple step . First create package name and needed function/procedure declaration .
CREATE OR REPLACE PACKAGE XML_PARSER AS
  
   FUNCTION PARSE_ACCOUNT_INFO RETURN VARCHAR2;
    
END XML_PARSER;
/

Second Step : Creating package body with actual implementation of function/procedure previously defined in creation of package.
CREATE OR REPLACE PACKAGE BODY XML_PARSER AS

  FUNCTION PARSE_ACCOUNT_INFO RETURN VARCHAR2 IS 
    TEMP VARCHAR2(10);
    BEGIN
      NULL;
    END;


END XML_PARSER;
/



Monday, November 18, 2013

The TCS Story and Beyond

Author: S. Ramadorai
Publisher: Portfolio (2013)  
On the last moment before leaving chennai of my official visit to there i bough this book , but my traveler mate take the book for reading in flight . Very next day i started reading the book .



Experience after reading 30 page : I was mad to complete the book.

Whatever ! content of this book is based on real life experience of a CEO who joined in a small growing company at India while has had good opportunity at west with good salary . He joined and finally retired as a CEO of that company and along this long journey that company became one of the large IT enabled service provider in market.

What one can find this book :
A young job seeker will know about the right decision about job and getting married and taking challenges.

A young engineer will know how to interact with potential clients and adopt new technology.

Its a must read book for any new entrepreneur.

A must book read book for software engineer .

The story of IT market expansion and adoption of new technology and solution are represented here with beauty.

One can find design strategy and industry collaboration effect and impotence of R&D in every sector of technology and business  towards progress.

Create New Schema in Oracle

Step One : Create Table Space


CREATE TABLESPACE SPR_DATA  DATAFILE 
'location in local hard disk\SPR_DATA_01.DBF'
SIZE 1000M EXTENT MANAGEMENT LOCAL AUTOALLOCATE SEGMENT SPACE     
MANAGEMENT AUTO;

Step Two: Create User

CREATE USER sprora IDENTIFIED BY "sprora" DEFAULT TABLESPACE SPR_DATE;

Step Three: Giving Permission

GRANT CONNECT TO sprora;
ALTER USER SPRORA QUOTA UNLIMITED ON SPR_DATA;
GRANT CREATE TABLE TO SPRORA;
GRANT DBA TO SPRORA; 
GRANT CREATE SESSION,CREATE TABLE,CREATE SEQUENCE,CREATE VIEW TO sprora; 
GRANT EXECUTE ON DBMS_SQLHASH TO  sprora;
GRANT EXECUTE ON DBMS_LOCK TO sprora;
GRANT DEBUG CONNECT SESSION TO sprora; 
GRANT DEBUG ANY PROCEDURE TO sprora;

Step Four: Connect as new user and create test table

CONNECT sprora/sprora
CREATE TABLE TEST (CITY varchar2(32), POPULATION number);
INSERT INTO TEST (CITY, POPULATION) values ('edmonton', 10);
INSERT INTO TEST (CITY, POPULATION) values ('vancouver', 20);
COMMIT;

Now test newly created table using select query :
SELECT * FROM TEST


Wednesday, July 03, 2013

Writing Resume for Software Company

Fresh graduate has to write resume to represent himself/herself as a potential candidate for a job. Initially it seems a easy task to do , yes it is easy in terms of typing in a key board by enough tricky.

To Do or Not To Do :
-Write your objective as simple as possible , i recommend one - two lines .
-Must use formal English and use simple words.
-Do not put your personal information : such as --- race , moms name etc.
-Focus on your achievement rather responsibility in previous position
-Put only those technical skill you know properly , never put something super special but you have no idea with that.
-Highlight your academic performance.
-In top  : Write name , address and contact number properly
-Two page is enough to represent you , may up to three page , but not more then that . All are busy in these day they don't have much time to read your long story .
-Always use PDF format while sending resume.-Send your resume to your known ones and ask for review and comments on that , this will help you to overcome silly mistake.
-Hey! you resume if not a polish diamond , share it with others , don't be poor minded.
-Highlight research experience , if you have any but not mandatory .
-



Monday, July 01, 2013

Example of Advanced Encryption Standard (AES) using JAVA

Example of AES using JAVA : 

Note : For base64 related method visit this post.
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;



/**
 * 
 * @author : ThinkTank
 * 
 * 
 */


public class AESEncryption {
 private KeyGenerator keyGenerator;
 private SecureRandom secureRandom;
 private byte[] randomBytes = new byte[100];
 private byte[] encryptedData = new byte[20000];
 private byte[] decryptedData = new byte[20000];
 private String encryptedDataAsBase64String;
 private SecretKey secretKey;
 private SecretKeySpec secretKeySpec;
 private Cipher cipher;
 private String originalData;



 /**
  * This method will encrypt data as our desired level
  * 
  * @param data data to be encrypted
  * @param encryptionLevel level of encryption
  * @param secureRandomSeed seed value 
  * @return encrypted string
  */
 public String encrypt(byte[] data,int encryptionLevel,int secureRandomSeed) {
  try {
   keyGenerator = KeyGenerator.getInstance("AES");
   keyGenerator.init(encryptionLevel);

   secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
   secureRandom.setSeed(secureRandomSeed);

   secureRandom.nextBytes(randomBytes);

   secretKey = keyGenerator.generateKey();
   byte[] primaryEncodedKey = secretKey.getEncoded();

   secretKeySpec = new SecretKeySpec(primaryEncodedKey, "AES");

   cipher = Cipher.getInstance("AES");
   cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

   encryptedData = cipher.doFinal(data);

   encryptedDataAsBase64String = Util.byteToBase64(encryptedData);

  } catch (NoSuchProviderException e) {
   e.getStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.getStackTrace();
  } catch (NoSuchPaddingException e) {
   e.getStackTrace();
  } catch (InvalidKeyException e) {
   e.getStackTrace();
  } catch (BadPaddingException e) {
   e.getStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.getStackTrace();
  }
  return encryptedDataAsBase64String;
 }

 /**
  * This method will return decrypted data
  *  
  * @return decrypted data as string 
  */
 public String decrypt(byte[] encryptedData) {
  
  try {
   cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
   decryptedData = cipher.doFinal(encryptedData);
   originalData = new String(decryptedData);
  } catch (InvalidKeyException e) {
   e.getStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.getStackTrace();
  } catch (BadPaddingException e) {
   e.getStackTrace();
  }
  return originalData;
 }
}


Ready to use One way Digest util class in JAVA or Example of SHA-512 Digest Using Java



Ready to use One way digest Java Class


Note : For base64 related method visit this post :


import java.security.MessageDigest;
import java.security.SecureRandom;


/**
 * 
 * @author : ThinkTank
 * 
 */



public class PasswordDigest {

/**
 * This method will compute hash as string for given password
 * 
 * @param salt salt value
 * @param passDigest password digest
 * @param password password which will digested 
 * @param iterationNumber number of iteration
 * @return password hash value
 * @throws Exception
 */
public static String recomputeHash(byte[] salt, String passDigest,String password,int iterationNumber) throws Exception {
 byte regeneratedHash[] = PasswordDigest.getHash(iterationNumber, password, salt);
 return Util.byteToBase64(regeneratedHash);
}

/**
 * @param iterationNumber
 * @param password
 * @param salt
 * @return hash digest as byte array
 * @throws Exception
 */
public static byte[] getHash(int iterationNumber, String password, byte[] salt) throws Exception {
 MessageDigest digest = MessageDigest.getInstance("SHA-512");
 digest.reset();
 digest.update(salt);
 byte[] input = digest.digest(password.getBytes("UTF-8"));
 for (int i = 0; i < iterationNumber; i++) {
  digest.reset();
  input = digest.digest(input);
 }
 return input;
}

/**
 * This method will generate salt value and return it as byte array
 * 
 * @return salt value as byte array
 * @throws Exception
 */
public static byte[] getSalt() throws Exception {
 SecureRandom secureRandom;
 byte[] bSalt = new byte[8];
 secureRandom = SecureRandom.getInstance("SHA1PRNG","SUN");
 secureRandom.nextBytes(bSalt);
 return bSalt;
}

}

Convert Base64 to Byte and Byte to Base64 in Java


Simple Ready to use utility class to convert : base64 -> byte and byte -> base64
import org.apache.commons.codec.binary.Base64;


public class Util {

 /**
  * 
  * This method take base64 type string as input and
  * convert it to byte[] array
  *  
  * @param data base64 type string
  * @return byte array
  * @throws Exception
  *  
  */

 @SuppressWarnings("unused")
 public static byte[] base64ToByte(String data) throws Exception {
  Base64 base64 = new Base64();
  return Base64.decodeBase64(data);
 }

 /**
  * This method take byte array as input and
  * convert it to base64 string
  * 
  * @param data byte array
  * @return base64 string
  * 
  */
 @SuppressWarnings("static-access")
 public static String byteToBase64(byte[] data) {
  Base64 base64 = new Base64();
  return base64.encodeBase64String(data);
 }

}

Saturday, May 18, 2013

New Date & Time API in JDK8

The existing Java date and time classes are poor, mutable, and have unpredictable performance. There has been a long-standing desire for a better date and time API based on the Joda-Time project. The new API will have a more intuitive design allowing code to better express its intent. The classes will also be immutable which aligns with the multi-core direction of the industry.

package com.lambada.practice;

import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;

public class EarlyReleaseDemo {

 
 public static void main (String [] args) {
  new EarlyReleaseDemo().dataAndTimeAPI();
 }
 
 
 public void dataAndTimeAPI() {
  Clock clock = Clock.systemUTC();
  System.out.println("Current time in milisecond : " +clock.millis());
  
  LocalDate date = LocalDate.now();
  
  LocalTime localTime = LocalTime.now();

  
  
  ZoneId zoneId = ZoneId.systemDefault();
  
  //console output
  System.out.println("Current Time : " +localTime);
  System.out.println("Current Hour : " +localTime.getHour());
  System.out.println("Current Min. : " +localTime.getMinute());
  System.out.println("Current Second : " +localTime.getSecond());
  System.out.println("Todays date : " +date);
  System.out.println("Year : "+date.getYear());
  System.out.println("Month Value : "+date.getMonthValue());
  System.out.println("Month :"+date.getMonth());
  System.out.println("Day of Month :"+date.getDayOfMonth());
  System.out.println("Day of year : "+date.getDayOfYear());
  System.out.println("System default zone : " +zoneId.normalized());
  System.out.println("Available Zone Id's :" + zoneId.getAvailableZoneIds());

 }
}


//output
Current time in milisecond : 1368893133938
Current Time : 22:05:34.048
Current Hour : 22
Current Min. : 5
Current Second : 34
Todays date : 2013-05-18
Year : 2013
Month Value : 5
Month :MAY
Day of Month :18
Day of year : 138
System default zone : Asia/Almaty
Available Zone Id's :[America/Virgin, Europe/London, Atlantic/Reykjavik, Canada/Eastern, Africa/Ndjamena, America/Grenada, Asia/Saigon, Asia/Muscat, Europe/Sarajevo, America/Belem, Eire, Greenwich, Universal, Asia/Kashgar, ...........
Reference's : http://openjdk.java.net/jeps/150
http://ttux.net/post/java-8-new-features-release-performance-code/

Wednesday, May 08, 2013

Ad hoc polymorphism With Java Example

In programming languages, ad hoc polymorphism[1] is a kind of polymorphism in which polymorphic functions can be applied to arguments of different types, because a polymorphic function can denote a number of distinct and potentially heterogeneous implementations depending on the type of argument(s) to which it is applied. It is also known as function overloading or operator overloading. The term "ad hoc" in this context is not intended to be pejorative; it refers simply to the fact that this type of polymorphism is not a fundamental feature of the type system. This is in contrast to parametric polymorphism, in which polymorphic functions are written without mention of any specific type, and can thus apply a single abstract implementation to any number of types in a transparent way. This classification was introduced by Christopher Strachey in 1967.
(ref : http://en.wikipedia.org/wiki/Ad-hoc_polymorphism)

// credit to choychoy
List list = new ArrayList(Arrays.asList(1,2,3));
int v = 1;
list.remove(v);
System.out.println(list); // prints [1, 3]

List list = new ArrayList(Arrays.asList(1,2,3));
Integer v = 1;
list.remove(v);
System.out.println(list); // prints [2, 3]

http://blog.functr.com/2012/08/java-oddities-part-ii.html
http://www.reddit.com/r/programming/comments/z2n9f/javawat_part_i/

Script to Disable Default F5 key using java script

function disableKey(event) {

 if (!event)
  event = window.event;
 if (!event)
  return;

 var keyCode = event.keyCode ? event.keyCode : event.charCode;
 if (keyCode == 116 || (event.ctrlKey && keyCode == 82)) {
   /* window.status = "F5 key detected! Attempting to disabling default
   * response."; window.setTimeout("window.status='';", 2000);
   */
  if (event.preventDefault)
   event.preventDefault();

  //IE (exclude Opera with !event.preventDefault):
  if (document.all && window.event && !event.preventDefault) {
   event.cancelBubble = true;
   event.returnValue = false;
   event.keyCode = 0;
  }

  return false;
 }
a
}

function setEventListener(eventListener) {
 if (document.addEventListener)
  document.addEventListener('keypress', eventListener, true);
 else if (document.attachEvent)
  document.attachEvent('onkeydown', eventListener);
 else
  document.onkeydown = eventListener;
}

function unsetEventListener(eventListener) {
 if (document.removeEventListener)
  document.removeEventListener('keypress', eventListener, true);
 else if (document.detachEvent)
  document.detachEvent('onkeydown', eventListener);
 else
  document.onkeydown = null;
}

setEventListener(disableKey)


Modules of Spring Framework

Introduction :

Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application.
Spring enables you to build applications from “plain old Java objects” (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE.
Examples of how you, as an application developer, can use the Spring platform advantage:
  • Make a Java method execute in a database transaction without having to deal with transaction APIs.
  • Make a local Java method a remote procedure without having to deal with remote APIs.
  • Make a local Java method a management operation without having to deal with JMX APIs.
  • Make a local Java method a message handler without having to deal with JMS APIs.

    (Reference : http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/overview.html)

    Modules  of Spring Framework :

    Core Container

    The Core Container consists of the Core, Beans, Context, and Expression Language modules.
    The Core and Beans modules provide the fundamental parts of the framework, including the IoC and Dependency Injection features. The BeanFactory is a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.
    The Context module builds on the solid base provided by the Core and Beans modules: it is a means to access objects in a framework-style manner that is similar to a JNDI registry. The Context module inherits its features from the Beans module and adds support for internationalization (using, for example, resource bundles), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container. The Context module also supports Java EE features such as EJB, JMX ,and basic remoting. The ApplicationContext interface is the focal point of the Context module.
    The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime. It is an extension of the unified expression language (unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting property values, property assignment, method invocation, accessing the context of arrays, collections and indexers, logical and arithmetic operators, named variables, and retrieval of objects by name from Spring's IoC container. It also supports list projection and selection as well as common list aggregations.

    Data Access/Integration

    The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules.

    Web

    The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules.
    Spring's Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context. It also contains the web-related parts of Spring's remoting support.

    AOP and Instrumentation

    Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. Using source-level metadata functionality, you can also incorporate behavioral information into your code, in a manner similar to that of .NET attributes.
    The separate Aspects module provides integration with AspectJ.
    The Instrumentation module provides class instrumentation support and classloader implementations to be used in certain application servers.

    Test

    The Test module supports the testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that you can use to test your code in isolation.

Wednesday, May 01, 2013

Drop Down List in GWT

To achieve this, we need to work on ListBox of GWT.
public class ListBoxExample implements EntryPoint {

  public void onModuleLoad() {
    // Make a new list box, adding a few items to it.
    ListBox lb = new ListBox();
    lb.addItem("foo");
    lb.addItem("bar");
    lb.addItem("baz");
    lb.addItem("toto");
    lb.addItem("tintin");

    // Make enough room for all five items (setting this value to 1 turns it
    // into a drop-down list).
    lb.setVisibleItemCount(1);

    // Add it to the root panel.
    RootPanel.get().add(lb);
  }
}

Monday, April 29, 2013

Close GWT Dilouge Box on KeyBoard ESCAPE Key

Requirement : Closeable dialogue box in GWT upon ESC key of keyboard. To achieve this we just need to override a GWT method.
private class ExtendedDialogBox extends DialogBox {

  
  protected void onPreviewNativeEvent(NativePreviewEvent event) {
   super.onPreviewNativeEvent(event);
   switch (event.getTypeInt()) {
   case Event.ONKEYDOWN:
    if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) {
     hide();
    }
    break;
   }
  }
 }

Prevent Default Refresh Event in Browser Using GWT

Bit odd requirement that if anyone need to prevent default Cntrl + R or F5 event using GWT (Google Web Tool Kit). It can be done easily. In onModuleMethod of EntryPoint class just use this code.

public void onModuleLoad() {
   
         
      //disable refresh button
  Event.addNativePreviewHandler(new NativePreviewHandler() {

   public void onPreviewNativeEvent(NativePreviewEvent event) {
    switch (event.getTypeInt()) {
    case Event.ONKEYDOWN:
     NativeEvent nEvent = event.getNativeEvent();
     if (nEvent.getCtrlKey() && nEvent.getKeyCode() == 'R') {
      nEvent.preventDefault();
     }

     if (nEvent.getKeyCode() == 116) {
      nEvent.preventDefault();
     }
     break;
    }
   }
  });

  }


This will full fill the need across the GWT application. Reference : Co worker : Ruhul

Monday, April 22, 2013

Load Image from DB and Show it in browser using Google Web Toolkit



A widget that displays the image at a given URL. The image can be in 'unclipped' mode (the default) or 'clipped' mode. In clipped mode, a viewport is overlaid on top of the image so that a subset of the image will be displayed. In unclipped mode, there is no viewport - the entire image will be visible. Whether an image is in clipped or unclipped mode depends on how the image is constructed, and how it is transformed after construction. Methods will operate differently depending on the mode that the image is in. These differences are detailed in the documentation for each method.
If an image transitions between clipped mode and unclipped mode, any Element-specific attributes added by the user (including style attributes, style names, and style modifiers), except for event listeners, will be lost.
reference :

 http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/Image.html

http://stackoverflow.com/questions/6409587/generating-an-inline-image-with-java-gwt 

public String getImage (String id) {
       String imageDataAsString = new String();
       byte imageBytes[] = new byte[5000];
       imageBytes = imageService.getImageById(id);
return encodeasBase64(imageBytes);
}

    


//convert data to base64 string
// * base64 codec ported with GWT will not going to work , use commons codec  *
// * this method is responsible to convert byteArray to base64 
//     * encoded string 
//*org.apache.commons.codec.binary.Base64*

public String encodeasBase64(byte[] imageByteArray) {
  StringBuilder imageDataAsbase64String = new StringBuilder();
  String  encodedString = new 
           String(Base64.encodeBase64(imageByteArray));

  imageDataAsbase64String.append("data:image/jpg;base64,");

  imageDataAsbase64String.append(encodedString);

  return imageDataAsbase64String.toString();
}


// Data will come from GWT rpc call , rpc call can be initiate upon click event
public void displayImage(String result) {
    Image image = new Image(result);
    HorizontalPanel imagePanel = new HorizontalPanel();
    
    DialogBox dialogueBox = new DialogBox();
    imagePanel.add(image);
    dialogueBox.setWidget(imagePanel);
    dialogueBox.show();
}