Thursday, July 19, 2012

facebook integration with java useful links

http://faheemsohail.com/2012/03/integrating-java-spring-mvc-and-facebook-part-1/
http://cagrikilit.com/2011/01/06/restfb-an-easy-way-to-integrate-with-facebook/
http://www.intelligrape.com/blog/2010/11/14/integrate-java-application-with-facebook-using-graph-api/

Wednesday, July 18, 2012

XSLT useful links


http://binodsuman.blogspot.in/2009/04/xslt-tutorial-using-java-and-xml.html

http://www.vogella.com/articles/XSLT/article.html

Tuesday, July 17, 2012

unix/linux commands for java developers

http://javarevisited.blogspot.in/2011/05/unix-command-interview-questions.html
http://www.fromdev.com/2008/12/debugging-java-on-unixlinux-my-favorite.html
http://www.cs.carleton.edu/generic-course-info/unix.html

Wednesday, July 11, 2012

Java Interview Questions

Q1.  Explain two main differences in List and Set.


                Q2:  Which Collection permits null values, HashMap or Hashtable.
                Answer: 

                Q3: What is the super class of java.lang.Exception
                Answer: 

                Q4: How to achieve Runtime Polymorphism in Java
Answer:
Q5: When you call Thread.start() method on the thread object, which state the thread will go in first.
Answer:

Q6: Is JVM platform independent?
Answer:
Q7: What are the methods of Object class
Answer: 

Q8: How do you prevent a member variable in any object from getting serialized?
Answer:
Q9: Can two threads execute two different Synchronized methods of an object at the same time?
Answer:

Q10: Can you add objects to an ArrayList which has been declared as final.
Answer:
Q11: Can you call one constructor from another?
Answer:
Q12: Inheritance in java expresses which relationship?
Answer:
Q13: Can you extend from two classes?
Answer:
Q14: What is anonymous class?
Answer:
Q15: Can there be an abstract class with none of its methods declared as abstract?
Answer:
Q16: Can abstract class have constructor?
Answer:
Q17: Are static variables - instance variables or class variables?
Answer:
Q17: When you invoke run() method on instance of Thread class, will it start thread?
Answer:
Q18: The command to eliminate a table from a database is:
Answer:
Q19: The result of a SQL SELECT statement is a(n)
Answer:
Q20: Which of the following is valid SQL for an Index?
Answer:

Declaring ArrayList ae final in java

public
System.
}
}
o/p:2
 we can add the objects to the final declared ArrayList.

if We want to prevent it we need to  use Collections.unmodifiableList()

