Monday, March 30, 2015

Generate the bar code image by itext

We can generate a bar code image by using the itext jar.

Itext jar : http://sourceforge.net/projects/itext/

Download jar : http://sourceforge.net/projects/itext/files/latest/download


sample code

import com.itextpdf.text.pdf.BarcodePDF417;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class GenerateBarCodeImage {
    public static void main(String[] args) throws IOException {
        BarcodePDF417 barcode = new BarcodePDF417();
        barcode.setText("Bla bla");
        java.awt.Image img = barcode.createAwtImage(Color.BLACK, Color.WHITE);
        BufferedImage outImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        outImage.getGraphics().drawImage(img, 0, 0, null);
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ImageIO.write(outImage, "png", bytesOut);
        bytesOut.flush();
        byte[] pngImageData = bytesOut.toByteArray();
        FileOutputStream fos = new FileOutputStream("barcode.png");
        fos.write(pngImageData);
        fos.flush();
        fos.close();
    }
}

Sunday, March 29, 2015

Regular expression to extract the src tag details from given image tag or html source text


By using the regular expression we can extract the any data from the given input, here we are trying to get the src attribute value from the given image tag or html text data.

Image 'src' attribute extract Regx:

<img[^>]*src=[\\\"']([^\\\"^']*)


sample code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class ImgTest {

    public static void main(String[] args) {

        String s = "<p><img src=\"38220.png\" alt=\"test\" title=\"test\" /> <img src=\"32222.png\" alt=\"test\" title=\"test\" /></p>";
        Pattern p = Pattern.compile("<img[^>]*src=[\\\"']([^\\\"^']*)");
        Matcher m = p.matcher(s);
        while (m.find()) {
            String src = m.group();
            int startIndex = src.indexOf("src=") + 5;
            String srcTag = src.substring(startIndex, src.length());
            System.out.println(srcTag);
        }
    }

}


Compare images are same by java

We can compare the given images are same or not by comparing the buffer data of the image.

1. Compare the image sizes are same or not.
2. Compare the binary data of two images are same or not.

sample code :

import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import javax.imageio.ImageIO;

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class compareimage {

    public static boolean compareImage(File fileA, File fileB) {
        try {
            // take buffer data from botm image files //
            BufferedImage biA = ImageIO.read(fileA);
            DataBuffer dbA = biA.getData().getDataBuffer();
            int sizeA = dbA.getSize();
            BufferedImage biB = ImageIO.read(fileB);
            DataBuffer dbB = biB.getData().getDataBuffer();
            int sizeB = dbB.getSize();
            // compare data-buffer objects //
            if (sizeA == sizeB) {
                for (int i = 0; i < sizeA; i++) {
                    if (dbA.getElem(i) != dbB.getElem(i)) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Failed to compare image files ...");
            return false;
        }
    }

    public static void main(String[] args) {
        File file1 = new File("path to image1");
        File file2 = new File("path to image2");
        System.out.println("result :" + compareImage(file1, file2));
    }
}

Friday, March 27, 2015

Reverse elements in Array

Reverse all elements in array, traditional way how we use to do is get the array and iterate through the for loop and use swap logic to move to temporary array and get the result.

But from > jdk 1.5 introduced reverse() in java.util.Collections which will reverse the order of the elements, all we have to do is to convert the array to arraylist by using Arrays.asList() and using collections.reverse() to reverse the order of the element.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class ReverseArray {

    public static void main(String[] args) {
        Integer[] numbers = new Integer[]{1, 2, 3, 4, 5, 6};
        List numberlist = Arrays.asList(numbers);
        Collections.reverse(numberlist);
        for (int i = 0; i < numberlist.size(); i++) {
            System.out.println(numberlist.get(i));
        }

        // logical way of doing , its always good to understand the logic 
        int[] _numbers = {1, 2, 3, 4, 5, 6};
        for (int i = 0; i < _numbers.length / 2; i++) {
            int temp = _numbers[i]; // swap numbers 
            _numbers[i] = _numbers[_numbers.length - 1 - i];
            _numbers[_numbers.length - 1 - i] = temp;
        }
        System.out.println("reversed array : " + Arrays.toString(_numbers));
    }
}


find character uppercase/lowercase count from given text

Find the character upper/lower case occurrence count with simple single line code without iteration in java.

int counta = text.split("(?=[a])").length - 1;

This simple code will find all the lowercase character 'a' from the given text, change the regx for the uppercase . ex 'A'.

sample test code

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class Countchar {

    public static void main(String[] args) {
        String text = "asfasfzxph adsa wetw";
        int counta = text.split("(?=[a])").length - 1;
        System.out.println("count a : "+counta);
        

    }
}


Monday, March 23, 2015

Thursday, March 19, 2015

Jfreechart servelt example



Prerequisites

  • JDK 1.5 and above
  • Jfreechart jar
  • mysql connector jar

To generate charts we can use jfrecharts which is open source and free. In this example i will show how to generate the jfreechart dynamically for every 5 seconds getting data from the database.

Full source code : github link

sample :
Create Simple servlet :

import java.awt.BasicStroke;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.data.jdbc.JDBCPieDataset;

public class JfreeChartServlet extends HttpServlet {
    
        private static Connection connection = null;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        try {
            JDBCPieDataset dataset = new JDBCPieDataset(getConnection());
            dataset.executeQuery("select * from result");
            JFreeChart chart = ChartFactory.createPieChart("Result Chart", dataset, true, true, false);
            chart.setBorderPaint(Color.black);
            chart.setBorderStroke(new BasicStroke(4.0f));
            chart.setBorderVisible(true);
            if (chart != null) {
                int width = 500;
                int height = 350;
                final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
                response.setContentType("image/png");
                OutputStream out = response.getOutputStream();
                ChartUtilities.writeChartAsPNG(out, chart, width, height, info);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    
    public static Connection getConnection() {
        if (connection != null)
            return connection;
        else {
            try {
                String driver = "com.mysql.jdbc.Driver";
                String url = "jdbc:mysql://localhost:3306/test";
                String user = "root";
                String password = "******";
                Class.forName(driver);
                connection = DriverManager.getConnection(url, user, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } 
            return connection;
        }

    }
    
    public static ArrayList<Result> getData() {
     connection = getConnection();
        ArrayList<Result> resultList = new ArrayList<Result>();
        try {
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("select * from result");
        
            while(rs.next()) { 
             Result result=new Result();
             result.setStatus(rs.getString("status"));
             result.setCount(rs.getInt("count"));
             resultList.add(result);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return resultList;
    }
}


jfreechartSample.jsp :

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pie Chart Demo</title>
<script language="Javascript">
function refreshpage(){
document.forms.form1.submit();
}
</script>
</head>
<body>
<h1>Pie Chart</h1>
<%response.setIntHeader("Refresh",5);%>
<form id="form1">
  <img src="chart" width="600" height="400" border="0"/>
<!--  <input type="button" onclick="refreshpage()" value="Refresh"/>-->
</form>
</body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>JfreeChartServlet</servlet-name>
    <servlet-class>JfreeChartServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>JfreeChartServlet</servlet-name>
    <url-pattern>/chart</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>jfreechartSample.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Database scripts: create the following table and insert the sample data.

CREATE TABLE `result` (
  `status` varchar(20) DEFAULT NULL,
  `count` int(11) DEFAULT NULL
);

INSERT INTO result(
   status
  ,count
) VALUES (
   'PASSED'  -- status - IN varchar(20)
  ,25   -- count - IN int(11)
);

INSERT INTO result(
   status
  ,count
) VALUES (
   'FAILED'  -- status - IN varchar(20)
  ,40   -- count - IN int(11)
);

INSERT INTO result(
   status
  ,count
) VALUES (
   'SKIPPED'  -- status - IN varchar(20)
  ,10   -- count - IN int(11)
)

Monday, March 2, 2015

Generate PDF report for selenium/testng test cases.

Use Open source pdfngreport plugin to generate the pdf report for the selenium/testng test cases execution.

It's Opensource and in maven repository

<dependency>
        <groupId>com.uttesh</groupId>
        <artifactId>pdfngreport</artifactId>
        <version>2.0.3</version>
</dependency>

Official WebPage http://uttesh.github.io/pdfngreport/

Pdf report will have chart shows how many test cases passed/failed/skipped.





Status table which shows full detail status of each test cases.



Exception summary of failed test cases.

5 Step to host static website/Project Pages site on github


5 Steps to host a static page or project page on github

  1. Create Github account and verify the email id
  2. Add your repository/project to github
  3. Create static pages for you application
  4. Create gh-page branch
  5. Live the pages

Create Github account and verify the email id

Create the github accound from github.com and verify email address.

Add your repository/project to github

Install git client in the respective box and upload the project to github

Create static pages for your application/profile

Create the static pages your repository, it takes all js/css/images folders also.


Create gh-page branch

Make a fresh clone


To set up a Project Pages site, you need to create a new "orphan" branch (a branch that has no common history with an existing branch) in your repository. The safest way to do this is to start with a fresh clone:



Create a gh-pages branch

Once you have a clean repository, you'll need to create the new gh-pages branch and remove all content from the working directory and index.



Add content and push
Now you have an empty working directory. You can create some content in this branch and push it to GitHub.push all static pages and relates files.

Load your new GitHub Pages site!!!!

After your push to the gh-pages branch, your Project Pages site will be available at http(s)://.github.io/. Note that Pages are always publicly accessible when published, even if their repository is private.

You con configure you domain to this.

I followed all the steps and created pages for my open source project have look for reference.







for reference see full sample code https://github.com/uttesh/pdfngreport/tree/gh-pages
live demo http://uttesh.github.io/pdfngreport/

Generate PDF page as image

We can generate the image of pdf page by using the Pdf-renderer

Simple class which generate the images file of given pdf file.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mayan.pdf;

/**
 *
 * @author Uttesh Kumar T.H.
 */
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.image.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.imageio.*;
import javax.swing.*;

public class PdfPageImageGenerator {

    public static void ImageGenerator() throws IOException {
        // load a pdf from a byte buffer
        File file = new File("sample.pdf");
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        PDFFile pdffile = new PDFFile(buf);
        int numPgs = pdffile.getNumPages();
        for (int i = 0; i < numPgs; i++) {
            PDFPage page = pdffile.getPage(i);
            Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
            Image img = page.getImage(rect.width, rect.height, rect, null, true, true);
            BufferedImage bImg = toBufferedImage(img);
            File yourImageFile = new File("pics\\page_" + i + ".png");
            ImageIO.write(bImg, "png", yourImageFile);
        }
    }

    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        image = new ImageIcon(image).getImage();
        boolean hasAlpha = hasAlpha(image);
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
        }
        if (bimage == null) {
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

    public static boolean hasAlpha(Image image) {
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage) image;
            return bimage.getColorModel().hasAlpha();
        }
        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
        }
        ColorModel cm = pg.getColorModel();
        return cm.hasAlpha();
    }

    public static void main(final String[] args) {
        new Runnable() {
            public void run() {
                try {
                    PdfPageImageGenerator.ImageGenerator();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }.run();
    }
}


formatted view of above code



Sunday, March 1, 2015

Spring + JPA + Hibernate Sample


Introduction


Stand-alone Spring application sample, Spring framework supports the persistence layer to be fully implemented through JPA. Simple example of configure the Spring needed components to perform persistence over standard JPA i.e. Persistence Unit, the Entity Manager factory and the Transaction Manager.

Sample Implementation project folder structure :


implementation as DAO layer, Service layer and hibernate model.

Build POM.xml details.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.uttesh.spring.entitymanager</groupId>
    <artifactId>SpringEntityManager</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringEntityManager</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.2.5.RELEASE</spring.version>
        <hibernate.version>4.1.9.Final</hibernate.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
  
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

    </dependencies>
</project>


JPA Entity model class


package com.uttesh.spring.entitymanager.model;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "USER")
public class User {

    @Id
    @Column(name = "ID", nullable = false)
    private int id;

    @Column(name = "NAME", nullable = false)
    private String name;

    @Column(name = "PASSWORD", nullable = false)
    private String password;

    @Column(name = "EMAIL", nullable = false)
    private String email;

    @Column(name = "SEX", nullable = false)
    private String sex;

    @Column(name = "DOB", nullable = false)
    private Date dob;

    @Column(name = "MOBILE", nullable = false)
    private String mobile;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    
}


Spring service and DAO layers

DAO layer
package com.uttesh.spring.entitymanager.dao;

import java.util.List;

import com.uttesh.spring.entitymanager.model.User;

public interface IUserDAO {

 public void save(User user);
 List<User> findAllUsers();
}

The Entity Manager is injected through the regular JPA @PersistenceContext annotation.

package com.uttesh.spring.entitymanager.dao.impl;

import com.uttesh.spring.entitymanager.dao.IUserDAO;
import com.uttesh.spring.entitymanager.model.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;

@Repository
//@Transactional(propagation = Propagation.MANDATORY, rollbackFor = {Exception.class})
public class UserDAOImpl implements IUserDAO {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void save(User user) {
        entityManager.persist(user);
        System.out.println("saved record : " + user.getId());
    }

    
    @Override
    public List<User> findAllUsers() {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<User> cq = builder.createQuery(User.class);
        Root<User> root = cq.from(User.class);
        cq.select(root);
        return entityManager.createQuery(cq).getResultList();
    }

}

service layer


package com.uttesh.spring.entitymanager.user;

import java.util.List;

import com.uttesh.spring.entitymanager.model.User;

public interface IUserService {

 void save(User user);
 List<User> findAllUsers();
}

package com.uttesh.spring.entitymanager.user.impl;

import com.uttesh.spring.entitymanager.dao.IUserDAO;
import com.uttesh.spring.entitymanager.model.User;
import com.uttesh.spring.entitymanager.user.IUserService;
import java.util.List;
import java.lang.UnknownError;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
//@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDAO userDAO;

    //@Transactional(readOnly = false)
    public void save(User user) {
        try {
            userDAO.save(user);
            save1();
           // save2();
        } catch (InterruptedException ex) {
            Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void save1() throws InterruptedException {
        User user = new User();
        user.setId(1008);
        user.setName("Uttesh kumar");
        user.setEmail("uttesh@gmail.com");
        user.setMobile("0123456789");
        user.setPassword("password");
        userDAO.save(user);
    }

    public void save2() {
        throw new UnknownError("INVALID");
    }

    @Transactional(readOnly = false)
    public List<User> findAllUsers() {
        return userDAO.findAllUsers();
    }

}

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence   http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="springEntitypersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.uttesh.spring.entitymanager.model.User</class>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
    </properties>
  </persistence-unit>
</persistence>

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd">

	<tx:annotation-driven />

	<context:component-scan base-package="com.uttesh.spring.entitymanager.dao.impl" />
	<context:component-scan base-package="com.uttesh.spring.entitymanager.user.impl" />

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/lab" />
		<property name="username" value="user" />
		<property name="password" value="password" />
	</bean>

	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="springEntitypersistenceUnit" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

</beans>


Testing

execute the sample.java class.

package com.uttesh.spring.entitymanager;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.uttesh.spring.entitymanager.model.User;
import com.uttesh.spring.entitymanager.user.IUserService;

public class Sample {

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        IUserService userManager = (IUserService) ctx.getBean("userServiceImpl");
        List<User> list = userManager.findAllUsers();
        User user = new User();
        user.setId(1006);
        user.setName("Uttesh kumar");
        user.setEmail("uttesh@gmail.com");
        user.setMobile("0123456789");
        user.setPassword("password");
        userManager.save(user);
        System.out.println("User Saved");
        list = userManager.findAllUsers();
        System.out.println("User count: " + list.size());

    }
}

Download source code from github Click here.