Tuesday, December 25, 2012

Dao with save method

 public Course CourseSave(Integer programmeId, String courseCode, String courseName, String creator, Date create_date) {
        s = sessionFactory.openSession();
        Transaction t = null;
        Programme pro = new Programme();
        UserList u = new UserList();
        try {
            t = s.beginTransaction();
            pro.setProgrammeId(programmeId);
            u.setEmailId(creator);
            Course CourseModel = new Course();
            CourseModel.setCourseCode(courseCode);
            CourseModel.setCourseName(courseName);
            CourseModel.setProgramme(pro);
            CourseModel.setCoursCreator(u);
            CourseModel.setCourceCreatorDate(create_date);
            s.save(CourseModel);
            t.commit();
            return CourseModel;
        } catch (Throwable ex) {
            //Log the Exception
            t.rollback();
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        } finally {
            s.close();
            sessionFactory.close();
        }
    }

Dao with Update method

public References ReferencesUpdate(long references_id, String user_id, String name, String designation, String org_univ, String place, String city, String state, String country, Long phoneno, Long mobileno, String email_id, String website) {
         s = sf.openSession();
        Transaction t = null;
        try {
            t = s.beginTransaction();
            References UpdateInfo = (References) s.load(References.class, references_id);
            UpdateInfo.setCity(city);
            UpdateInfo.setCountry(country);
            UpdateInfo.setDesignation(designation);
            UpdateInfo.setEmailId(email_id);
            UpdateInfo.setMobileno(mobileno);
            UpdateInfo.setName(name);
            UpdateInfo.setOrgUniv(org_univ);
            UpdateInfo.setPhoneno(phoneno);
            UpdateInfo.setPlace(place);
            UpdateInfo.setState(state);
            UpdateInfo.setWebsite(website);
            if (null != UpdateInfo) {
                s.update(UpdateInfo);
            }
            t.commit();
            return UpdateInfo;
        } catch (Throwable ex) {
            //Log the Exception
            t.rollback();
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        } finally {
            s.close();
            sf.close();
        }
    }

Dao delete example

@SuppressWarnings("unchecked")
    public AcademicDelete AcademicInformation(long academicInfoId) {
         s = sf.openSession();
        Transaction t = null;
        try {
            t = s.beginTransaction();

            Academic deleteInfo = (Academic) s.load(Academic.class, academicInfoId);
            if (deleteInfo != null) {
                s.delete(deleteInfo);
            }
            t.commit();
            return deleteInfo;
        } catch (Throwable ex) {
            //Log the Exception
            t.rollback();
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        } finally {
            s.close();
            sf.close();
        }
    }

DAo with list example

 @SuppressWarnings("unchecked")
    public List<Academic> ProfileAcademicListByUserId(String user_id) {
        s = sf.openSession();
        Transaction t = s.beginTransaction();

        List<Academic> academiclist = null;
        try {
            academiclist = s.createQuery("from Academic where user_id='" + user_id + "'").list();
        } catch (HibernateException HE) {
            System.out.println(HE);
        }
        t.commit();
        s.close();
        sf.close();
        return academiclist;
    }

Printing of div

