Sunday, April 22, 2012

How to format an XML String in java

Generally we get XMLs as string in java and that is highly unreadable and unformatted.

How do I format it ??

I am just presenting one of the many ways to do that.

Thanks to http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java

You would need to import these:

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

Pretty straight forward function is available:

public static String prettyFormat(String input, int indent) {
        try
        {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            // This statement works with JDK 6
            transformerFactory.setAttribute("indent-number", indent);
            
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        }
        catch (Throwable e)
        {
            // You'll come here if you are using JDK 1.5
            // you are getting an the following exeption
            // java.lang.IllegalArgumentException: Not supported: indent-number
            // Use this code (Set the output property in transformer.
            try
            {
                Source xmlInput = new StreamSource(new StringReader(input));
                StringWriter stringWriter = new StringWriter();
                StreamResult xmlOutput = new StreamResult(stringWriter);
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
                transformer.transform(xmlInput, xmlOutput);
                return xmlOutput.getWriter().toString();
            }
            catch(Throwable t)
            {
                return input;
            }
        }
    }

    public static String prettyFormat(String input) {
        return prettyFormat(input, 2);
    }

How to log SOAP Request and response XML in log file

Thanks to http://www.coderanch.com/t/549539/Web-Services/java/Convert-SOAP-response-SOAP-XmL
http://qa.netbeans.org/modules/j2ee/promo-g/end2end/hello_ws.html

It is mostly desired to log the SOAP request and response XML into log file.
But there is no direct way, using which you can log the XML, because the XML generation part is in the control of the webservice framework. But the good news that you can configure it to print the XML where ever you like it to.

Configure logging of XML on server side using Netbeans

Creating web project
  1. Go to File - New Project - Web - Web Application
  2. Specify HelloWs as Project Name
  3. Specify project's directory
  4. Choose Java EE 5 as J2EE version and
  5. Click Finish
Creating web service
  1. Go to File - New File - Web services - Web Service - Next
  2. Specify name of web service, eg. HelloWebService
  3. Specify package for the web service, eg. org.netbeans.end2end.hellosample
  4. Click Finish
Implementing web service
  1. Uncomment commented code in source file
  2. Add serviceName="GreeterWs" to WebService annotation
  3. Add operationName="sayHi" to WebMethod annotation
  4. Add @WebParam(name="name") to String param argument of method operation
  5. Add new sayHello(String): String operation to web service using Web Service -> Add Operation... action in editor
    Implement both operation, so the implementation class will look like this:
Creating message handler
  • Go to File - New File - Web services - Message Handler - Next
  • Specify name of message handler, eg. MessageHandler
  • Specify package for the message handler, eg. org.netbeans.end2end.hellosample
  • Click Finish
  • Implement simple log method in handler, eg. like on following picture:


  • And add handler to the webservice using Configure Handlers... action in context menu on HelloWebService's node

Configure logging of XML on client side using Netbeans

Write a myHandler as follows:
import java.io.IOException;  
import java.util.Set;  
  
import javax.xml.soap.SOAPException;  
import javax.xml.soap.SOAPMessage;  
import javax.xml.ws.handler.MessageContext;  
import javax.xml.ws.handler.soap.SOAPHandler;  
import javax.xml.ws.handler.soap.SOAPMessageContext;  
  
public class MyHandler implements SOAPHandler {  
  
    public boolean handleMessage(SOAPMessageContext smc) {  
  
        Boolean outboundProperty = (Boolean) smc  
                .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);  
  
        SOAPMessage message = smc.getMessage();  
        // This if condition gets reversed when we write
        // code on client side.
        if (outboundProperty.booleanValue()) {  
            System.out.print(" SOAP Request ");  
        } else {  
            System.out.print(" SOAP Respone ");  
        }  
  
        try {  
            message.writeTo(System.out);  
        } catch (SOAPException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        System.out.println("");  
        // if this function will return true, only then the chaining concept will work.
        // if we return outboundProperty which happens to be false in some cases
        // the chaining will not work.  
        //return outboundProperty;  
        return true;
  
    }  
  
    public Set getHeaders() {  
        return null;  
    }  
  
    public boolean handleFault(SOAPMessageContext context) {  
        return true;  
    }  
  
