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

}
}