public
System.
}
}
class SampleTest {public static final List<String> list =Collections.unmodifiableList(new ArrayList<String>());public static void main(String[] args){list.add("ABC");list.add("BCD");out.println(list.size());
class SampleTest {public static final ArrayList<String> list =new ArrayList<String>() ;public static void main(String[] args){list.add("ABC");list.add("BCD");out.println(list.size());
o/p :java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(
at com.jnet.test.SampleTest.main(

Now we are not able to modify the List
Collections.java:1018)SampleTest.java:11)

 

Exception in thread "main"

Exceptions(checked,Unchecked) in java

Java has a powerful concept for exception and error handling. An exception is an error that occurs at runtime. It is either generated by the Java Virtual Machine (VM) in response to an unexpected condition or it is generated by your code as a result of executing a throw statement.
Understanding Exceptions
Exceptions generated from runtime are called unchecked exceptions, since it is not possible for the compiler to determine that your code will handle the exception. Exception classes that descend from RuntimeException and Error classes are unchecked exceptions. Examples for RuntimeException are illegal cast operation, inappropriate use of a null pointer, referencing an out of bounds array element. Error exception classes signal critical problems that typically cannot be handled by your application. Examples are out of memory error, stack overflow, failure of the Java VM.
Thrown exceptions are referred to as checked exceptions. The compiler will confirm at compile time that the method includes code that might throw an exception. Moreover the compiler requires the code that calls such a method to include this call within a try block, and provide an appropriate catch block to catch the exception.
java.lang.Object
   |
   +--java.lang.Throwable
         |
         +--java.lang.Exception
         |     |
         |     +--java.lang.ClassNotFoundException
         |     |
         |     +--java.io.IOException
         |     |     |
         |     |     +--java.io.FileNotFoundException
         |     |
         |     +--java.lang.RuntimeException
         |           |
         |           +--java.lang.NullPointerException
         |           |
         |           +--java.lang.IndexOutOfBoundsException
         |                 |
         |                 +--java.lang.ArrayIndexOutOfBoundsException
         |
         +--java.lang.Error
               |
               +--java.lang.VirtualMachineError
                     |
                     +--java.lang.OutOfMemoryError
When an (either checked or unchecked) exception is thrown, execution will attempt to immediately branch to the first catch block whose associated exception class matches the class or a superclass of the thrown exception. If the exception does not occur within a try block or the thrown exception is not caught in a matching catch block, execution of the method immediately terminates and control returns to the invoker of the method, where this process is repeated. The result is that the exception chain is escalated until a matching catch block is found. If not, the thread containing the thrown exception is terminated.
First Example
The following Demo1 class demonstrates the behaviour of exceptions and applications.
import java.io.*;
class Demo1 {
  public static FileInputStream f1(String fileName)
    throws FileNotFoundException
  {
    FileInputStream fis = new FileInputStream(fileName);
    System.out.println("f1: File input stream created");
    return fis;
  }
  public static FileInputStream f2(String fileName)
  {
    FileInputStream fis = null;
    try
    {
      fis = new FileInputStream(fileName);
    }
    catch (FileNotFoundException ex)
    {
      System.out.println("f2: Oops, FileNotFoundException caught");
    }
    finally
    {
      System.out.println("f2: finally block");
    }
    System.out.println("f2: Returning from f2");
    return fis;
  }
  public static void main(String args[])
  {
    FileInputStream fis1 = null;
    FileInputStream fis2 = null;
    String fileName = "foo.bar";
    // String fileName = null;
    System.out.println(  "main: Starting " + Demo1.class.getName()
                       + " with file name = " + fileName);
    // get file input stream 1
    try {
      fis1 = f1(fileName);
    }
    catch (FileNotFoundException ex)
    {
      System.out.println("main: Oops, FileNotFoundException caught");
    }
    catch (Exception ex)
    {
      System.out.println("main: Oops, genreal exception caught");
    }
    // get file input stream 2
    fis2 = f2(fileName);
    System.out.println("main: " + Demo1.class.getName() + " ended");
  }
}
Compile and run the Demo1 class will generate output as follows (assuming that the file foo.bar does not exist):
main: Starting Demo1 with file name = foo.bar
main: Oops, FileNotFoundException caught
f2: Oops, FileNotFoundException caught
f2: finally block
f2: Returning from f2
main: Demo1 ended
The example program tries to create two file input streams. Therefore two methods f1 and f2 are implemented. First, the main program calls f1 method. Because the constructor of the FileInputStream throws a FileNotFoundException the method f1 must be defined with the throws FileNotFoundException in the method definition. The thrown exception is not handled in the method but forwarded to the invoker. Note, that the system output before the return statement is never executed.
So the invoker, in our example the main program, must catch this exception. The method f1 is called in a try block. The following catch blocks catch either a FileNotFoundException or a general Exception. In our example, the exception is caught in the first catch block and the system output is generated. Since the exception in f1 is caught and handled, the execution of the program is not terminated.
Second, the example program creates another FileInputStream invoking the f2 method. This method catches the FileNotFoundException, so this exception must not be forwarded to the invoker. The try ... catch statement is followed by a finally block. This block is always executed, regardless whether or not an exception occurs within the try block. This generates the system output in our example. Again, the exception is caught and the program executes, this generates the system output in f2 and main.
This was a straight forward example with caught exceptions. What happens with uncaught exceptions? Change the fileName assignment in the main method: Comment out the first assignment and activate the second String fileName = null; then compile and execute Demo1 again. The generated output is:
main: Starting Demo1 with file name = null
main: Oops, genreal exception caught
f2: finally block
java.lang.NullPointerException
java.io.FileInputStream Demo1.f2(java.lang.String)
void Demo1.main(java.lang.String[])
Exception in thread main
This time, we try to create two FileInputStream objects using null instead of a file name. Invoking f1 will generate a NullPointerException which is caught in the main program. Next f2 is called which could handle only the FileNotFoundException but not a NullPointerException. Nevertheless the finally block is executed and then the control returns to the main program. Because there is no try ... catch statement around the call to f2 and no matching catch block is found, the thread is terminated. Note, that f2 and main can not execute the system output statements any more.
Second Example
The second example will show some special behaviour in catch and finally blocks:
import java.io.*;
class Demo2 {
  public static FileInputStream f1(String fileName)
  {
    FileInputStream fis = null;
    try
    {
      fis = new FileInputStream(fileName);
    }
    catch (FileNotFoundException ex)
    {
      System.out.println("f1: Oops, FileNotFoundException caught");
      throw new Error("f1: File not found");
    }
    System.out.println("f1: File input stream created");
    return fis;
  }
  public static FileInputStream f2(String fileName)
  {
    FileInputStream fis = null;
    try
    {
      fis = new FileInputStream(fileName);
    }
    catch (FileNotFoundException ex)
    {
      System.out.println("f2: Oops, FileNotFoundException caught");
      return fis;
    }
    finally
    {
      System.out.println("f2: finally block");
      return fis;
    }
    // Compiler error: statement not reacheable
    // System.out.println("f2: Returning from f2");
    // return fis;

  }
  public static void main(String args[])
  {
    FileInputStream fis1 = null;
    FileInputStream fis2 = null;
    String fileName = "foo.bar";
    // String fileName = null;
    System.out.println(  "main: Starting " + Demo2.class.getName()
                       + " with file name = " + fileName);
    // get file input stream 1
    try {
      fis1 = f1(fileName);
    }
    catch (Exception ex)
    {
      System.out.println("main: Oops, general exception caught");
    }
    catch (Throwable th)
    {
      System.out.println("main: Oops, throwable object caught");
    }
    // get file input stream 2
    fis2 = f2(fileName);
    System.out.println("main: " + Demo2.class.getName() + " ended");
  }
}
}
Compile and run Demo2 will generate the following output:
main: Starting Demo2 with file name = foo.bar
f1: Oops, FileNotFoundException caught
main: Oops, throwable object caught
f2: Oops, FileNotFoundException caught
f2: finally block
main: Demo2 ended
Again f1 is called to get a new FileInputStream with a given file name. The thrown FileNotFoundException in f1 is caught in the following catch block. But this time an Error is thrown so that the method is terminated immediately. Because Error is not a subclass of Exception the first catch block does not match. But the second catch block matches all throwable objects.
Calling f2 method will generate a FileNotFoundException too. This exception is caught in f2 and the method returns directly from the catch block. Remember, that the finally block is executed regardless whether an exception is caught or not.
In both methods f1 and f2, the FileNotFoundException is caught and handled, so the program can terminate normally. Change again the fileName assignment in the main method and compile and run Demo2 again:
main: Starting Demo2 with file name = null
main: Oops, general exception caught
f2: finally block
main: Demo2 ended
The NullPointerException thrown in f1 is not caught, so the exception is forwarded to the invoker. The main program catches Exception, which is a superclass of the thrown exception.
The call to f2 method seems to work fine even the thrown NullPointerException is not caught directly. Note, that the finally block is executed regardless whether an exception is caught or not. Since the finally block terminates with a return statement, the program executes without failure. So be careful returning within finally blocks, this breaks the exception chaining to the invoker and it simulates error free program execution.
Summary
  • Normal program execution is immediately branched when an exception is thrown.
     
