This is the continuation of Export QR Code to PDF in Java. In this article I am going to explain how to add QR Code images to PDF table cells with Sample Example Program.

Libraries we need 

Libraries needed for QR Code generation
  1. zxing-core-1.7.jar
  2. zxing-j2se-1.7.jar
Libraries needed for PDF generation
  1. itextpdf-5.5.0

Create PDF document 

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();

Create Table

// a table with two columns
PdfPTable table = new PdfPTable(2);
// add table to pdf document
document.add(table);

Create Table Cell

// create paragraph
Paragraph para = new Paragraph();
// create pdf cell
PdfPCell cell = new PdfPCell(para);
table.addCell(cell);

Add Image to PDF Cell

// get image instance
Image img = Image.getInstance(RESOURCE);
PdfPCell cell = new PdfPCell();
// add image to pdf cell
cell.addElement(img);

Convert BufferedImage to Image

We will get QR code image in BufferedImage format. We have to convert that into Image format and then we can add that to table cell
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage bi = createQRCode("srinivas", "UTF-8",40, 40);
ImageIO.write(bi, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
Image image = Image.getInstance(imageInByte);

ByteArrayOutputStream to file

Get PDF file in the format of ByteArrayOutputStream and then write it to file.
ByteArrayOutputStream os = PdfGenerator.getPDF(list);
FileOutputStream fos = new FileOutputStream (file);
os.writeTo(fos);

PDFGenerator.java 

This file will give the ByteArrayOutputStream of list of strings

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.qrcode.WriterException;

public class ExporToPDF {
    // color codes
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static ByteArrayOutputStream getPDF(ArrayList<String> qrList) throws DocumentException, WriterException, IOException, com.google.zxing.WriterException {
        Document document = new Document(new RectangleReadOnly(595.0F, 842.0F),
                10, 10, 10, 10);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfPTable mainTable = new PdfPTable(4);
        mainTable.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        PdfPTable subTable = null;
        PdfPTable dataTable = null;
        PdfPCell clientNumber = null;

        PdfPCell dataCell = null;
        PdfPCell imageCell = null;
        PdfPCell subTableCell = null;
        PdfPCell dummyCell = null;
            document.open();
            for (String arr : qrList) {
                subTable = new PdfPTable(2);
                subTable.setWidths(new int[] { 100, 70 });
                dataTable = new PdfPTable(1);
                dataTable.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

                clientNumber = new PdfPCell(new Phrase("# " + arr,
                        FontFactory.getFont(FontFactory.HELVETICA, 12,
                                Font.NORMAL, CMYKColor.WHITE)));

                // Get QR code
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedImage bi = createQRCode(arr, "UTF-8", 40, 40);
                ImageIO.write(bi, "png", baos);
                baos.flush();
                byte[] imageInByte = baos.toByteArray();
                baos.close();
                Image image = Image.getInstance(imageInByte);

                clientNumber.setColspan(2);
                clientNumber.setBackgroundColor(BaseColor.GRAY);
                subTable.getDefaultCell().setBorderColor(BaseColor.GRAY);

                subTable.addCell(clientNumber);
                // detail 1
                dataTable.addCell(new Phrase(trimLength("datail 1", 20),
                        FontFactory.getFont(FontFactory.HELVETICA, 5,
                                Font.NORMAL, CMYKColor.BLACK)));
                // detail 2
                dataTable.addCell(new Phrase(trimLength("datail 2", 20),
                        FontFactory.getFont(FontFactory.HELVETICA, 5,
                                Font.NORMAL, CMYKColor.BLACK)));
                // detail 3
                dataTable.addCell(new Phrase(trimLength("datail 3", 20),
                        FontFactory.getFont(FontFactory.HELVETICA, 5,
                                Font.NORMAL, CMYKColor.BLACK)));
                // detail 4
                dataTable.addCell(new Phrase(trimLength("datail 4", 20),
                        FontFactory.getFont(FontFactory.HELVETICA, 5,
                                Font.NORMAL, CMYKColor.BLACK)));
                // detail 5
                dataTable.addCell(new Phrase(trimLength("datail 6", 20),
                        FontFactory.getFont(FontFactory.HELVETICA, 5,
                                Font.NORMAL, CMYKColor.BLACK)));
                // detail 6
                dataTable.addCell(new Phrase(trimLength("datail 7", 20),
                        FontFactory.getFont(FontFactory.HELVETICA, 5,
                                Font.NORMAL, CMYKColor.BLACK)));

                dataCell = new PdfPCell(dataTable);
                dataCell.setBorderWidthRight(0);
                subTable.addCell(dataCell);

                imageCell = new PdfPCell(image);
                imageCell.setBorderWidthLeft(0);
                imageCell.setPaddingTop(7);
                imageCell.setPaddingRight(2);
                imageCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                subTable.addCell(imageCell);

                subTableCell = new PdfPCell(subTable);
                subTableCell.setBorder(Rectangle.NO_BORDER);
                subTableCell.setPadding(5);
                mainTable.addCell(subTableCell);

            }
            if (qrList.size() % 4 != 0) {
                int noOfdummyCells = 4 - (qrList.size() % 4);
                for (int i = 0; i < noOfdummyCells; i++) {
                    dummyCell = new PdfPCell();
                    dummyCell.setBorderWidth(0);
                    mainTable.addCell(dummyCell);
                }
            }
            document.add(mainTable);
            document.close();
        return os;
    }

    public static String trimLength(String value, int limit) {
        if (value != null) {
            String temp = value.trim();
            if (value.length() >= limit) {
                temp = value.substring(0, (limit - 3));
                temp = temp + "...";
            }
            return temp;
        } else {
            return " ";
        }
    }

    /**
     * To Generate QR Code Image from text
     * 
     * @param qrCodeData
     *            - text for QR Code image
     * @param charset
     * @param qrCodeheight
     *            - QR Code image height
     * @param qrCodewidth
     *            - QR Code image width
     * @return
     * @throws WriterException
     * @throws IOException
     * @throws com.google.zxing.WriterException
     */
    public static BufferedImage createQRCode(String qrCodeData, String charset,
            int qrCodeheight, int qrCodewidth) throws WriterException,
            IOException, com.google.zxing.WriterException {
        // Generate BitMatrix
        com.google.zxing.common.BitMatrix matrix = new MultiFormatWriter()
                .encode(new String(qrCodeData.getBytes(charset), charset),
                        BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // Converting BitMatrix to Buffered Image
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

}
Read More
This article was inspired by Google Login Form UI. This below UI is simple and it displays Login, Register and Forgot-Password panel in on same screen.

Form Structure

<form class="panel" id='login' action='' method='post'>
    ..........
</form>
<form class="panel" id='forgotpassword' action='' method='post'>
    ..........
</form>
<form class="panel" id='register' action='' method='post'>
    .........
</form>

Switch Panel Triggers 

<a class="switchPanelButton" panelclass="panel" panelid="forgotpassword" href="#"> Forgot password </a>

jQuery Code to Switch Panels 

$(".switchPanelButton").click(function(event){
    event.preventDefault();
    var panel = $(this).attr('panelclass');
    $("."+panel).hide();
    var panelid = $(this).attr('panelid');
    $("#"+panelid).show();
});
Read More
QR code is getting famous because of its easy readable nature. You can take snapshot and get the data from it. Now its time to generate PDF file with full QR codes.

Libraries we need 

Libraries needed for QR Code generation
  1. zxing-core-1.7.jar
  2. zxing-j2se-1.7.jar
Libraries needed for PDF generation
  1. itextpdf-5.5.0

Code to generate QR code

    /**
     * To Generate QR Code Image from text
     * @param qrCodeData - text for QR Code image
     * @param charset 
     * @param qrCodeheight - QR Code image height
     * @param qrCodewidth - QR Code image width
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static BufferedImage createQRCode(String qrCodeData, String charset,
            int qrCodeheight, int qrCodewidth) throws WriterException,
            IOException {
        // Generate BitMatrix
        BitMatrix matrix = new MultiFormatWriter().encode(
                new String(qrCodeData.getBytes(charset), charset),
                BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // Converting BitMatrix to Buffered Image 
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

Code to generate PDF file

Document document = new Document();
        
// Get file
PdfWriter.getInstance(document, new FileOutputStream("qrcode.pdf"));
document.open();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
// Get QR code for "Hello"
BufferedImage bi = createQRCode("Hello","UTF-8", 200, 200);
ImageIO.write(bi, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
Image image = Image.getInstance(imageInByte);

// Add image to PDF document
document.add(image);
document.close();

Java class for Exporting QR Codes to PDF files



import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class ExporToPDF {
    // color codes
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static void main(String[] args) throws WriterException, IOException,
            NotFoundException {
        
        String charset = "UTF-8"; // or "ISO-8859-1"
        Document document = new Document();
        String filePath="qrcode.pdf";
        try {
            
            // Get file
            PdfWriter.getInstance(document, new FileOutputStream("qrcode.pdf"));
            document.open();
            
            // data to covert to QR code
            String[] qrdata = {"srinivas","dasari","blog.sodhanalibrary.com","pojo.sodhanalibrary.com","flaticon.sodhanalibrary.com","google","facebook","reddit","blogger","yourname"};
            float x = 100f, y = 830f, posx, posy;
            int n=0;
            for (int j = 0; j < 5; j++) {
                posy = y - j * 200f;
                for (int i = 0; i < 2; i++) {
                    posx = x + i * 200f;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    
                    // Get QR code
                    BufferedImage bi = createQRCode(qrdata[n], charset, 200, 200);
                    ImageIO.write(bi, "png", baos);
                    baos.flush();
                    byte[] imageInByte = baos.toByteArray();
                    baos.close();
                    Image image = Image.getInstance(imageInByte);
                    image.setAbsolutePosition(posx, posy);
                    
                    // Add image to PDF document
                    document.add(image);
                    n++;
                }
            }
            document.close();
            System.out.println(new File(filePath).getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * To Generate QR Code Image from text
     * @param qrCodeData - text for QR Code image
     * @param charset 
     * @param qrCodeheight - QR Code image height
     * @param qrCodewidth - QR Code image width
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static BufferedImage createQRCode(String qrCodeData, String charset,
            int qrCodeheight, int qrCodewidth) throws WriterException,
            IOException {
        
        // Generate BitMatrix
        BitMatrix matrix = new MultiFormatWriter().encode(
                new String(qrCodeData.getBytes(charset), charset),
                BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        
        // Converting BitMatrix to Buffered Image 
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
    
}

Read More
By using Hours and Minutes rotation animation keyframes we can create Clock Loader.

Markup

<div class="panel">
    <div class="b-loader"></div>
</div>

CSS3

.panel {
  background:#2fc7f7;
  position:relative;
}

.b-loader {
  width: 84px;
  height: 84px;
  border: 2px solid #ffffff;
  border-radius: 50%;
  position: absolute;
  z-index: 60;
  top: 50px;
  left: 50%;
  margin-left: -44px;
}


.b-loader:before,
.b-loader:after {
  content: ' ';
  background: url(/img/loader-arrow.png) 50% 50% no-repeat;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}


.b-loader:before {
  -o-animation: fxRotateMinute 500ms linear infinite;
  -moz-animation: fxRotateMinute 500ms linear infinite;
  -webkit-animation: fxRotateMinute 500ms linear infinite;
  -webkit-animation: fxRotateMinute 500ms linear infinite;
}

.b-loader:after {
  -o-animation: fxRotateHour 3000ms linear infinite;
  -moz-animation: fxRotateHour 3000ms linear infinite;
  -webkit-animation: fxRotateHour 3000ms linear infinite;
  -webkit-animation: fxRotateHour 3000ms linear infinite;
}

@-o-keyframes fxRotateMinute {
  from {
    -o-transform: rotate(0);
  }
  to {
    -o-transform: rotate(1turn);
  }
}
@-moz-keyframes fxRotateMinute {
  from {
    -moz-transform: rotate(0);
  }
  to {
    -moz-transform: rotate(1turn);
  }
}
@-webkit-keyframes fxRotateMinute {
  from {
    -webkit-transform: rotate(0);
  }
  to {
    -webkit-transform: rotate(1turn);
  }
}
@-webkit-keyframes fxRotateMinute {
  from {
    -webkit-transform: rotate(0);
  }
  to {
    -webkit-transform: rotate(1turn);
  }
}

@-o-keyframes fxRotateHour {
  from {
    -o-transform: rotate(0.25turn);
  }
  to {
    -o-transform: rotate(1.25turn);
  }
}
@-moz-keyframes fxRotateHour {
  from {
    -moz-transform: rotate(0.25turn);
  }
  to {
    -moz-transform: rotate(1.25turn);
  }
}
@-webkit-keyframes fxRotateHour {
  from {
    -webkit-transform: rotate(0.25turn);
  }
  to {
    -webkit-transform: rotate(1.25turn);
  }
}
@-webkit-keyframes fxRotateHour {
  from {
    -webkit-transform: rotate(0.25turn);
  }
  to {
    -webkit-transform: rotate(1.25turn);
  }
}
Read More
We can design menu button in an interactive way like displaying different shapes with animation . Observe the below diagram for shapes with user actions.

HTML Markup 

<div class="side-nav">
  <button class="navbar-toggle">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar top"></span>
    <span class="icon-bar middle"></span>
    <span class="icon-bar bottom"></span>
  </button>
  <div class="menuPanel">
  </div>
</div>

CSS 

.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    margin: -1px;
    padding: 0;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    border: 0
}

.navbar-toggle {
    position: relative;
    float: right;
    margin-right: 15px;
    padding: 9px 10px;
    margin-top: 23px;
    margin-bottom: 23px;
    border: 1px solid transparent;
    border-radius: 1px;
    cursor:pointer;
    z-index:1;
}

.navbar-toggle:focus {
    outline: none
}

.navbar-toggle .icon-bar {
    display: block;
    width: 22px;
    height: 2px;
    border-radius: 1px
}

.navbar-toggle .icon-bar+.icon-bar {
    margin-top: 4px
}

.navbar-toggle {
    display: block;
    background: #2fc7f7;
    float: none;
    width: 75px;
    height: 75px;
    border-radius: 0;
    margin-right: 15px;
    padding: 10px 15px;
    margin-top: 8px;
    margin-bottom: 8px
}

.navbar-toggle:hover {
    -webkit-transition: margin-bottom 500ms ease-in-out;
    transition: margin-bottom 500ms ease-in-out
}

.navbar-toggle:hover span.icon-bar {
    position: relative
}

.navbar-toggle:hover span.icon-bar.top {
    top: 7.5px;
    -webkit-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg)
}

.navbar-toggle:hover span.icon-bar.middle {
    left: 0px;
    position: relative
}

.navbar-toggle:hover span.icon-bar.bottom {
    bottom: 7.5px;
    position: relative;
    -webkit-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    transform: rotate(-90deg)
}

.navbar-toggle span.icon-bar {
    background: #fff;
    display: block;
    width: 40px;
    height: 4px;
    border-radius: 1px;
    -webkit-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transition: all 300ms ease-in-out;
    transition: all 300ms ease-in-out
}

.navbar-toggle.active {
    -webkit-transition: all 300ms ease-in-out;
    transition: all 300ms ease-in-out
}

.navbar-toggle.active span.icon-bar {
    position: relative;
    -webkit-transition: all 300ms ease-in-out;
    transition: all 300ms ease-in-out
}

.navbar-toggle.active span.icon-bar.top {
    -webkit-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    transform: rotate(-45deg);
    top: 0px
}

.navbar-toggle.active span.icon-bar.middle {
    width: 0;
    height: 0;
    margin: 0 auto
}

.navbar-toggle.active span.icon-bar.bottom {
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
    margin: 0;
    top: -4px;
}
.menuPanel {
    background: #2fc7f7;
    font-size:40px;
    padding:60px 40px 40px 80px;
    display:none;
    position:absolute;
    top:0px;
    color:#fff;
    line-height:60px;
}

.side-nav {
    position:relative;
    margin:auto;
    width:500px;
}

.side-nav a{
    color:#fff;
    text-decoration:none;
}

jQuery Code

$(function(){
    $(".navbar-toggle").click(function(){
        $(this).toggleClass("active");
        $(this).next(".menuPanel").slideToggle();
    });
});
Read More
I built many web applications with java and tomcat server. I came across so many problems in handling the flow of programs. Atlast I figured out this below standard way.

Some Standards

  1. Catch exception when you can continue with remaining program  ( Closing statement wont break the process, so you can continue with remaining program)
  2. Throw exception when you can't continue with remaining program  ( Failing to get Database connection will break the process, so you can not continue with remaining program)
  3. Its better to catch exceptions at Servlet, so that it is possible to give appropriate message to user
  4. To avoid SQL Injection attack, Use PreparedStatement to execute queries
  5. Use one Java Class to creating and closing Connections and Statements.
  6. Use one Java Class to execute all queries
  7. Its better to use Pojo classes to carry out data.

DBConn.java

This Java Class is to create Connections and Closing connections and statements.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author srinivas
 * This file is to create Connections and Closing connections and statements.
 */
public class DBConn {
    Connection con = null;
    static String className = "class sodhana.sdb.connection.DBConnection";

    /**
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     * To Create Connections
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = null;
        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/world", "root", "srinivas");
        return connection;
    }

    /**
     * @param con
     * @param stmt
     * @param rs
     * To close statements, result sets and Connection 
     */
    public static void close(Connection con, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param con
     * @param stmt
     * To close statements and Connection
     */
    public static void close(Connection con, Statement stmt) {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param con
     * @param pstmt
     * @param rs
     * To Close PreparedStatement and Connection
     */
    public static void close(Connection con, PreparedStatement pstmt,
            ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param con
     * To close connection
     */
    public static void closeConnection(Connection con) {
        try {
            if (con != null)
                con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param conn
     * @throws SQLException
     * To Commit and Close the connection
     */
    public static void commitAndClose(Connection conn) throws SQLException {
        conn.commit();
        conn.close();
    }

}

Exception Class for Database Exceptions

Whenever we need to throw an exception, throw the this exception.
public class DBException extends Exception {

    private static final long serialVersionUID = 1L;

    private String message;

    public DBException(String string) {
        message = string;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
}

Example

Lets take an example of Employee Table which consists of ID and Name.

EmployeeDAO.java

This java class is for executing all type of  SQL Queries. This is Data Access Object for above Employee Table
public class EmployeeDAO {

    /**
     * @throws DBException 
     * @throws ClassNotFoundException
     * @throws SQLException
     * To Create Table
     */
    public static void createTable() throws DBException {
        Connection conn = null;
        Statement s = null;
        try {
            conn = DBConn.getConnection();
            s = conn.createStatement();
            s.executeUpdate("create table EMP(id varchar(30),name varchar(200),primary key(id))");
            DBConn.close(conn, s);
        } catch (SQLException | ClassNotFoundException e) {
            DBConn.close(conn, s);
            throw new DBException("Excepion while accessing database");
        }

    }

    /**
     * To Drop Table
     * @throws DBException 
     */
    public static void dropTable() {
        Connection conn = null;
        Statement s = null;
            try {
                conn = DBConn.getConnection();
                s = conn.createStatement();
                s.executeUpdate("drop table EMP");
                DBConn.close(conn, s);
            } catch (ClassNotFoundException | SQLException e) {
                DBConn.close(conn, s);
            }
    }

    /**
     * @param emp
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * To Insert Into Data into Table
     */
    public static void insertRow(EmployeePojo emp) throws DBException{
        Connection conn = null;
        PreparedStatement psInsert = null;
        try {
            conn = DBConn.getConnection();
            psInsert = conn.prepareStatement("insert into "
                    + "EMP(id,name) values (?,?)");
            psInsert.setString(1, emp.getId());
            psInsert.setString(2, emp.getName());
            psInsert.executeUpdate();
            DBConn.close(conn, psInsert);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, psInsert);
            throw new DBException("Excepion while accessing database");
        }
    }

    /**
     * @param emp
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * Update data in EMP table
     */
    public static void updateRow(EmployeePojo emp) throws DBException{
        Connection conn = null;
        PreparedStatement psInsert = null;
        try {
            conn = DBConn.getConnection();
            psInsert = conn
                    .prepareStatement("update EMP set name = ? where id = ?");
            psInsert.setString(2, emp.getId());
            psInsert.setString(1, emp.getName());
            psInsert.executeUpdate();
            DBConn.close(conn, psInsert);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, psInsert);
            throw new DBException("Excepion while accessing database");
        }
    }

    /**
     * @param emp
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * To Insert or Update Table
     */
    public static void insertOUpdateRow(EmployeePojo emp) throws DBException{
        if(searchEmployee(emp.getId())){
            updateRow(emp);
        } else {
            insertRow(emp);
        }
    }

    /**
     * @param conn
     * @param id
     * @throws DBException 
     * @throws SQLException
     * To delete data from Table
     */
    public static void deleteRow(String id){
        Connection conn = null;
        PreparedStatement psInsert = null;
        try {
            conn = DBConn.getConnection();
            psInsert = conn
                    .prepareStatement("delete from EMP where id=?");
            psInsert.setString(1, id);
            psInsert.executeUpdate();
            psInsert.close();
            DBConn.close(conn, psInsert);
        } catch (SQLException | ClassNotFoundException e) {
            DBConn.close(conn, psInsert);
        }
    }

    /**
     * @param id
     * @return
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * Read data from Table
     */
    public static EmployeePojo selectEmployee(String id) throws DBException {
        Connection conn = null;
        PreparedStatement psInsert = null;
        ResultSet res=null;
        EmployeePojo emp = new EmployeePojo();
        try {
            conn = DBConn.getConnection();
            psInsert = conn
                    .prepareStatement("select * from EMP where id = ?");
            psInsert.setString(1, id);
            res = psInsert.executeQuery();
            if (res != null) {
                while (res.next()) {
                    emp.setId(res.getString(1));
                    emp.setName(res.getString(2));
                }
            }
            DBConn.close(conn, psInsert, res);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, psInsert, res);
            throw new DBException("Excepion while accessing database");
        }
        return emp;
    }

    /**
     * @param id
     * @return
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * To search data
     */
    public static boolean searchEmployee(String id) throws DBException{
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        boolean b = false;
        try {
            conn = DBConn.getConnection();
            ps = conn
                    .prepareStatement("select * from EMP where id = ?");
            ps.setString(1, id);
            res = ps.executeQuery();
            if (res != null) {
                while (res.next()) {
                    b = true;
                }
            }
            DBConn.close(conn, ps, res);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, ps, res);
            throw new DBException("Excepion while accessing database");
        }
        return b;
    }

    /**
     * Droping and Creating Table
     * @throws DBException 
     */
    public static void resetEMP() throws DBException {
            EmployeeDAO.dropTable();
            EmployeeDAO.createTable();
    }

    /**
     * @param args
     * @throws DBException 
     */
    public static void main(String args[]) throws DBException {
        resetEMP();
    }

}

EmployeePojo.java

Use this class to carry information
public class EmployeePojo {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

}

Call DAO from Servlet 

This is the most important part.  If user requests for Insert operation, call insert function in EmployeeDAO.java. If query execution is successful then write success response to user. If query execution is not successful then catch the exception and write failure response to user.
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            EmployeePojo emp = EmployeeDAO.selectEmployee(id);
            String message = " Employee id : "+id +" ----- Employee name : "+emp.getName();
            request.setAttribute("message", message);
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        } catch (DBException e) {
            e.printStackTrace();
            String message = " Database exception ";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }

Read More

Search This Blog

Loading...

Blogroll

Srinivas Dasari
find me on facebook
follow me on twitter

Follow by Email

Popular Posts