Tuesday, August 21, 2012

Problem using c:set of jstl

The problem was that i was not able to set the value of a variable defined in a scriptlet.
<c:set var="test" value="yogesh"/>

Root cause: The tag lib i was using was perhaps of an older version.

Older version:
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

Newer version:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/jsp/core" %>

Please do post more information if you have more knowledge about this problem.

Sunday, May 27, 2012

How to put time restriction on web service function call?

Add the following 2 imports

import com.sun.xml.ws.developer.JAXWSProperties;
import javax.xml.ws.BindingProvider;

Just add this before the function call where you call web service.


((BindingProvider)port).getRequestContext()
                          .put(JAXWSProperties.CONNECT_TIMEOUT, 100);
        ((BindingProvider)port).getRequestContext()
                           .put(JAXWSProperties.REQUEST_TIMEOUT, 100);

Saturday, May 26, 2012

How to put a time restriction on a method in java?

I have a specific requirement where in I am calling a method and I want to get the response within a specific duration.
For example, I am trying to fetch the contents of a web-page.

If within 3 seconds, I get the response, its good, otherwise, I want to give a message to the user that internet is too slow.

Now, how do I do this?

You could make use of the ExecutorService and its timeout facilities. The idea is to execute the method you want to call in a different thread, and let the ExecutorService cancel it after a specific time. Here is a simple example, using two fixed threads. You'd have to adapt this to your needs.

Make a class MyTask implements Callable<Void>


package testapp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class MyTask implements Callable<Void> {

    private String name;
    private long sleepTime;

    public MyTask(String name, long sleepTime) {
        this.name = name;
        this.sleepTime = sleepTime;
    }

    public Void call() throws Exception {
        System.out.println("Starting task " + name);
        Thread.sleep(sleepTime);
        System.out.println("Finished task " + name);
        return null;
    }
}

Use this as is done here

public class ExecutorServiceTest {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Collection<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
        tasks.add(new MyTask("Task1", 10000));
        tasks.add(new MyTask("Task2", 2000));
        System.out.println(new java.util.Date());
        List<Future<Void>> taskFutures = service.invokeAll(tasks, 2L, TimeUnit.SECONDS);
        for (Future<Void> future : taskFutures) {
            System.out.println("Done: " + future.isDone());
            System.out.println("Cancelled: " + future.isCancelled());
        }
        System.out.println(new java.util.Date());

        System.out.println("END");

    }
}

Sunday, May 20, 2012

How to upload file using struts and hiberate?

How to upload file using struts and hibernate?

I spent 5-6 hours figuring out how can I upload a file into Blob in a database. So I decided to write a short article.

Add enctype="multipart/form-data" in the form tag (in JSP)

<html:form method="POST" action="/solution.do" enctype="multipart/form-data">


Add 2 fields in ActionForm, one which is populated via struts framework.
Second one which is read by hibernate i.e. uploadedBlob

// This is filled by the code written in Action Class.
    // This has to be done manually and is not done automatically.
    private Blob uploadedBlob;
    public Blob getUploadedBlob() {
        return uploadedBlob;
    }

    public void setUploadedBlob(Blob uploadedba) {
        this.uploadedBlob = uploadedba;
    }
    
    // This is the actual FormFile which gets populated into the ActionForm
    // by struts framework.
    private FormFile uploadedfile;
    public FormFile getUploadedfile() {
        return uploadedfile;
    }

    public void setUploadedfile(FormFile uploadedfile) {
        this.uploadedfile = uploadedfile;
    } 

Add the following in formbean.hbm.xml

<property column="uploadedfile" name="uploadedBlob" type="blob"/>

In Action Class, convert FormFile to Blob and set it in FormBean (while saving)

// Convert FormFile to a byte Array
        byte[] byteArray=formbean.getUploadedfile().getFileData();
        // Convert this byteArray to a blob
        Blob myblob=Hibernate.createBlob(byteArray);
        formbean.setUploadedBlob(myblob);