  • Checked exceptions must be caught or forwarded. This can be done in a try ... catch statement or by defining the exception in the method definition.
     
  • The exception is caught by the first catch block whose associated exception class matches the class or a superclass of the thrown exception.
     
  • If no matching catch block is found in the exception chain, the thread containing the thrown exception is terminated.
     
  • The finally block after a try ... catch statement is executed regardless whether an exception is caught or not.
     
  • Returning within a finally block breaks the exception chain to the invoker even for uncaught exceptions.
......................

Checked or Unchecked

In Java there are basically two types of exceptions: Checked exceptions and unchecked exceptions. C# only has unchecked exceptions. The differences between checked and unchecked exceptions are:
  1. Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown.
  2. Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.
There are many arguments for and against both checked and unchecked, and whether to use checked exceptions at all. I will go through the most common arguments throughout this text. Before I do so, let me just make one thing clear:
Checked and unchecked exceptions are functionally equivalent. There is nothing you can do with checked exceptions that cannot also be done with unchecked exceptions, and vice versa.
Regardless of your choice between checked and unchecked exceptions it is a matter of personal or organisational style. None is functionally better than the other.


A Simple Example

Before discussing the advantages and disadvantages of checked and unchecked exceptions I will show you the difference in the code they make. Here is a method that throws a checked exception, and another method that calls it:
    public void storeDataFromUrl(String url){
        try {
            String data = readDataFromUrl(url);
        } catch (BadUrlException e) {
            e.printStackTrace();
        }
    }

