Thursday, 30 May 2013

Generate Report in java using DynamicReports and JasperReports

Generate Reports in java using DynamicReports and JasperReports

This example shows you how to generate a simple report using DynamicReports and JasperReports
For developing this you must need to download DynamicReports the library and include it into their classpath. It allows you to produce documents that can be exported into many popular formats, It is based on JasperReport library.
1 : Create a DataSource and use it into report generation as
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection(“jdbc:mysql://hostname:port/dbname”,”username”,”password”);
2 : Suppose mysql server contains a database test having table customer having fields
The table customer having fields
Column name
Data type
id
int
first_name
varchar(50)
last_name
varchar(50)
Created_date
datetime
age
int

We will create  report that will get all customers from the table and the data will be put into the report.

3 :Create a empty report object

JasperReportBuilder report = DynamicReports.report();

4: Now create a report colum for each database column

Columns.column("Customer Id", "id", DataTypes.integerType());
Where first parameter is column level
Second parameter is actual table field which is same as table column name.
Third parameter is datatype

5 : Add the report columns.

report
  .columns(
    Columns.column("Customer Id", "id", DataTypes.integerType()),
    Columns.column("First Name", "first_name", DataTypes.stringType()),
    Columns.column("Last Name", "last_name", DataTypes.stringType()),
    Columns.column("Created Date", "date", DataTypes.dateType()))
    Columns.column("Customer Age", "age", DataTypes.integerType()))

6 : Add a title text and page number to a report

.title(//title of the report
    Components.text("SimpleReportExample")
      .setHorizontalAlignment(HorizontalAlignment.CENTER))
  .pageFooter(Components.pageXofY())//show page number on the page footer

7 : Finally set the datasource query and connection

.setDataSource("SELECT id, first_name, last_name, created_date,age FROM customers ", connection);
Now below the full example here.
SimpleReportTest.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;
public class DynamicSimpleTest {
  public static void main(String[] args) {
            Connection connection = null;
            try {
                        Class.forName("com.mysql.jdbc.Driver");
                        connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test","root", "admin123");
            } catch (SQLException e) {
                        e.printStackTrace();
                        return;
            } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        return;
            }
            JasperReportBuilder report = DynamicReports.report();//a new report
            report
              .columns(
                  Columns.column("Customer Id", "id", DataTypes.integerType()),
                  Columns.column("First Name", "first_name", DataTypes.stringType()),
                  Columns.column("Last Name", "last_name", DataTypes.stringType()),
                  Columns.column("Created_date", "created_date", DataTypes.dateType()),
                  Columns.column("Customer Age","age",DataTypes.integerType()))
                 

              .title(//title of the report
                  Components.text("SimpleReportExample")
                          .setHorizontalAlignment(HorizontalAlignment.CENTER))
                          .pageFooter(Components.pageXofY())//show page number on the page footer
                          .setDataSource("SELECT id, first_name, last_name, created_date,age FROM customers",
                                  connection);

            try {
                //show the report
                        report.show();

                //export the report to a pdf file
                        report.toPdf(new FileOutputStream("d:/report1.pdf"));
            } catch (DRException e) {
                        e.printStackTrace();
            } catch (FileNotFoundException e) {
                        e.printStackTrace();
            }
  }
After Running It, It generates a report in pdf as below.

Output is here :








Wednesday, 29 May 2013

How to use jcaptcha image service in our application

How to use jcaptcha image service in our application
How to install it
For maven users, you need to add the following dependency in your pom file.
<dependency>
    <groupId>com.octo.captcha</groupId>
    <artifactId>jcaptcha</artifactId>
    <version>1.0</version>
</dependency>
For without maven2 users
Add jcaptcha-all.jar (provided in bin-distribution) and commons-collection-3.2 or greater  to your application class path, i.e. in your WEB-INF/lib.
Implement a CaptchaService, It must be a singleton
package com.jcaptcha.test;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;
public class CaptchaServiceSingleton {
private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();
    public static ImageCaptchaService getInstance(){
        return instance;
    }
}