    public void close(MessageContext context) {  
    }  
}  
And write myHanlderResolver like this:
import java.util.ArrayList;  
import java.util.List;  
  
import javax.xml.ws.handler.HandlerResolver;  
import javax.xml.ws.handler.PortInfo;  
  
public class MyHandlerResolver implements HandlerResolver {  
  
    public List getHandlerChain(PortInfo portInfo) {  
        ArrayList handlerChain = new ArrayList();  
        handlerChain.add(new MyHandler());  
        return handlerChain;  
    }  
  
} 
To associate your handler with the web service, you need to do something like this:
myws.service = new myws_Service(); 
System.out.println("Now setting the HandlerResolver");
// Following two 
HandlerResolver myHanlderResolver = new MyHandlerResolver();
service.setHandlerResolver(myHanlderResolver);
System.out.println("myHandlerResolver has been set.");

How to convert SOAPMessage to a String

'
private String log(SOAPMessage message) throws SOAPException, IOException
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        message.writeTo(out);
        logger.debug(out.toString());
        return out.toString();
    }
You might like reading this : http://javakafunda.blogspot.in/2012/04/how-to-format-xml-string-in-java.html

Tuesday, April 17, 2012

Providing a default exception handling strategy in Java applications

Source : http://blog.smartkey.co.uk/2012/03/providing-a-default-exceptoin-strategy/comment-page-1/

When writing a Java application you may need to consider how that application should react when an uncaught exception is encountered. Generally, when an exception is not handled, the threads stack trace is printed to the error stream and the throwing thread dies; potentially causing the application to shut down if there are no other active (or daemon) threads running.

If your application runs as a server, then there will likely be multiple threads (created by the IO libraries) which are used to respond to the incoming requests. This makes it hard to implement a consistent strategy that can handle all uncaught exceptions in a uniform way.

The following program illustrates how to register a default policy for handling uncaught exceptions

public class TestMain 
{
 public static void main(String[] args) 
 {
  Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() 
  {
   @Override
   public void uncaughtException(Thread t, Throwable e) 
   {
    if (e instanceof InvocationTargetException) 
    {
     e = e.getCause();
    }
    //handle all uncaught exceptions here
    System.out.println("Got exception with message: " + e.getMessage());
   }
  });
  throw new RuntimeException("Gonna die!");
 }
}

Setting the default exception handler (line 3) will alter the default behavior for handling uncaught exceptions in the JVM. The implementation of the uncaughtException method (lines 6-10) will now determine what should be done. In this case just the message from the exception will be printed to standard out. A more real-world application of this might be to send a warning message to an operations team, or to take some other remedial action.

The caveat to this approach is that the default exception handler will only be used in cases where neither the offending Thread, or the ThreadGroup that it belongs to, have had their uncaught exception handlers set. If your application manages its own threads, then this will likely not be a problem for you. If your application runs in an application server, then you might well find that the application server has set these handlers already.

Sunday, April 15, 2012

Sample program to test SSL Connection with certicates

Keywords : ssl sample program, test program to test ssl, How can I check connectivity to ssl using java, test connectivity with ssl, Ssl connectivity testing programs.


I was looking for a sample program in java, using which I can test the connectivity to SSL.

Then I found http://www.herongyang.com/JDK/SSL-Socket-Server-Example-SslReverseEchoer.html

There are two programs

SslReverseEchoer.java (Running on server side)