function lprintf()
{
var DocumentContainer = document.getElementById('live');
var WindowObject = window.open('', 'PrintWindow','width=550,height=350,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}

How to create a Word Document

just download the apache poi.jar


package org.IGNOU.ePortfolio.Action;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.Borders;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 *
 * @author Amit
 */
public class CreateWordDoc {

     public static void main(String[] args) throws IOException {
        XWPFDocument document = new XWPFDocument();

        XWPFParagraph paragraphOne = document.createParagraph();
        paragraphOne.setAlignment(ParagraphAlignment.CENTER);
        paragraphOne.setBorderBottom(Borders.SINGLE);
        paragraphOne.setBorderTop(Borders.SINGLE);
        paragraphOne.setBorderRight(Borders.SINGLE);
        paragraphOne.setBorderLeft(Borders.SINGLE);
        paragraphOne.setBorderBetween(Borders.SINGLE);

        XWPFRun paragraphOneRunOne = paragraphOne.createRun();
        paragraphOneRunOne.setBold(true);
        paragraphOneRunOne.setItalic(true);
        paragraphOneRunOne.setText("Hello world! This is paragraph one!");
        paragraphOneRunOne.addBreak();

        XWPFRun paragraphOneRunTwo = paragraphOne.createRun();
        paragraphOneRunTwo.setText("Run two!");
        paragraphOneRunTwo.setTextPosition(100);

        XWPFRun paragraphOneRunThree = paragraphOne.createRun();
        paragraphOneRunThree.setStrike(true);
        paragraphOneRunThree.setFontSize(20);
        paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);
        paragraphOneRunThree.setText(" More text in paragraph one...");

        XWPFParagraph paragraphTwo = document.createParagraph();
        paragraphTwo.setAlignment(ParagraphAlignment.DISTRIBUTE);
        paragraphTwo.setIndentationRight(200);
        XWPFRun paragraphTwoRunOne = paragraphTwo.createRun();
        paragraphTwoRunOne.setText("And this is paragraph two.");

        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream("C:/Users/Amit/Downloads/Amit.doc");
        } catch (FileNotFoundException e) {
        }

        try {
            document.write(outStream);
            outStream.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }

}

Thursday, July 28, 2011

Connection Pooling Example in Java with MySQL, Oracle, DB


ConnectionPool.java

package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

public class ConnectionPool implements Runnable
{    
    // Number of initial connections to make.
    private int m_InitialConnectionCount = 5;    
    // A list of available connections for use.
    @SuppressWarnings("rawtypes")
private Vector m_AvailableConnections = new Vector();
    // A list of connections being used currently.
    @SuppressWarnings("rawtypes")
private Vector m_UsedConnections = new Vector();
    // The URL string used to connect to the database
    private String m_URLString = null;
    // The username used to connect to the database
    private String m_UserName = null;    
    // The password used to connect to the database
    private String m_Password = null;    
    // The cleanup thread
    private Thread m_CleanupThread = null;
       
                                             
    //Constructor
    @SuppressWarnings("unchecked")
public ConnectionPool(String urlString, String user, String passwd) throws SQLException
    {
        // Initialize the required parameters
        m_URLString = urlString;
        m_UserName = user;
        m_Password = passwd;

        for(int cnt=0; cnt<m_InitialConnectionCount; cnt++)
        {
            // Add a new connection to the available list.
            m_AvailableConnections.addElement(getConnection());
        }
       
        // Create the cleanup thread
        m_CleanupThread = new Thread(this);
        m_CleanupThread.start();
    }    
   
    private Connection getConnection() throws SQLException
    {
        return DriverManager.getConnection(m_URLString, m_UserName, m_Password);
    }
   
    @SuppressWarnings("unchecked")
public synchronized Connection checkout() throws SQLException
    {
        Connection newConnxn = null;
       
        if(m_AvailableConnections.size() == 0)
        {
            // Im out of connections. Create one more.
             newConnxn = getConnection();
            // Add this connection to the "Used" list.
             m_UsedConnections.addElement(newConnxn);
            // We dont have to do anything else since this is
            // a new connection.
        }
        else
        {
            // Connections exist !
            // Get a connection object
            newConnxn = (Connection)m_AvailableConnections.lastElement();
            // Remove it from the available list.
            m_AvailableConnections.removeElement(newConnxn);
            // Add it to the used list.
            m_UsedConnections.addElement(newConnxn);            
        }        
       
        // Either way, we should have a connection object now.
        return newConnxn;
    }
   

    @SuppressWarnings("unchecked")
public synchronized void checkin(Connection c)
    {
        if(c != null)
        {
            // Remove from used list.
            m_UsedConnections.removeElement(c);
            // Add to the available list
            m_AvailableConnections.addElement(c);        
        }
    }            
   
    public int availableCount()
    {
        return m_AvailableConnections.size();
    }
   
    public void run()
    {
        try
        {
            while(true)
            {
                synchronized(this)
                {
                    while(m_AvailableConnections.size() > m_InitialConnectionCount)
                    {
                        // Clean up extra available connections.
                        Connection c = (Connection)m_AvailableConnections.lastElement();
                        m_AvailableConnections.removeElement(c);
                       
                        // Close the connection to the database.
                        c.close();
                    }
                   
                    // Clean up is done
                }
               
                System.out.println("CLEANUP : Available Connections : " + availableCount());
               
                // Now sleep for 1 minute
                Thread.sleep(60000 * 1);
            }    
        }
        catch(SQLException sqle)
        {
            sqle.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


Main.java

package com;

import java.sql.*;


public class Main
{
    public static void main (String[] args)
    {    
        try
        {
        //JDBC Driver for MySql Database
           // Class.forName("com.mysql.jdbc.Driver").newInstance();
       
        //JDBC Driver for Oracle Database
        Class.forName("oracle.jdbc.OracleDriver");
        }
        catch (Exception E)
        {
            System.err.println("Unable to load driver.");
            E.printStackTrace();
        }

        try
        {        
            //Connection with MySQL Database....
        //ConnectionPool cp = new ConnectionPool("jdbc:mysql://localhost/test", "root", "vinay0809");
           
       //Connection with Oracle Database...
        ConnectionPool cp = new ConnectionPool("jdbc:oracle:thin:@localhost:1521:XE", "java", "vinay0809");
            Connection []connArr = new Connection[7];
       
            for(int i=0; i<connArr.length;i++)
            {
                connArr[i] = cp.checkout();
                System.out.println("Checking out..." + connArr[i]);
                System.out.println("Available Connections ... " + cp.availableCount());
            }                

            for(int i=0; i<connArr.length;i++)
            {
                cp.checkin(connArr[i]);
                System.out.println("Checked in..." + connArr[i]);
                System.out.println("Available Connections ... " + cp.availableCount());
            }
        }
        catch(SQLException sqle)
        {
            sqle.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }        
    }
}




/**
 * @(#)DBConnect.java
 * @author
 * @version 1.00 2011/5/10
 */

import java.sql.*;

public class DBConnect
{
static Connection con=null;
static final String DBDriver="sun.jdbc.odbc.JdbcOdbcDriver";
static final String DBURL="jdbc:odbc:";
static final String DBName="JAVA";
static final String DBUser="";
static final String DBPassword="";

public Connection getConnection()
{
if(con !=null)
return con;
try
{
con=DriverManager.getConnection("jdbc:odbc:DB2DSN");
}
catch(SQLException e)
{
System.err.println("Cannot connect to database: for DB2. \n Check that DB2 is running and \nthe SKICLUB database Exists.");
}
return con;
}
/**
*main method
*@pram not used
*/
public static void main (String[] args)
{
DBConnect dbdemo=new DBConnect();
System.out.println("Getting Database Driver.");

try
{
Class.forName(DBDriver);
}
catch(ClassNotFoundException e)
{
System.err.println("Cannot load Database Driver:\n for DB2, your classpath muct include\nSQLLIB\\java12\\DB2Java.Zip.");
}
System.out.println("Getting Database Connection");
Connection con=dbdemo.getConnection();
if(con==null)
System.exit(0);
System.out.println("\nDatabase Ready.");
try
{
DatabaseMetaData md=con.getMetaData();
System.out.println("\nProduct Name: "+md.getDatabaseProductName());
System.out.println("\nDriver Name: "+md.getDriverName());
con.close();
}
catch(Exception e)
{
System.err.println(e.getClass().getName()+":"+e.getMessage());
}
}

}