Create a servlet for captcha image.

package com.jcaptcha.test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageCaptchaServlet extends HttpServlet {
       private static final long serialVersionUID = 1L;
       public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
    }

    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
       byte[] captchaChallengeAsJpeg = null;
       // the output stream to render the captcha image as jpeg into
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
        // get the session id that will identify the generated captcha.
        //the same id must be used to validate the response, the session id is a good candidate!
        String captchaId = httpServletRequest.getSession().getId();
        // call the ImageCaptchaService getChallenge method
            BufferedImage challenge = CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,httpServletRequest.getLocale());
            // a jpeg encoder
            JPEGImageEncoder jpegEncoder =JPEGCodec.createJPEGEncoder(jpegOutputStream);
            jpegEncoder.encode(challenge);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (CaptchaServiceException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        // flush it in the response
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

}


In web.xml  You can add this as
<?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">
  <display-name></display-name>
  <servlet>
        <servlet-name>jcaptcha</servlet-name>
        <servlet-class>ImageCaptchaServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>

  <servlet-mapping>
        <servlet-name>jcaptcha</servlet-name>
        <url-pattern>/jcaptcha</url-pattern>
    </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


In the form you must add this to display captcha image and input text box for submitting
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
//String path = request.getContextPath();
//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>JCaptcha Index Page</title>
      <meta http-equiv="pragma" content="no-cache">
      <meta http-equiv="cache-control" content="no-cache">
      <meta http-equiv="expires" content="0">   
      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
      <meta http-equiv="description" content="How to create Captcha Image Service">
    </head>
 
  <body>
     <img src="jcaptcha">
     <input type='text' name='j_captcha_response' value=''>
  </body>
</html>

For Validation You can Implement validation service as
Handle the post (using a servlet, or whatever).
The validateCaptchaForId method will return true if the response is correct.
           Boolean isResponseCorrect =Boolean.FALSE;
           //remenber that we need an id to validate!
           String captchaId = httpServletRequest.getSession().getId();
           //retrieve the response
           String response = httpServletRequest.getParameter("j_captcha_response");
           // Call the Service method
            try {
                isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
                        response);
            } catch (CaptchaServiceException e) {
                 //should not happen, may be thrown if the id is not valid
           }

The Output are as Below :




Tuesday, 28 May 2013

How to know mysql database size

How to know mysql database size

There are two ways to know the mysql database size

1 : BY SQL Script


Sum of data_length + index_length is equal to the total table size
       data_length – store the real data.
       index_length – store the table index.
Here’s the SQL script to list out the entire databases size
1 : SELECT table_schema "Data Base Name", SUM( data_length + index_length) / 1024 / 1024 
"Data Base Size in MB" FROM information_schema.TABLES GROUP BY table_schema ;

2 : SELECT TABLE_NAME, table_rows, data_length, index_length, 
ROUND(((data_length + index_length) / 1024 / 1024),2) "Size in MB"
FROM information_schema.TABLES WHERE table_schema = "msplash";
Table counts for a database the query is :
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'test';

2. Locate the MySQL stored data

Windows
1) Locate the my.ini, which store in the MySQL installation folder
for example :
C:\Program Files\MySQL\MySQL Server 5.2\my.ini
Open it any text editor

#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.2/"
 
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.2/Data/"
Find the “datadir”, this is the where  MySQL stored the data in Windows.
Linux
1) Locate the my.cnf with the find / -name my.cnf command.
cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
[mysqld]
#
# * Basic Settings
#
user   = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket  = /var/run/mysqld/mysqld.sock
port   = 3306
basedir  = /usr
datadir  = /var/lib/mysql
tmpdir  = /tmp
language = /usr/share/mysql/english
skip-external-locking
3) Find the “datadir”, this is where  MySQL stored the data in Linux system.


Friday, 24 May 2013

Mysql Replication setup for master to slave on windows


