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

Configure logging of XML on client side using Netbeans

How to convert SOAPMessage to a String

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)

SslSocketClient.java (running on client side)

How to test these programs

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).

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

Make the changes in server.xml

Check untrusted certificate on client side

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


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

Check your certificate details

2. Connector in server.xml

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



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;
/