SDN Featured Content

Do you Think Hibernate is better technology that EJB

Java/J2EE blogs

Welcome to my java /J2EE blogs.


Thursday, December 31, 2009

Storing/retrieving the image data from SQL server.

This is the example that stores the pdf file into  SQL server image data and retrieve the data back.

 

package com.test;
import java.sql.*;
import java.io.*;
/**
*
* @author ajayk
*
*/
public class SavePDF
{
        public static void main(String[] args)
        {
                Connection connection=getConnection(
                  "jdbc:sqlserver://192.168.10.102:1433;databaseName=pp_integration","sa","rtr");
                deleteImageData(connection);
                insertImage(connection,"C://Documents and Settings//ram//Desktop//install.pdf");
                getImageData(connection);
        }

   public static Connection getConnection(String connectString,String userId, String password)
     {
       Connection conn=null;
             try
             {
                     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                     conn = DriverManager.getConnection(
                             connectString, userId, password);

                     System.out.println("connected");
                     return conn;
             }
             catch (Exception e)
             {
                     e.printStackTrace();
             }
            return conn;
     }

     public static void insertImage(Connection conn,String img)
     {
             int len;
             String query;
             PreparedStatement pstmt;
             try
             {
                     File file = new File(img);
                     FileInputStream fis = new FileInputStream(file);
                     len = (int)file.length();

                     query = ("insert into test_blob VALUES(?)");
                     pstmt = conn.prepareStatement(query);
                     pstmt.setBinaryStream(1, fis, len);
                     pstmt.executeUpdate();

             }
             catch (Exception e)
             {
                     e.printStackTrace();
             }
     }

     public static void getImageData(Connection conn)
     {
              byte[] fileBytes;
              String query;
              try
              {
                      query = "select image from test_blob";
                      Statement state = conn.createStatement();
                      ResultSet rs = state.executeQuery(query);
                      if (rs.next())
                     {
                               fileBytes = rs.getBytes(1);
                               OutputStream targetFile= 
                               new FileOutputStream(
                                    "C://Documents and Settings//ram//Desktop//new.pdf");

                               targetFile.write(fileBytes);
                               targetFile.close();
                     }       
              }
              catch (Exception e)
              {
                      e.printStackTrace();
              }
     }
     public static void deleteImageData(Connection conn)
     {
             String query;
              try
              {
                      query = "delete  from test_blob";
                      Statement state = conn.createStatement();
                      state.execute(query);
              }
              catch (Exception e)
              {
                      e.printStackTrace();
              }
     } 
}

Monday, December 28, 2009

Splitting of a pdf document using java itext API

Below is the simple java program that can split the pdf document to a specific range of the pages.

 