/**
 * SslReverseEchoer.java
 * Copyright (c) 2005 by Dr. Herong Yang
 * http://www.herongyang.com/JDK/SSL-Socket-Server-Example-SslReverseEchoer.html
 */
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
public class SslReverseEchoer {
public static void main(String[] args) {
      // This is the keystore generated on the server.
      String ksName = "C:\\localhostCerts\\localhost.jks";
   // Keystore Password
      char ksPass[] = "welcome".toCharArray();
      // store Password
   char ctPass[] = "welcome".toCharArray();
      try {
         KeyStore ks = KeyStore.getInstance("JKS");
         ks.load(new FileInputStream(ksName), ksPass);
         KeyManagerFactory kmf = 
         KeyManagerFactory.getInstance("SunX509");
         kmf.init(ks, ctPass);
         SSLContext sc = SSLContext.getInstance("TLS");
         sc.init(kmf.getKeyManagers(), null, null);
         SSLServerSocketFactory ssf = sc.getServerSocketFactory();
         // This is the port number that we'll be giving in the client program.
         // Please do note it down.
         SSLServerSocket s 
            = (SSLServerSocket) ssf.createServerSocket(8888);
         printServerSocketInfo(s);
         SSLSocket c = (SSLSocket) s.accept();
         printSocketInfo(c);
         BufferedWriter w = new BufferedWriter(new OutputStreamWriter(
            c.getOutputStream()));
         BufferedReader r = new BufferedReader(new InputStreamReader(
            c.getInputStream()));
         String m = "Welcome to SSL Reverse Echo Server."+
            " Please type in some words.";
         w.write(m,0,m.length());
         w.newLine();
         w.flush();
         while ((m=r.readLine())!= null) {
            if (m.equals(".")) break;
            char[] a = m.toCharArray();
            int n = a.length;
            for (int i=0; i<n/2; i++) {
               char t = a[i];
               a[i] = a[n-1-i];
               a[n-i-1] = t;
            }
            w.write(a,0,n);
            w.newLine();
            w.flush();
         }
         w.close();
         r.close();
         c.close();
         s.close();
      } catch (Exception e) {
         System.err.println(e.toString());
      }
   }
   private static void printSocketInfo(SSLSocket s) {
      System.out.println("Socket class: "+s.getClass());
      System.out.println("   Remote address = "
         +s.getInetAddress().toString());
      System.out.println("   Remote port = "+s.getPort());
      System.out.println("   Local socket address = "
         +s.getLocalSocketAddress().toString());
      System.out.println("   Local address = "
         +s.getLocalAddress().toString());
      System.out.println("   Local port = "+s.getLocalPort());
      System.out.println("   Need client authentication = "
         +s.getNeedClientAuth());
      SSLSession ss = s.getSession();
      System.out.println("   Cipher suite = "+ss.getCipherSuite());
      System.out.println("   Protocol = "+ss.getProtocol());
   }
   private static void printServerSocketInfo(SSLServerSocket s) {
      System.out.println("Server socket class: "+s.getClass());
      System.out.println("   Socker address = "
         +s.getInetAddress().toString());
      System.out.println("   Socker port = "
         +s.getLocalPort());
      System.out.println("   Need client authentication = "
         +s.getNeedClientAuth());
      System.out.println("   Want client authentication = "
         +s.getWantClientAuth());
      System.out.println("   Use client mode = "
         +s.getUseClientMode());
   }
}
Of course, to run this program, you need to have the key store file, C:\localhostCerts\localhost.jks, ready. It contains a self-signed pair of private and public keys.
If you want to create certificates using keytool, you can follow first 2 steps of this

SslSocketClient.java (running on client side)

/**
 * SslSocketClient.java
 * Copyright (c) 2005 by Dr. Herong Yang
 * Before you execute this program, you have to prepare a jks file which will be trusted
 * by the client program. To make the trusted key store file you can use keytool -import command
 * You can read http://www.herongyang.com/JDK/SSL-Socket-Make-Self-Signed-Certificates-Trusted.html for more information.
 * This is also a good URL to study : http://docs.oracle.com/javaee/1.4/tutorial/doc/Security6.html
 */
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class SslSocketClient {
   public static void main(String[] args) {
      BufferedReader in = new BufferedReader(
         new InputStreamReader(System.in));
      PrintStream out = System.out;
      SSLSocketFactory f = 
         (SSLSocketFactory) SSLSocketFactory.getDefault();
      try {
   // This is the port number of the server on which server is listening
         SSLSocket c =
           (SSLSocket) f.createSocket("localhost", 8888);
         printSocketInfo(c);
         c.startHandshake();
         BufferedWriter w = new BufferedWriter(
            new OutputStreamWriter(c.getOutputStream()));
         BufferedReader r = new BufferedReader(
            new InputStreamReader(c.getInputStream()));
         String m = null;
         while ((m=r.readLine())!= null) {
            out.println(m);
            m = in.readLine();
            w.write(m,0,m.length());
            w.newLine();
            w.flush();
         }
         w.close();
         r.close();
         c.close();
      } catch (IOException e) {
         System.err.println(e.toString());
      }
   }
   private static void printSocketInfo(SSLSocket s) {
      System.out.println("Socket class: "+s.getClass());
      System.out.println("   Remote address = "
         +s.getInetAddress().toString());
      System.out.println("   Remote port = "+s.getPort());
      System.out.println("   Local socket address = "
         +s.getLocalSocketAddress().toString());
      System.out.println("   Local address = "
         +s.getLocalAddress().toString());
      System.out.println("   Local port = "+s.getLocalPort());
      System.out.println("   Need client authentication = "
         +s.getNeedClientAuth());
      SSLSession ss = s.getSession();
      System.out.println("   Cipher suite = "+ss.getCipherSuite());
      System.out.println("   Protocol = "+ss.getProtocol());
   }
}

