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();
    }
}