    public String readDataFromUrl(String url)
    throws BadUrlException{
        if(isUrlBad(url)){
            throw new BadUrlException("Bad URL: " + url);
        }

        String data = null;
        //read lots of data over HTTP and return
        //it as a String instance.

        return data;
    }
As you can see the readDataFromUrl() method throws a BadUrlException. I have created BadUrlException myself. BadUrlException is a checked exception because it extends java.lang.Exception:
    public class BadUrlException extends Exception {
        public BadUrlException(String s) {
            super(s);
        }
    }
If storeDataFromUrl() wants to call readDataFromUrl() it has only two choices. Either it catches the BadUrlException or propagates it up the call stack. The storeDataFromUrl() listed above catches the exception. This storeDataFromUrl() implementation propagates the BadUrlException instead:
    public void storeDataFromUrl(String url)
    throws BadUrlException{
        String data = readDataFromUrl(url);
    }
Notice how the try catch block is gone and a "throws BadUrlException" declaration is added instead. Now, let's see how it looks with unchecked exceptions. First I change the BadUrlException to extend java.lang.RuntimeException instead:
    public class BadUrlException extends RuntimeException {
        public BadUrlException(String s) {
            super(s);
        }
    }
Then I change the methods to use the now unchecked BadUrlException:
    public void storeDataFromUrl(String url){
        String data = readDataFromUrl(url);
    }

    public String readDataFromUrl(String url) {
        if(isUrlBad(url)){
            throw new BadUrlException("Bad URL: " + url);
        }

        String data = null;
        //read lots of data over HTTP and
        //return it as a String instance.

        return data;
    }
Notice how the readDataFromUrl() method no longer declares that it throws BadUrlException. The storeDataFromUrl() method doesn't have to catch the BadUrlException either. The storeDataFromUrl() method can still choose to catch the exception but it no longer has to, and it no longer has to declare that it propagates the exception.


Checked or Unchecked?

Now that we have seen the difference in code between checked and unchecked exceptions, let's dive into the arguments for and against both.
Some Java books(*) covering exceptions advice you to use checked exceptions for all errors the application can recover from, and unchecked exceptions for the errors the application cannot recover from. In reality most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions. The action / transaction that failed will be aborted but the application has to stay alive and be ready to serve the next action / transaction. The only time it is normally legal to shut down an application is during startup. For instance, if a configuration file is missing and the application cannot do anything sensible without it, then it is legal to shut down the application.
(*) Suns Java Tutorial does for one.
My advice to you is to use either only checked exceptions or only unchecked exceptions. Mixing exception types often results in confusion and inconsistent use. Of course you should be pragmatic. Do what makes sense in your situation.
Below is a list of the most common arguments for and against checked and unchecked exceptions. An argument in favor of one type of exceptions is usually against the other type (pro-checked = con-unchecked, pro-unchecked = con-checked). Therefore the arguments are only listed as either in favour of checked or unchecked exceptions.