How to test these programs

After you have created certificates on the server side, you can start the server as follows.
C:\>java SslReverseEchoer
Server socket class: class com.sun.net.ssl.internal.ssl.SSLServerSocketImpl
   Socker address = 0.0.0.0/0.0.0.0
   Socker port = 8888
   Need client authentication = false
   Want client authentication = false
   Use client mode = false
Socket class: class com.sun.net.ssl.internal.ssl.SSLSocketImpl
   Remote address = /127.0.0.1
   Remote port = 53298
   Local socket address = /127.0.0.1:8888
   Local address = /127.0.0.1
   Local port = 8888
   Need client authentication = false
   Cipher suite = SSL_RSA_WITH_RC4_128_MD5
   Protocol = TLSv1
While the server program is running, go to the client machine and execute the following

C:\>java SslSocketClient
Socket class: class com.sun.net.ssl.internal.ssl.SSLSocketImpl
   Remote address = localhost/127.0.0.1
   Remote port = 8888
   Local socket address = /127.0.0.1:52814
   Local address = /127.0.0.1
   Local port = 52814
   Need client authentication = false
   Cipher suite = SSL_NULL_WITH_NULL_NULL
   Protocol = NONE
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHands
hakeException: sun.security.validator.ValidatorException: PKIX path building fai
led: sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target

// Please note that the above command will terminate the server process. You need to restart it.
// In the above command, we didn't provide the certiciates, so as expected, it should not be 
// able to connect.


// Before running the following command, you have to import the server side certificate
// into cacerts.jks using the keytool -import command.

C:\>java -Djavax.net.ssl.trustStore=localhostCerts\cacerts.jks SslSocketClient
Socket class: class com.sun.net.ssl.internal.ssl.SSLSocketImpl
   Remote address = localhost/127.0.0.1
   Remote port = 8888
   Local socket address = /127.0.0.1:52816
   Local address = /127.0.0.1
   Local port = 52816
   Need client authentication = false
   Cipher suite = SSL_RSA_WITH_RC4_128_MD5
   Protocol = TLSv1
Welcome to SSL Reverse Echo Server. Please type in some words.
How are you?
?uoy era woH

How to make my browser trust my server certificate?

Hi Guys,

I was exploring the SSL thing, and wanted to know what are the steps involved in making my browser trust the server certificate that server is sending.

First of all you need to generate a keystore (This needs to be done on server side).

C:\localhostCerts>keytool -genkey -alias server-alias -keyalg RSA -keypass welcome -storepass welcome -keystore localhost.jks
What is your first and last name?
  [Unknown]:  localhost
What is the name of your organizational unit?
  [Unknown]:  NSEL
What is the name of your organization?
  [Unknown]:  NSEL
What is the name of your City or Locality?
  [Unknown]:  NOIDA
What is the name of your State or Province?
  [Unknown]:  UP
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=localhost, OU=NSEL, O=NSEL, L=NOIDA, ST=UP, C=IN correct?
  [no]:  yes


C:\localhostCerts>dir
 Volume in drive C has no label.
 Volume Serial Number is CE67-DC0D

 Directory of C:\localhostCerts

15-Apr-2012  01:10 PM    <DIR>          .
15-Apr-2012  01:10 PM    <DIR>          ..
15-Apr-2012  01:10 PM             1,338 localhost.jks
               1 File(s)          1,338 bytes
               2 Dir(s)  343,529,140,224 bytes free

The above command has generated a keystore (on the server side)

Now convert this into a server certificate (and send it to client side)