package com.pdf.split;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFSplit
{
    /**
     * Default constructor
     */
    public PDFSplit(){
    }
    /**
     * parameterized constructor
     */
    public PDFSplit(String fromPath,int fromPage,int toPage,String toPath){
    splitPDF1(fromPath,fromPage,toPage,toPath);
    }

    public static void main(String[] args)
    {

        try
        {

            splitPDF(new FileInputStream("C:\\PAYware_SIM_Integration_Guide.pdf"),

            new FileOutputStream("C:\\output2.pdf"), 2, 10);

        }
        catch (Exception e)
        {

            e.printStackTrace();

        }

    }

    /**
     *
     * @param inputStream
     * @param outputStream
     * @param fromPage
     * @param toPage
     */
    public static void splitPDF(InputStream inputStream,

    OutputStream outputStream, int fromPage, int toPage)
    {

        Document document = new Document();

        try
        {
            PdfReader inputPDF = new PdfReader(inputStream);
            int totalPages = inputPDF.getNumberOfPages();
            if (fromPage > toPage)
            {
            fromPage = toPage;
            }
            if (toPage > totalPages)
            {
            toPage = totalPages;
            }
            // Create a writer for the outputstream 
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data 
            PdfImportedPage page;
            while (fromPage <= toPage)
            {
            document.newPage();
            page = writer.getImportedPage(inputPDF, fromPage);
            cb.addTemplate(page, 0, 0);
            fromPage++;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        }
        catch (Exception e)
        {
        e.printStackTrace();
        }
        finally
        {
        if (document.isOpen()){
            document.close();
        }
        try{
        if (outputStream != null)
        outputStream.close();
        }
        catch (IOException ioe)
        {
        ioe.printStackTrace();
        }
        }
    }

    /**
     *
     * @param inputStream
     * @param outputStream
     * @param fromPage
     * @param toPage
     */
    public static void splitPDF1(String pathFrom,int fromPage, int toPage,String toPath){
        Document document = new Document();
        OutputStream outputStream=null;
        InputStream inputStream=null;
        try
        {
            inputStream=new FileInputStream(pathFrom);
            outputStream=new FileOutputStream(toPath);
            PdfReader inputPDF = new PdfReader(inputStream);
            int totalPages = inputPDF.getNumberOfPages();
            //make fromPage equals to toPage if it is greater 
            if (fromPage > toPage)
            {
            fromPage = toPage;
            }
            if (toPage > totalPages)
            {
            toPage = totalPages;
            }
            // Create a writer for the outputstream 
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data 
            PdfImportedPage page;
            while (fromPage <= toPage)
            {
            document.newPage();
            page = writer.getImportedPage(inputPDF, fromPage);
            cb.addTemplate(page, 0, 0);
            fromPage++;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        }
        catch (Exception e)
        {
        e.printStackTrace();
        }
        finally
        {
        if (document.isOpen()){
            document.close();
        }
        try{
        if (outputStream != null)
        outputStream.close();
        }
        catch (IOException ioe)
        {
        ioe.printStackTrace();
        }
        }
    }
}

Friday, December 18, 2009

A good link on spring Aspect oriented programming

Here is very good link to understand the Spring AOP concepts..

http://www.javalobby.org/java/forums/t44746.html


Enjoy healthy reading.......................

getting SQL timestamp for the last calender day

Here is a code snippet of getting the sql timestamp for the last calender day

We can also modify the timing in date(currrent or previous), hour, minute or seconds by adding the positive or negative number.

Calendar todayDate = Calendar.getInstance();
todayDate.add(Calendar.DATE, -1);
todayDate.set(Calendar.HOUR_OF_DAY, 0);
todayDate.set(Calendar.MINUTE, 0); // set minute in hour
todayDate.set(Calendar.SECOND, 0); // set second in minute
todayDate.set(Calendar.MILLISECOND, 0);
Date currentDate=todayDate.getTime();
long miliseconds=currentDate.getTime();
java.sql.Timestamp lastDayDate = new java.sql.Timestamp(miliseconds);

Payware API payment example from java language

Payware API is one of the easy way to make payment online using no API setup.
It has made a simple java example to post the valid XML as an request to the Payware API and in return we get the response back.

We must have the demo account setup with the payware before we try this example else it give the error with invalid login details.

It's very good API that support the multiple plateform(visual basic,java .net) to make the payment online.



package com.payware.classes;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.payware.util.Utilities;
import com.payware.util.PaywareConstants;
public class PaywarePayment{
/**
* logger instance
*/
protected Log log = LogFactory.getLog(getClass());

public String processPayment(
) throws Exception {
log.info("PaywarePayment is called");
StringBuffer responseData=new StringBuffer();
try {

String requestXml =
""+
"100010001"+
"APIUser"+
"APIPassword"+
"123456789"+
"PAYMENT"+
"SALE"+
"CREDIT"+
"4005550000000019"+
"3"+
"4005550000000019=07121011000012345678"+
"12"+
"07"+
"1.00"+
"12345678901234567"+
"12345678901234567"+
"0.16"+
"123456"+
"
";
String httpsURL = "https://APIDemo.IPCharge.net/IPCHAPI/RH.aspx";
URL myurl = new URL(httpsURL);

HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\"");
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(),
"UTF8");
out.write(requestXml);
out.close();

InputStream ins = con.getInputStream();
InputStreamReader isr=new InputStreamReader(ins);
BufferedReader in =new BufferedReader(isr);

String inputLine="";
responseData.append("\n");
while ((inputLine = in.readLine()) != null){
if(!inputLine.trim().equalsIgnoreCase(".") && !inputLine.trim().equalsIgnoreCase("")){
System.out.println("Input Line:::"+inputLine);
String key=inputLine.substring(0,inputLine.indexOf(" "));;
String value=inputLine.substring(key.length(),inputLine.length());
responseData.append("<"+key+">"+value+""+"\n");
}
}
responseData.append("
");

} catch (Exception e) {
e.printStackTrace();

}

return responseData.toString();
}

public static void main(String args[]){
PaywarePayment ppgtw=new PaywarePayment();
String response="";
try
{
response = ppgtw.processPayment();
System.out.println(response);
String currentDate = Utilities.now("yyyyMMdd");
String file_name = "PFReport" + currentDate + ".xml";
FileWriter WriteResult = new FileWriter("c:" +
"\\reports\\" +
file_name);
PrintWriter ResultOutput = new
PrintWriter(WriteResult, true);
ResultOutput.println(response);



} catch (Exception e)
{
System.out.println("Error in the main class:"+e.getMessage());
e.printStackTrace();
}

}
}

Thursday, June 18, 2009

seting up SSL in tomcat 6

Hi All


Here is a good link to set up the SSL in tomcat 6.


http://techtracer.com/2007/09/12/setting-up-ssl-on-tomcat-in-3-easy-steps/

Types of Beans


Managed-Bean Type


Description: This type of managed-bean participates in the "Model" concern of the MVC design pattern. When you see the word "model" -- think DATA. A JSF model-bean should be a POJO that follows the JavaBean design pattern with getters/setters encapsulating properties. The most common use case for a model bean is to be a database entity, or to simply represent a set of rows from the result set of a database query.

Backing Managed-Bean

Description: This type of managed-bean participates in the "View" concern of the MVC design pattern. The purpose of a backing-bean is to support UI logic, and has a 1::1 relationship with a JSF view, or a JSF form in a Facelet composition. Although it typically has JavaBean-style properties with associated getters/setters, these are properties of the View -- not of the underlying application data model. JSF backing-beans may also have JSF actionListener and valueChangeListener methods.

Controller Managed-Bean

Description: This type of managed-bean participates in the "Controller" concern of the MVC design pattern. The purpose of a controller bean is to execute some kind of business logic and return a navigation outcome to the JSF navigation-handler. JSF controller-beans typically have JSF action methods (and not actionListener methods).
Support Managed-Bean
Description: This type of bean "supports" one or more views in the "View" concern of the MVC design pattern. The typical use case is supplying an ArrayList to JSF h:selectOneMenu drop-down lists that appear in more than one JSF view. If the data in the dropdown lists is particular to the user, then the bean would be kept in session scope. However, if the data applies to all users (such as a dropdown lists of provinces), then the bean would be kept in application scope, so that it can be cached for all users.

Utility Managed-Bean

Description: This type of bean provides some type of "utility" function to one or more JSF views. A good example of this might be a FileUpload bean that can be reused in multiple web applications.

THE SINGLETON PATTERN

THE SINGLETON PATTERN
The Singleton pattern is grouped with the other Creational patterns, although
it is to some extent a “non-creational” pattern. There are any number of cases
in programming where you need to make sure that there can be one and only
one instance of a class. For example, your system can have only one window
manager or print spooler, or a single point of access to a database engine.
The easiest way to make a class that can have only one instance is to embed a
static variable inside the class that we set on the first instance and check
for each time we enter the constructor. A static variable is one for which there
is only one instance, no matter how many instances there are of the class.
static boolean instance_flag = false;
The problem is how to find out whether creating an instance was successful
or not, since constructors do not return values. One way would be to call a
method that checks for the success of creation, and which simply returns
some value derived from the static variable. This is inelegant and prone to
error, however, because there is nothing to keep you from creating many
instances of such non-functional classes and forgetting to check for this error
condition.
A better way is to create a class that throws an Exception when it is
instantiated more than once. Let’s create our own exception class for this
case:
class SingletonException extends RuntimeException
{
//new exception type for singleton classes
public SingletonException()
{
super();
}
//-----------------------------------------------
public SingletonException(String s)
{
super(s);
}
}
Note that other than calling its parent classes through the super()method,
this new exception type doesn’t do anything in particular. However, it is
convenient to have our own named exception type so that the compiler will
warn us of the type of exception we must catch when we attempt to create an
instance of PrintSpooler.
32
Throwing the Exception
Let’s write the skeleton of our PrintSpooler class; we’ll omit all of the
printing methods and just concentrate on correctly implementing the
Singleton pattern:
class PrintSpooler
{
//this is a prototype for a printer-spooler class
//such that only one instance can ever exist
static boolean
instance_flag=false; //true if 1 instance
public PrintSpooler() throws SingletonException
{
if (instance_flag)
throw new SingletonException("Only one spooler allowed");
else
instance_flag = true; //set flag for 1 instance
System.out.println("spooler opened");
}
//-------------------------------------------
public void finalize()
{
instance_flag = false; //clear if destroyed
}
}
Creating an Instance of the Class
Now that we’ve created our simple Singleton pattern in the PrintSpooler
class, let’s see how we use it. Remember that we must enclose every method
that may throw an exception in a try - catch block.
public class singleSpooler
{
static public void main(String argv[])
{
PrintSpooler pr1, pr2;
//open one spooler--this should always work
System.out.println("Opening one spooler");
try{
pr1 = new PrintSpooler();
}
catch (SingletonException e)
{System.out.println(e.getMessage());}
//try to open another spooler --should fail
System.out.println("Opening two spoolers");
33
try{
pr2 = new PrintSpooler();
}
catch (SingletonException e)
{System.out.println(e.getMessage());}
}
}
Then, if we execute this program, we get the following results:
Opening one spooler
printer opened
Opening two spoolers
Only one spooler allowed
where the last line indicates than an exception was thrown as expected. You
will find the complete source of this program on the example CD-ROM as
singleSpooler.java.
Static Classes as Singleton Patterns
There already is a kind of Singleton class in the standard Java class libraries:
the Math class. This is a class that is declared final and all methods are
declared static, meaning that the class cannot be extended. The purpose of
the Math class is to wrap a number of common mathematical functions such
as sin and log in a class-like structure, since the Java language does not
support functions that are not methods in a class.
You can use the same approach to a Singleton pattern, making it a final class.
You can’t create any instance of classes like Math, and can only call the static
methods directly in the existing final class.
final class PrintSpooler
{
//a static class implementation of Singleton pattern
static public void print(String s)
{
System.out.println(s);
}
}
//==============================
public class staticPrint
{
public static void main(String argv[])
{
Printer.print("here it is");
}
}
34
One advantage of the final class approach is that you don’t have to
wrap things in awkward try blocks. The disadvantage is that if you would like
to drop the restrictions of Singleton status, this is easier to do in the exception
style class structure. We’d have a lot of reprogramming to do to make the
static approach allow multiple instances.
Creating Singleton Using a Static Method
Another approach, suggested by Design Patterns, is to create
Singletons using a static method to issue and keep track of instances. To
prevent instantiating the class more than once, we make the constructor
private so an instance can only be created from within the static method of the
class.
class iSpooler
{
//this is a prototype for a printer-spooler class
//such that only one instance can ever exist
static boolean instance_flag = false; //true if 1 instance
//the constructor is privatized-
//but need not have any content
private iSpooler() { }
//static Instance method returns one instance or null
static public iSpooler Instance()
{
if (! instance_flag)
{
instance_flag = true;
return new iSpooler(); //only callable from within
}
else
return null; //return no further instances
}
//-------------------------------------------
public void finalize()
{
instance_flag = false;
}
}
One major advantage to this approach is that you don’t have to worry
about exception handling if the singleton already exists-- you simply get a
null return from the Instance method:
iSpooler pr1, pr2;
//open one spooler--this should always work
System.out.println("Opening one spooler");
pr1 = iSpooler.Instance();
35
if(pr1 != null)
System.out.println("got 1 spooler");
//try to open another spooler --should fail
System.out.println("Opening two spoolers");
pr2 = iSpooler.Instance();
if(pr2 == null)
System.out.println("no instance available");
And, should you try to create instances of the iSpooler class directly,
this will fail at compile time because the constructor has been declared as
private.
//fails at compile time because constructor is privatized
iSpooler pr3 = new iSpooler();
Finding the Singletons in a Large Program
In a large, complex program it may not be simple to discover where
in the code a Singleton has been instantiated. Remember that in Java, global
variables do not really exist, so you can’t save these Singletons conveniently
in a single place.
One solution is to create such singletons at the beginning of the
program and pass them as arguments to the major classes that might need to
use them.
pr1 = iSpooler.Instance();
Customers cust = new Customers(pr1);
A more elaborate solution could be to create a registry of all the
Singleton classes in the program and make the registry generally available.
Each time a Singleton instantiates itself, it notes that in the Registry. Then
any part of the program can ask for the instance of any singleton using an
identifying string and get back that instance variable.
The disadvantage of the registry approach is that type checking may
be reduced, since the table of singletons in the registry probably keeps all of
the singletons as Objects, for example in a Hashtable object. And, of course,
the registry itself is probably a Singleton and must be passed to all parts of
the program using the constructor or various set functions.
Other Consequences of the Singleton Pattern
1. It can be difficult to subclass a Singleton, since this can only work if the
base Singleton class has not yet been instantiated.
36
2. You can easily change a Singleton to al

Factory Patterns in Math Computation
Most people who use Factory patterns tend to think of them as tools
for simplifying tangled programming classes. But it is perfectly possible to
use them in programs that simply perform mathematical computations. For
example, in the Fast Fourier Transform (FFT), you evaluate the following
four equations repeatedly for a large number of point pairs over many passes
through the array you are transforming. Because of the way the graphs of
these computations are drawn, these equations constitute one instance of the
FFT “butterfly.” These are shown as Equations 1--4.




So it is not unreasonable to package this computation in a couple of
classes doing the simple or the expensive computation depending on the
angle y. We’ll start by creating a Complex class that allows us to manipulate
real and imaginary number pairs:
class Complex {
float real;
float imag;
}


Then we’ll create our Butterfly class as an abstract class that we’ll fill
in with specific descendants:
abstract class Butterfly {
float y;
public Butterfly() {
}
public Butterfly(float angle) {
y = angle;
}
abstract public void Execute(Complex x, Complex y);
}
Our two actual classes for carrying out the math are called
addButterfly and trigButterfly. They implement the computations shown in
equations (1--4) and (5--8) above.
class addButterfly extends Butterfly {
float oldr1, oldi1;
public addButterfly(float angle) {
}
public void Execute(Complex xi, Complex xj) {
oldr1 = xi.getReal();
oldi1 = xi.getImag();
xi.setReal(oldr1 + xj.getReal()); //add and subtract
xj.setReal(oldr1 - xj.getReal());
xi.setImag(oldi1 + xj.getImag());
xj.setImag(oldi1 - xj.getImag());
}
}
and for the trigonometic version:
class trigButterfly extends Butterfly {
float y;
float oldr1, oldi1;
float cosy, siny;
float r2cosy, r2siny, i2cosy, i2siny;
public trigButterfly(float angle) {
y = angle;
cosy = (float) Math.cos(y); //precompute sine and cosine
siny = (float)Math.sin(y);
}
public void Execute(Complex xi, Complex xj) {
oldr1 = xi.getReal(); //multiply by cos and sin
oldi1 = xi.getImag();
r2cosy = xj.getReal() * cosy;
r2siny = xj.getReal() * siny;
i2cosy = xj.getImag()*cosy;
24
i2siny = xj.getImag()*siny;
xi.setReal(oldr1 + r2cosy +i2siny); //store sums
xi.setImag(oldi1 - r2siny +i2cosy);
xj.setReal(oldr1 - r2cosy - i2siny);
xj.setImag(oldi1 + r2siny - i2cosy);
}
}
Finally, we can make a simple factory class that decides which class
instance to return. Since we are making Butterflies, we’ll call our Factory a
Cocoon:
class Cocoon {
public Butterfly getButterfly(float y) {
if (y !=0)
return new trigButterfly(y); //get multiply class
else
return new addButterfly(y); //get add/sub class
}
}
You will find the complete FFT.java program on the example
CDROM.
When to Use a Factory Pattern
You should consider using a Factory pattern when
· A class can’t anticipate which kind of class of objects it must create.
· A class uses its subclasses to specify which objects it creates.
· You want to localize the knowledge of which class gets created.
There are several similar variations on the factory pattern to
recognize.
1. The base class is abstract and the pattern must return a complete working
class.
2. The base class contains default methods and is only subclassed for cases
where the default methods are insufficient.
3. Parameters are passed to the factory telling it which of several class types
to return. In this case the classes may share the same method names but
may do something quite different.

Saturday, February 21, 2009

org.apache.AnnotationProcessor error or error loadin the jsp page

java.lang.ClassCastException: org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.AnnotationProcessor



The solution is:

Add

into context.xml file (to Context element) in tomcat/conf directory. This makes classloading in Tomcat sticking to J2EE spec.