  1. Pro Checked Exceptions:
    Compiler enforced catching or propagation of checked exceptions make it harder to forget handling that exception.
  2. Pro Checked Exceptions:
    Unchecked exceptions makes it easier to forget handling errors since the compiler doesn't force the developer to catch or propagate exceptions (reverse of 1).
  3. Pro Unchecked Exceptions:
    Checked exceptions that are propagated up the call stack clutter the top level methods, because these methods need to declare throwing all exceptions thrown from methods they call.
  4. Pro Checked Exceptions:
    When methods do not declare what unchecked exceptions they may throw it becomes more difficult to handle them.
  5. Pro Unchecked Exceptions:
    Checked exceptions thrown become part of a methods interface and makes it harder to add or remove exceptions from the method in later versions of the class or interface.


Each of the arguments also have counter arguments which will be discussed as I go through the argument in the following sections.

Argument 1 (Pro Checked Exceptions):

Compiler enforced catching or propagation of checked exceptions makes it harder to forget the handling of that exception.

Counter-argument:

When being forced to catch or propagate many exceptions developers risk acting sloppily, and just write
try{
   callMethodThatThrowsException();
catch(Exception e){
}
and thus effectively ignore the error.


Argument 2 (Pro Checked Exceptions):

Unchecked exceptions makes it easier to forget handling errors since the compiler doesn't force the developer to catch or propagate exceptions.

Counter-argument 1:

It's not any worse than the sloppy exception handling tendency when being forced to handle or propagate checked exceptions.

Counter-argument 2:

On a recent larger project we decided to go with unchecked exceptions. My personal experience from that project is this: When using unchecked exceptions any method can potentially throw exceptions. Thus I was always reasonably conscious about exceptions no matter what parts of the code I was working on. Not only when checked exceptions were declared.
In addition many of the standard Java API methods that do not declare any checked exceptions may still throw unchecked exceptions like NullPointerException or InvalidArgumentException. Your application will still need to handle these unchecked exceptions. You could argue that the fact that there are checked exceptions makes it easy to forget handling the unchecked exceptions because they are not declared.


Argument 3 (Pro Unchecked Exceptions):

Checked exceptions that are propagated up the call stack clutter the top level methods, because these methods need to declare throwing all exceptions thrown from methods they call. That is. the declared exceptions are aggreated up the methods in the call stack. Example:
    public long readNumberFromUrl(String url)
    throws BadUrlExceptions, BadNumberException{
        String data = readDataFromUrl(url);
        long number = convertData(data);
        return number;
    }

    private String readDataFromUrl(String url)
    throws BadUrlException {
       //throw BadUrlException if url is bad.
       //read data and return it.
    }

    private long convertData(String data)
    throws BadNumberException{
        //convert data to long.
        //throw BadNumberException if number isn't within valid range.
    }
As you can see the readNumberFromUrl() needs to declare throwing both the BadUrlException and the BadNumberException that are thrown from the readDataFromUrl() and converData() methods. Imagine how many exceptions would need to be declared at the top level methods of an application with thousands of classes. This can make checked exception propagation a real pain.

Counter-argument 1:

The exception declaration aggregation rarely happens in real applications. Often developers will use exception wrapping instead. Here is how that could look:
    public void readNumberFromUrl(String url)
    throws ApplicationException{
        try{
            String data = readDataFromUrl(url);
            long number = convertData(data);
        } catch (BadUrlException e){
            throw new ApplicationException(e);
        } catch (BadNumberException e){
            throw new ApplicationException(e);
        }
    }
As you can see the readNumberFromUrl() method now only declares throwing ApplicationException. The exceptions BadUrlException and BadNumberException are caught and wrapped in a more general ApplicationException. This way exception wrapping avoids exception declaration aggregation.
My personal opinion is, that if all you do is to wrap the exception and not provide any extra information, why wrap it at all? The try-catch block is just extra code that doesn't do anything. It would be easier to just make the ApplicationException, BadUrlException and BadNumberException be unchecked exceptions. Here is an unchecked version of the above code:
    public void readNumberFromUrl(String url){
        String data = readDataFromUrl(url);
        long number = convertData(data);
    }
It is still possible to wrap unchecked exceptions if you should want to. Below is a wrapping edition of the unchecked code. Notice how the readNumberFromUrl() method does not declare throwing the ApplicationException even if it throws it.
    public void readNumberFromUrl(String url)
        try{
            String data = readDataFromUrl(url);
            long number = convertData(data);
        } catch (BadUrlException e){
            throw new ApplicationException(
                "Error reading number from URL", e);
        } catch (BadNumberException e){
            throw new ApplicationException(
                "Error reading number from URL", e);
        }
    }

Counter-argument 2:

Another commonly used technique to avoid exception declaration aggregation up the call stack of an application is to create an application base exception. All exceptions thrown in the application must be a subclass of the base exception. All methods throwing exceptions need only declare to throw the base exception. As you know a method throwing Exception may also throw any subclass of Exception. Here is how that could look:
    public long readNumberFromUrl(String url)
    throws ApplicationException {
        String data = readDataFromUrl(url);
        long number = convertData(data);
        return number;
    }