C:\localhostCerts>keytool -export -alias server-alias -storepass welcome -file server.cer -keystore localhost.jks
Certificate stored in file <server.cer>

C:\localhostCerts>dir
 Volume in drive C has no label.
 Volume Serial Number is CE67-DC0D

 Directory of C:\localhostCerts

15-Apr-2012  01:11 PM    <DIR>          .
15-Apr-2012  01:11 PM    <DIR>          ..
15-Apr-2012  01:10 PM             1,338 localhost.jks
15-Apr-2012  01:11 PM               563 server.cer
               2 File(s)          1,901 bytes
               2 Dir(s)  343,560,626,176 bytes free

Make the changes in server.xml

Make changes as given on http://javakafunda.blogspot.in/2012/04/how-to-configure-tomcat-to-support-ssl.html in step 2.
(Take care of the file name)

Saved the server.xml on server and restart Tomcat, access to https://localhost:8443/

You'll see a page as given below


As you see the google chrome doesn't trusts the certificate that was provided by the server.

Check untrusted certificate on client side

If you open server.cer (provided by the server) by double clicking, you can see the message as given below

This CA Root certificate is not trusted. To enable trust, install this certificate in the Trusted Root Certification Authorities Store

How to add this certificate to Trusted Root Certification Authorities on Google Chrome??

  1. Tools -> Settings
  2. Click on Show advanced settings at the bottom of the page
  3. Click on Manage Certificates
  4. Click on Trusted Root Certification Authorities tab
  5. Click on import
  6. Select server.cer from your machine
  7. Next, Next, and Finish
  8. You should get a import successful message

Again open the server.cer, and now you should see the certificate as follows.


if you open https://localhost:8443/ in IE or google chrome you will NOT see the warning and in the address bar, you'll notice the lock.





Saturday, April 14, 2012

Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object

I was getting the following error in the logs of the tomcat, when I try to start the tomcat server.

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

Things I tried but didn't work
=========================
1) I used class finder to find that which jar contains this class java.lang.Object, and it was rt.jar.
I added rt.jar in the classpath. But of no use.
2) I made a Environment variable CATALINA_HOME, JAVA_HOME, but didn't help.
3) I tried rebooting the machine every time, after I set the paths specified in step 2.
4) Uninstalling and re-installing the tomcat didn't help.


ROOT CAUSE AND SOLUTION:
=========================
During installation of tomcat, the default jre directory that was coming on the installation screens of tomcat didn't had rt.jar
I realized this when I checked the jre folder.

Then I decided to uninstall and re-install tomcat and while re-installation I took care while specifying the jre folder. And the new jre folder had rt.jar

This solution made it work. :)

I m happy :)


How to configure Tomcat to support SSL or https

Thanks to http://www.mkyong.com/tomcat/how-to-configure-tomcat-to-support-ssl-or-https/


1. Generate Keystore

First, uses "keytool" command to create a self-signed certificate. During the keystore creation process, you need to assign a password and fill in the certificate’s detail.

$Tomcat\bin>keytool -genkey -alias mkyong -keyalg RSA -keystore c:\mkyongkeystore
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  yong mook kim
What is the name of your organizational unit?
  //omitted to save space
  [no]:  yes
 
Enter key password for <mkyong>
        (RETURN if same as keystore password):
Re-enter new password:
 
$Tomcat\bin>
Here, you just created a certificate named "mkyongkeystore", which locate at "c:\".

Check your certificate details

Certificate Details
You can use same "keytool" command to list the existing certificate's detail
$Tomcat\bin>keytool -list -keystore c:\mkyongkeystore
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

mkyong, 14 Disember 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): C8:DD:A1:AF:9F:55:A0:7F:6E:98:10:DE:8C:63:1B:A5

$Tomcat\bin>

2. Connector in server.xml

Next, locate your Tomcat’s server configuration file at $Tomcat\conf\server.xml, modify it by adding a connector element to support for SSL or https connection.

File : $Tomcat\conf\server.xml
//...
 <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the 
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
 
 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 
        keystoreFile="c:\mkyongkeystore"
        keystorePass="password" />
  //...

Saved it and restart Tomcat, access to https://localhost:8443/