For saving this formbean to database use
private boolean saveOrUpdate(SolutionFormBean formbean) 
{
        Session session = null;

        //Transaction object
        // Nothing happens without transaction in hibernate.
        Transaction transaction = null;
        try {
            // This step will read hibernate.cfg.xml
            // and prepare hibernate for use
            SessionFactory sessionFactory = new Configuration()
                                             .configure().buildSessionFactory();
            session = sessionFactory.openSession();
            // Using a transaction is mandatory.
            transaction = session.beginTransaction();
            session.saveOrUpdate(formbean);
            // Commit it
            transaction.commit();
            System.out.println("Done");
            return true;
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        } finally {
            // Actual row insertion will happen at this step
            if(session!=null)
            {
                session.flush();
                session.close();
            }
            return true;
        }
    }

While reading Blob from database, you would have to do the reverse, i.e.
convert Blob to byteArray and write to ServletOutputStream

Blob dbBlob = dbBean.getUploadedBlob();
        int bloblength=(int)dbBlob.length();
        byte[] tempByte = dbBlob.getBytes(1, bloblength);
        // Now we have converted blob to byte array.
        ServletOutputStream out = response.getOutputStream();
        // For reading more about this header do check out the following link
        // http://javakafunda.blogspot.com/2011/10/forcing-saveas-using-http-header.html
        response.setHeader("Content-Disposition", "attachment; filename="
                                                       +formbean.getFilename());
        out.write(tempByte);
        out.flush();
        out.close();

Sunday, May 6, 2012

How to configure end point WSDL URL at runtime?

Configure WSDL URL at run-time :

http://biemond.blogspot.in/2009/04/changing-wsdl-url-endpoint-in-jax-ws.html

Saturday, May 5, 2012

A perfect example to understand wait and notify in threads

class myWriterThread implements Runnable
{
    private mClass userInput;
    public myWriterThread(mClass userInput) {
        this.userInput = userInput;
    }
    public void run() {
        userInput.waitForInput();
    }
}
class myReaderThread implements Runnable
{
    private mClass userInput;

    public myReaderThread(mClass userInput) {
        this.userInput = userInput;
    }


    public void run() {
        userInput.ReadInput();
    }
}
class mClass 
{
    public synchronized void waitForInput() 
    {
        while(!userInput.equals("Y"))
        {
            try
            {
                System.out.println("Going to wait");
                wait();
            }
            catch(InterruptedException e)
            {
                System.out.println(e.getMessage());
                System.out.println("Got interrupted");
            }
        }
        System.out.println("Wait for Input notified");
    }
    public synchronized void ReadInput()
    {
       try
        {
             userInput="Y";
             System.out.println("Reader has set userInput to Y");
             notify();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        System.out.println("I am exiting ReadInput");
    }        
    private String userInput;

    public mClass(String userInput) {
        this.userInput = userInput;
    }
}
public class CustomClass
{
    public static void main(String args[])
    {
        mClass m = new mClass("N");
        Thread t1 = new Thread(new myWriterThread(m));
        Thread t3 = new Thread(new myWriterThread(m));
        t3.start();
        t1.start();
        Thread t2 = new Thread(new myReaderThread(m));
        t2.start();
    }
}

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

Thursday, March 8, 2012

Formatting your HTML Document using Notepad++ !!

Formatting your HTML Document !!

I always wished I had a tool that could format my ugly looking HTML document. The feature is provided by Notepad++

The version of Notepad++ that has this feature


How to format HTML using Notepad++


Wednesday, March 7, 2012

Reading CSV made easy

How to use CSV Reader

import util.CSVReader;
/**
 *
 * @author : Yogesh Gandhi
 * @email : yogesh249@gmail.com
 */
public class Main {
    public static void main(String[] args)throws Exception  {
            CSVReader csvReader = new CSVReader("D:\\yogesh.csv");
            // As CSVReader implements Iterable
            // So, we can use it in the enhanced for loop 
            // as follows. Any class that implements Iterable
            // can follow a colon in the enhanced for loop.
            for(HashMap mp : csvReader)
            {
                System.out.println(mp.get("mobile"));
            }
    }
}

CSV Reader

/**
 *
 * @author : Yogesh Gandhi
 * @email : yogesh249@gmail.com
 *
 */

package util;

import java.util.*;
import java.io.*;

public class CSVReader implements Iterable<HashMap<String, String>> {