Mysql Replication setup for  master to slave on windows
Description :
You can back up your MySQL database using the built-in dump tool, but the second you do that backup is out of date. Since so many companies and web-based tools rely heavily on databases, it’s crucial that those databases are as up-to-date as possible. One very simple solution is database replication, which keeps a real-time copy of the database on a remote server. With this in place, if something happens to the primary database, it will be much easier to get your database back up and running with current information.

The are easy steps to Mysql Replication setup for master to slave on windows
What we need to setup correctly replication on windows are :
1 : Two correctly configured MySQL servers.
2 : Root access and access to the database administrator on both servers.
3 : Ability to work from the command line.
The setup will use two machine master and slave.
First we start setup from master configuration
Suppose 192.168.1.34 is a master and 192.168.1.35 is slave
On Master Machine Configuration
Step 1 : Open the my.ini/my.cnf file and add the following lines below [mysqld]
log-bin=mysql-bin
server-id=1
innodb_flush_log_at_trx_commit=1
sync_binlog=1
binlog-do-db=database_to_be_replicated
Save the my.ini/my.cnf file and restart the mysql server on master machine
For linux : /etc/inid.t/mysqld restart
For windows you can restart from services by control panel.

Step 2 : Setup a user for replication privileges.
Log on to master with root privileges with command line
Mysql –u root –pxxxx
CREATE USER ‘replication_user’@ ‘X.X.X.X’ IDENTIFIED BY ‘password’;

GRANT REPLICATION SLAVE ON *.* TO ‘replication_user’@'X.X.X.X’ IDENTIFIED BY ‘password’;

Replace the X.X.X.X with ip address of slave machine.

Step 3 : To unlock the database do the following commands
FLUSH TABLES WITH READ LOCK;
Now unlock the tables
Show master status to user later
UNLOCK TABLES;

On Slave Configuration :
Mysql Replication setup for  master to slave on windows are as follows

Step 4 : Open the my.ini/my.cnf file from slave server
Add the following lines below [mysqld] line
server-id=2
 
Step 5 : Go to the master and issue the following command as
SHOW MASTER STATUS; 
 
 
mysql> show master status;
+------------------+-----------+--------------+------------------+
| File             | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+-----------+--------------+------------------+
| mysql-bin.000001 | 346934211 |              |                  |
+------------------+-----------+--------------+------------------+
1 row in set (0.00 sec)
 
Step 6 : Again go to the slave machine and issue the following command as
 
STOP SLAVE;
Step 7 : You must run the following command as
 
CHANGE MASTER TO MASTER_HOST=’IP_ADDRESS_OF_MASTER’, MASTER_USER=’USER’, MASTER_PASSWORD=’USER_PASSWORD’, MASTER_LOG_FILE=’mysql-bin.007′, MASTER_LOG_POS=NUMBER;
Where the following applies:
IP_ADDRESS_OF_MASTER is the actual IP address of the Master
USER is the MySQL admin user
USER_PASSWORD is the password for the USER
NUMBER is the Position Number reported from the SHOW MASTER STATUS command.
For Example
 
 
CHANGE MASTER TO 
MASTER_HOST=’192.168.1.34’,
MASTER_USER='replication_user',
MASTER_PASSWORD='password', 
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=346934211;
Save the file and exit.
Step 8 : Restart the Slave by issuing the command 
SLAVE START; 
 
Now you can follow these steps to make sure everything is working fine.
 
SHOW SLAVE STATUS;.
 
 
mysql> show slave status \G
*************************** 1. row *********************
               Slave_IO_State: Waiting for master to sen
                  Master_Host: 192.168.1.34
                  Master_User: replication_user
                  Master_Port: 3306
                Connect_Retry: 10
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 346934211
               Relay_Log_File: WIN-THQO1NKG27F-relay-bin
                Relay_Log_Pos: 785
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 1146
 
In the above output if you see the following
 
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
 
Then all is fine. Replicated MySQL database. 
Congratulations!