In this example, we are using Google Chrome to access the Tomcat configured SSL site, and you may notice a crossed icon appear before the https protocol :), this is caused by the self-signed certificate and Google chrome just do not trust it.

In production environment, you should consider buy a signed certificate from trusted SSL service provider like verisign or sign it with your own CA server



Wednesday, April 4, 2012

How to create dynamic trigger in Oracle?

Thanks to http://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:59412348055

Problem:

I'm trying to create a generic before update trigger
which will compare all :old.column_values to all
:new.column_values. If the column_values are different, then I
would like to log the change to a separate table. When I try to
compile :old., Oracle return an
"(1):PLS-00049: bad bind variable 'NEW." Can you recommend a
dynamic way to accomplish this? Thanks in advance.

Solution:

:new and :old are like bind variables to the trigger, they are not 'regular' variables.
you cannot dynamically access them, only 'statically'.

I suggest you consider writing a stored procedure or sql*plus script to write a trigger
that statically references the new/old values. For example, if you wanted to save in a
table the time of update, who updated, table updated, column modified and new/old values,
you could code a sql*plus script like:

--------------------------------------------------------------------
create table audit_tbl
(    timestamp    date,
    who            varchar2(30),
    tname        varchar2(30),
    cname        varchar2(30),
    old            varchar2(2000),
    new            varchar2(2000)
)
/

create or replace package audit_pkg
as
    procedure check_val( l_tname in varchar2, 
                             l_cname in varchar2, 
                 l_new in varchar2, 
                             l_old in varchar2 );

    procedure check_val( l_tname in varchar2, 
                             l_cname in varchar2, 
                     l_new in date, 
                             l_old in date );

    procedure check_val( l_tname in varchar2, 
                             l_cname in varchar2, 
                 l_new in number, 
                             l_old in number );
end;
/


create or replace package body audit_pkg
as

procedure check_val( l_tname in varchar2,
                     l_cname in varchar2,
             l_new in varchar2,
                     l_old in varchar2 )
is
begin
    if ( l_new <> l_old or
         (l_new is null and l_old is not NULL) or
         (l_new is not null and l_old is NULL) )
    then
        insert into audit_tbl values
        ( sysdate, user, upper(l_tname), upper(l_cname),
                             l_old, l_new );
    end if;
end;

procedure check_val( l_tname in varchar2, l_cname in varchar2,
             l_new in date, l_old in date )
is
begin
    if ( l_new <> l_old or
         (l_new is null and l_old is not NULL) or
         (l_new is not null and l_old is NULL) )
    then
        insert into audit_tbl values
        ( sysdate, user, upper(l_tname), upper(l_cname),
          to_char( l_old, 'dd-mon-yyyy hh24:mi:ss' ),
          to_char( l_new, 'dd-mon-yyyy hh23:mi:ss' ) );
    end if;
end;

procedure check_val( l_tname in varchar2, l_cname in varchar2,
             l_new in number, l_old in number )
is
begin
    if ( l_new <> l_old or
         (l_new is null and l_old is not NULL) or
         (l_new is not null and l_old is NULL) )
    then
        insert into audit_tbl values
        ( sysdate, user, upper(l_tname), upper(l_cname),
                                 l_old, l_new );
    end if;
end;

end audit_pkg;
/


set serveroutput on
set feedback off
set verify off
set embedded on
set heading off
spool tmp.sql

prompt create or replace trigger aud#&1
prompt after update on &1
prompt for each row
prompt begin

select '    audit_pkg.check_val( ''&1'', ''' || column_name ||
          ''', ' || ':new.' || column_name || ', :old.' || 
             column_name || ');'
from user_tab_columns where table_name = upper('&1')
/
prompt end;;
prompt /

spool off
set feedback on
set embedded off
set heading on
set verify on

@tmp
-------------

That will build the generic table and package plus generate a trigger that would look 
like:

SQL> @thatscript dept


create or replace trigger aud#dept
after update on dept
for each row
begin
    audit_pkg.check_val( 'dept', 'DEPTNO', :new.DEPTNO, :old.DEPTNO);
    audit_pkg.check_val( 'dept', 'DNAME', :new.DNAME, :old.DNAME);
    audit_pkg.check_val( 'dept', 'LOC', :new.LOC, :old.LOC);
end;
/