    private BufferedReader _reader;
    private String[] headers;
    public CSVReader(String filePath) throws Exception {
        // Initialize the _reader
        _reader = new BufferedReader(new FileReader(filePath));
        // Initialize the headers.
        String headerLine = _reader.readLine();
        headers = headerLine.split(",");
        if(headers==null) throw new Exception("No headers present in the file");
    }

    public void Close() {
        try {
            _reader.close();
        } catch (Exception ex) {
        }
    }

    @Override
    public Iterator<HashMap<String, String>> iterator() {
        return new CSVIterator();
    }

    private class CSVIterator implements Iterator<HashMap<String, String>> {
        private HashMap<String, String> _currentMap;
        @Override
        public boolean hasNext() {
            try {
                // Read the next line from the CSV.
                String currentLineString = _reader.readLine();
                if(currentLineString!=null)
                {
                    // Populate _currentMap with the values.
                    String[] elements=currentLineString.split(",");
                    _currentMap = new HashMap<String, String>();
                    for(int h=0; h<headers.length; h++)
                    {
                        String key=headers[h];
                        String value = elements[h];
                        _currentMap.put(key, value);
                    }
                }
                else
                {
                    return false;
                }
            } catch (Exception ex) {
                _currentMap = null;
                ex.printStackTrace();
            }

            return _currentMap != null;
        }
        @Override
        public void remove() {
        }

        @Override
        public HashMap<String, String> next() {
            return _currentMap;
        }
    }
}

Tuesday, February 21, 2012

How to invoke a web service using JDeveloper (given a WSDL)

How to call a web service from Jdeveloper (provided WSDL file or URL)

Create a New Empty Project















Thursday, February 9, 2012

The prefix "jaxb" for element "jaxb:globalBindings" is not bound.

I'm using xjc to compile XML Schema into JAXB objects and the
compiling is fine unless I try to define jaxb bindings. For instance,
if I try adding this code in the schema:

<xs:annotation>
<xs:appinfo>
<jaxb:globalBindings generateIsSetMethod="true">
bindingStyle="modelGroupBinding"
choiceContentProperty="true" >

<xjc:serializable uid="12343"/>
<jaxb:javaType name="short"
xmlType="xs:long"
printMethod="javax.xml.bind.DatatypeConverter.printShort"
parseMethod="javax.xml.bind.DatatypeConverter.parseShort"/>
</jaxb:globalBindings>
</xs:appinfo>
</xs:annotation>

xjc complains with:
[ERROR] The prefix "jaxb" for element "jaxb:globalBindings" is not
bound.

SOLUTION
========

Missing namespace declaration. There should be something like this:
xmlns:jaxb="URI"
Just look for the other namespace definitions (i.e. xmlns:s) and
add the above attribute to the end.

Source : http://www.velocityreviews.com/forums/t137983-problem-in-xjc-with-recognizing-jaxb-prefix.html

xsd:date maps to java.util.Calendar

My schema has an element of type xs:date, which jaxb maps to a java.util.Calendar. If I create a Calendar object with Calendar.getInstance(), it marshalls to "2003-11-24-05:00".

How can I get it to marshall to just "2003-11-24"?

SOLUTION:
Write a converter class (see MyConverter below) and added an annotation/appinfo to the xml schema, also shown below.


public class MyConverter
{
    static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    static public String printCalendar(Calendar c)
    {
        return df.format(c.getTime());
    }