    private String readDataFromUrl(String url)
    throws BadUrlException {
       //throw BadUrlException if url is bad.
       //read data and return it.
    }

    private long convertData(String data)
    throws BadNumberException{
        //convert data to long.
        //throw BadNumberException if number isn't within valid range.
    }


    public class ApplicationException extends Exception{ }
    public class BadNumberException   extends ApplicationException{}
    public class BadUrlException      extends ApplicationException{}
Notice how the BadNumberException and BadUrlException are no longer declared thrown nor caught and wrapped. They are subclasses of the ApplicationException so they will get propagated up the call stack.
My opinion is the same as with exception wrapping: If all methods in the application just declares throwing the ApplicationException (base exception), why not just make the ApplicationException unchecked and save some try-catch blocks and throws ApplicationExceptions clauses?

Argument 4 (Pro Checked Exceptions)

When methods do not declare what unchecked exceptions they may throw it becomes more difficult to handle them. Without declaration you cannot know which exceptions the method may throw. Thus you may not know how to handle them properly. Except of course, if you have access to the code and can see there what exceptions may be thrown from the method.

Counter-argument:

In most cases you cannot do anything about the exception except showing an error message to the user, write a message to the log, and/or rollback the transaction etc. No matter what exception occurs you will in many situations handle it the same way. Because of this applications often have a few central and general pieces of error handling code. Therefore it is not so important to know exactly what exceptions may be thrown.

Argument 5 (Pro Unchecked Exceptions)

Checked exceptions declared on methods become part of a the class or interface contract. This makes it harder to add new exceptions to the method later without breaking the contract.

Counter-argument

This is not a problem if the method uses a base exception. New exceptions can be thrown at will if the method declares throwing the base exception. The only requirement is that the new exceptions thrown are subclasses of the base exception.
Again, what is the value of having all methods that may throw exceptions declare throwing the same base exception? Does it enable you to handle the exceptions any better than if you knew the methods might throw an unchecked exception?


Summary

I used to be in favor of checked exceptions but recently I have begun to change my mind. Personalities like Rod Johnson (Spring Framework), Anders Hejlsberg (father of C#), Joshua Bloch (Effective Java, item 41: Avoid unnecessary use of checked exceptions) and others have made me rethink the real benefit of checked exceptions. Lately we have tried using unchecked exceptions on a larger project, and they have worked out just fine. The error handling is centralized in a few classes. Here and there we have had to do local error handling instead of propagating the exception to the main error handling code. But it is not in very many places. Our code has become somewhat more readable now that there aren't try-catch blocks all over the code. In other words, there are a lot less no-benefit catch-rethrow try-catch blocks in the code than with checked exceptions. All in all I would recommend using unchecked exceptions. At least give it a try on a project. I have summarized the reasons below:
  • Unchecked exceptions do not clutter the code with unnecessary try-catch blocks.
  • Unchecked exceptions do not clutter the method declarations with aggregated exception declarations.
  • The argument that you easier forget to handle unchecked exceptions is not valid in my experience.
  • The argument that it is harder to know how to handle undeclared exceptions is not valid in my experience.
  • Unchecked exceptions avoids versioning problems altogether.

Wednesday, July 4, 2012

how to save a object in database using java



import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
static final String saveReportSQLStat =
    "Insert into DOCUMENT_GEN " +
        "(ID_BUS, ID_BUS_FLNG, CD_DOC_TYPE, " +
            "TS_CREATED, DT_CYCLE, TX_DOCUMENT) " +
    "values(?, ?, 'FI', " +
            "?, ?, ?)";
public void saveReport(String businessID, String filingNumber,
        SavedReportResult savableReport, Connection con)
    throws CRDException, SQLException
{
    PreparedStatement prepStat = null;
    boolean newManager = false;
    if(savableReport == null)
        return;
   
    try{
        if(con == null){
            newManager = true;
            con = DBManager.getConnection();
        }
        prepStat = con.prepareStatement(saveReportSQLStat);
        prepStat.setString(1, businessID);
        prepStat.setString(2, filingNumber);
        prepStat.setTimestamp(3, DateFormatter.getInstance().getTimeStamp(savableReport.getFilingDate(), savableReport.getFilingTime()));
        prepStat.setString(4, savableReport.getFilingDate());
        if (savableReport != null) {
            StringWriter writer = new StringWriter();
       
            try {
                Marshaller.marshal(savableReport, writer);
            } catch (MarshalException e) {
                throw new CRDException(e.getMessage());
            } catch (ValidationException e) {
                throw new CRDException(e.getMessage());
            }
            ByteArrayInputStream is =
                new ByteArrayInputStream(writer.toString().getBytes());
            prepStat.setBinaryStream(5, is, is.available());
        } else {
            prepStat.setNull(5, Types.BLOB);
        }
        prepStat.execute();
        prepStat.close();
    }finally{
        if(prepStat != null)   
            prepStat.close();
        if(con != null && newManager)
            con.close();
        prepStat = null;
        con = null;       
    }
}

get the object from database using java

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;

static final String getOnlineBusinessFilingReportSQL = "Select TX_DOCUMENT from DOCUMENT_GEN where ID_BUS_FLNG = ? with UR ";
public SavedReportResult getOnlineBusinessFilingReport(String filingNumber)throws CRDException, SQLException {
    PreparedStatement prepStat = null;
    ResultSet rs = null;
    Connection con = null ;
    SavedReportResult savedReport = null;
    boolean newManager = false;
    try {
        String busIdWithoutSpace = StringUtils.deleteWhitespace(filingNumber);
        filingNumber = StringUtils.leftPad(busIdWithoutSpace, 10, '0');
    } catch (NumberFormatException e) {
    }
    try {       
        con = DBManager.getConnection();
        prepStat = con.prepareStatement(getOnlineBusinessFilingReportSQL);
        prepStat.setString(1, filingNumber != null ? filingNumber.trim() : "");
        rs = prepStat.executeQuery();
        if(rs.next()){
            InputStream is =
                rs.getBinaryStream(1);
            if(is != null){
                BufferedReader reader =
                    new BufferedReader(new InputStreamReader(is));
                try {
                    try {
                        savedReport =
                            (SavedReportResult) Unmarshaller.unmarshal(SavedReportResult.class, reader);
                   
                    } catch (ValidationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (MarshalException e) {
                    throw new CRDException(e.getMessage());
                }
            }
        }
        rs.close();
        prepStat.close();
} finally {
        if(rs != null)
            rs.close();
        if(prepStat != null)   
            prepStat.close();
        if(con != null && newManager)
                con.close();
        rs = null;   
        prepStat = null;
        con = null;       
    }
    return savedReport;
}

convert Object into a file using java


//Java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;

import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

/**
 * This class demonstrates the conversion of an arbitrary object file to a
 * PDF using JAXP (XSLT) and FOP (XSL:FO).
 */
public class GenericPDFGenerator {
   
    /*
     * This method accepts a list SavedReportResult objects, an xsl file to transform
     * and destination output stream
     */
    public void convert2PDF(InputSource inputSource, XMLReader xmlReader, InputStream xsltInputStream, OutputStream out)
                throws IOException, FOPException, TransformerException {

        //Construct driver
        Driver driver = new Driver();

        //Setup logger
        Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
        driver.setLogger(logger);
        MessageHandler.setScreenLogger(logger);

        //Setup Renderer (output format)
        driver.setRenderer(Driver.RENDER_PDF);


        try {
            driver.setOutputStream(out);

            //Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xsltInputStream));

            //Setup input for XSLT transformation
            Source src = new SAXSource(xmlReader, inputSource);

            //Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(driver.getContentHandler());

            //Start XSLT transformation and FOP processing
            transformer.transform(src, res);
        } finally {
            out.close();
        }
    }
}