    static public Calendar parseCalendar(String c) throws ParseException
    {
        Date d = df.parse(c);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        return cal; 
    }
}

<xsd:schema ...>
<xsd:annotation>
<xsd:appinfo>
<jaxb:globalBindings 
<jaxb:javaType name="java.util.Calendar" xmlType="xsd:date"
printMethod="MyConverter.printCalendar"
parseMethod="MyConverter.parseCalendar"
/>
</jaxb:globalBindings>
</xsd:appinfo>
</xsd:annotation>
...
</xsd:schema>

Source : https://forums.oracle.com/forums/thread.jspa?threadID=1624090

Sunday, February 5, 2012

What's the difference between display: none and visibility: hidden?

Question: What's the difference between display: none and visibility: hidden?
The display: none and visibility: hidden CSS properties appear to be the same thing, but they aren't.

Answer:
These two style properties do two different things.

visibility: hidden hides the element, but it still takes up space in the layout.

display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code.

You can see the effect of these style properties on this page. I created three identical swatches of code, and then set the display and visibility properties on two so you can see how they look.

Source: http://webdesign.about.com/od/css/f/blfaqhidden.htm

Sunday, January 22, 2012

Removing scriptlets from a JSP

I have read on internet that it is a very bad idea to use scriplets in a JSP.
Even if you need to use scriplets in a JSP, that is most likely because you are doing something in JSP, which should be better handled in a Action class.

So, I am trying to gather few tips, how to convert an existing JSP with scriplet to a JSP without scriplet.

Guys please comment and add more, i'll keep on adding it to the main post :)
There could be multiple ways of doing the same thing, you guys can add your knowledge to this, so that we can come up with a post, that we can re-use.

Most of the help has been taken from http://www.roseindia.net/jstl/jstlcoretags.shtml

You might like to read a discussion on WHY to avoid scriplets


Scriplet code Without scriplet code
<%=request.getContextPath()%> ${pageContext.request.contextPath}
<%= request.getRequestURI().contains("/events/")%> ${fn:contains(pageContext.request.requestURI, '/events/')}
<%= request.getRequestURI().contains("/events/") ? "class='selected'" : ""%> ${fn:contains(pageContext.request.requestURI, '/events/')? 'class="selected"' : ''}
<% if(request.getRequestURI().contains("/events/")) { %>

...

<%}%>
<c:if test="${fn:contains(pageContext.request.requestURI, '/events/')}">
...
</c:if>
<% String s = request.getParameter("text1"); %> <c:set var="s" value="${param.text1}" >
<% out.println(s);%> <c:out value="${s}" />
<% if(s.equals("sam"))
{
out.println("Good Morning...SAM!");
}
%>
<c:if test="${s eq 'sam'}">
<c:out value="Good Morning...SAM!" />
</c:if>

<%
switch(s)
{
case 1: out.println("Sunday");
case 2: out.println("Monday");
...
}
%>

<c:choose>
<c:when test="${s==1}">Sunday </c:when>
<c:when test="${s==2}">Monday</c:when>
<c:when test="${s==3}">Tuesday</c:when>
<c:when test="${s==4}">Wednesday</c:when>
<c:when test="${s==5}">Thursday</c:when>

<c:otherwise>
select between 1 & 5
</c:otherwise>
</c:choose>

<%
HttpSession session = request.getSession();
out.println(

(Questions)

session.getAttribute("Questions").getQuestionPaperID());

%>
<c:out value="${sessionScope.Questions.questionPaperID}" />

<%request.getSession().getAttribute("my_var") %>

Can be accessed using JSTL with the sessionScope keyword. To access my_var, call sessionScope.myvar

Remember to use sessionScope

<c:out value="${sessionScope.my_var}"/>

To make it easier, this link would help you understand the JSTL tags better...

Thursday, January 12, 2012

Basic fundas about using float or double

Think again if you are going to use float or double for amount/currency field.

Reason behind this is

Floats have a fixed number of total bits of precision, which must be shared among the integer and fractional parts. If you use more of those bits to store a larger integer portion (123456 vs. just 12), that leaves fewer for the fractional portion (.4 vs. .45678).

Also, you should be aware that since float and double are base-2 formats, rather than base-10, many values that can be represented with a small, finite number of digits in base-10 cannot be stored in a double or float. For instance, it is impossible to store exactly 1/10 (0.1) in a double or float, just as it's impossible to store 1/3 (0.333...) exactly in a finite number of digits in base-10.

Demonstration code:

    public static void main(String args[]) {  
        double d = 1997500.43;  
        String s = "1997500.43";  
        float f = (float) d;  
        System.out.println(f);//1997500.4  
  
        float f3 = Float.parseFloat(s);  
        System.out.println(f3);//1997500.4  
  
        float f4 = Double.valueOf(s).floatValue();  
        System.out.println(f4);//1997500.4  
  
        float f5 = new Double(s).floatValue();  
        System.out.println(f5);//1997500.4  
  
        float xFloat;  
        Double x = new Double("63.8644951");  
        xFloat = x.floatValue();  
        System.out.println(xFloat);// 63.864494  
  
        float xFloat2;  
        Double x2 = new Double("3333263.8644951");  
        xFloat2 = x2.floatValue();  
        System.out.println(xFloat2);// 3333263.8  
}  

Detailed information about floats and doubles is available at : http://www.coderanch.com/t/564234/java/java/Precision-loss-String-Float-double

Best Practices while writing Java code

Usually many of us write the java code in a try-catch block as follows

try
{
       // some code here
}
catch(Exception e)
{
    // log exception here
}

Better way to do it is

try
{
       // some code here
}
catch(Exception e)
{
    // log exception here
}
catch(Throwable ex)
{
     // One must add throwable clause always
     // because in case of some error also, you can
     // log it and see, what error has occured.
}


If you do not add Throwable clause, and in production, some error occurs, Then nothing will be logged in your logs, you may end up breaking your head, why the hell it is not working.

Make it a habit to use try-catch-Throwable in place of try-catch-Exception

Classes not being generated in WEB-INF/classes folder

Posting this on behalf of Vaibhav Garg..

The settings in the Eclipse were perfect to store the output in the output folder as WEB-INF/classes folder. But, still the classes were not being generated in this folder when the code was built. 

Reason:

There were a couple of dependent projects included in the build path. And, there were errors in those projects. Due to this reason, the project was not getting built. And, the error list was huge around 2500 errors in the entire workspace. So, it was difficult to get the exact reason whether the project has some errors or not.

Once the errors in dependent projects were resolved, it got built successfully and the class files got generated in the WEB-INF/classes folder.

Monday, January 2, 2012

How to check which application is using a particular port?

Source : http://oolacola.blogspot.com/2009/04/how-to-find-out-which-application-is.html

Let's say that we are looking for port 80 -- IIS, Apache and other web servers listen in port 80, so when you are having problems starting Apache, this technique will be useful. Here is the command.

C:\>netstat -aon | findstr 80

-a means list all active connections and their ports. -o means include their process IDs. -n means display the port numbers numerically.


The pipe symbol ( | ) means, that instead of the result of netstat being displayed on the screen, feed it's result to the findstr process -- we are looking specifically for the line which has 0.0:80 -- you actually don't need findstr, but I don't want to scroll down and hunt down manually which app is using port 80. You might see something like this.

TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 560

Aha! now we know that process 560 is using port 80 (that last column right there, is the process ID), you could press CTRL-ALT-DEL now to show the process window, and manually look up which app has the process ID 560, or you could enter ..

C:\>tasklist | findstr 560