Monday, 17 June 2013

Pagination in JSP and Servlet


Pagination in JSP and Servlet

What is Pagination ?

  • Fetching millions of records from database consumes almost all CPU power and memory of machine.
  • Hence we break millions of records into small chunks showing limited number of records (say 10 or 20) per page. The best example of this is Google search pagination which allows user to navigate to next page by page number and explore limited records per pages.

  Steps for creating pagination in jsp and servlet.

Step 1 : First You have to create employee  table in mysql database.

The structure of employee table is as

CREATE TABLE `employee` (
  `emp_id` int(10) NOT NULL,
  `emp_name` varchar(50) DEFAULT NULL,
  `salary` double DEFAULT NULL,
  `department` varchar(50) DEFAULT NULL,
  `state` varchar(50) DEFAULT NULL,
  `city` varchar(50) DEFAULT NULL,
  `country` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Step 2 :  Download mysql connector and jstl jar and include in WEB-INF/lib folder

Step 3 : Writing transfer object class as Employee

package test.paging;

public class Employee {
private int id;
private String name;
    private double salary;
    private String department;
    private String state;
    private String city;
    private String country;
    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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

}

Step 4 : Writing Connection Factory Class

package test.paging;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
//static reference to itself
    private static ConnectionFactory instance =new ConnectionFactory();
    String url = "jdbc:mysql://localhost/test";
    String user = "root";
    String password = "admin1&$$31223";
    String driverClass = "com.mysql.jdbc.Driver"; 
    //private constructor
    private ConnectionFactory() {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static ConnectionFactory getInstance()   {
        return instance;
    }
    public Connection getConnection() throws SQLException,ClassNotFoundException {
        Connection connection =DriverManager.getConnection(url, user, password);
        return connection;
    }
}

Step 5 : Writing DAO Class

package test.paging;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class EmployeeDAO {
Connection connection;
    Statement stmt;
    private int noOfRecords;
    public EmployeeDAO() { 
   
    }
    private static Connection getConnection() throws SQLException,ClassNotFoundException {
        Connection con = ConnectionFactory.getInstance().getConnection();
        return con;
    }
    public List<Employee> viewAllEmployees(int offset,int noOfRecords)
    {
        String query = "select SQL_CALC_FOUND_ROWS * from employee limit "+ offset + ", " + noOfRecords;
        System.out.println("EmployeeDAO.viewAllEmployees()"+query);
        List<Employee> list = new ArrayList<Employee>();
        Employee employee = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                employee = new Employee();
                employee.setId(rs.getInt("emp_id"));
                employee.setName(rs.getString("emp_name"));
                employee.setSalary(rs.getDouble("salary"));
                employee.setDepartment(rs.getString("department"));
                employee.setState(rs.getString("state"));
                employee.setCity(rs.getString("city"));
                employee.setCountry(rs.getString("country"));
                list.add(employee);
            }
            rs.close();
            rs = stmt.executeQuery("SELECT FOUND_ROWS()");
            if(rs.next())
                this.noOfRecords = rs.getInt(1);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally
        {
            try {
                if(stmt != null)
                    stmt.close();
                if(connection != null)
                    connection.close();
                } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    public int getNoOfRecords() {
        return noOfRecords;
    }
}

Step 6 : Writing Servlet :

package test.paging;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EmployeeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public EmployeeServlet() {
            super();
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int recordsPerPage = 5;
        if(request.getParameter("page") != null){
            page = Integer.parseInt(request.getParameter("page"));
        }
        EmployeeDAO dao = new EmployeeDAO();
        List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,recordsPerPage);
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view = request.getRequestDispatcher("display.jsp");
        view.forward(request, response);
    }
}

Step 7 : Writing web.xml as

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javae
    /web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JSPPagination</display-name>
  <servlet>
    <servlet-name>EmployeeServlet</servlet-name>
    <servlet-class>test.paging.EmployeeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeServlet</servlet-name>
    <url-pattern>/employee.do</url-pattern>
  </servlet-mapping>
</web-app>

Step 8 : Writing display.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employees</title>
</head>

<body>
   <table border="1" cellpadding="5" cellspacing="5">
        <tr>
            <th>Employee ID</th>
            <th>Empployee Name</th>
            <th>Salary</th>
            <th>Department</th>
            <th>State</th>
            <th>City</th>
            <th>Country</th>
        </tr>
        <c:forEach var="employee" items="${employeeList}">
            <tr>
                <td>${employee.id}</td>
                <td>${employee.name}</td>
                <td>${employee.salary}</td>
                <td>${employee.department}</td>
                <td>${employee.state}</td>
                  <td>${employee.city}</td>
                    <td>${employee.country}</td>
            </tr>
        </c:forEach>
    </table>
     <table border="0" cellpadding="0" cellspacing="0">
     <td>
 <%--For displaying Previous link except for the 1st page --%>
    <c:if test="${currentPage != 1}">
       <!--  <td> --><a href="employee.do?page=${currentPage - 1}">&nbsp;Previous</a><!-- </td> -->
    </c:if>
    <%--For displaying Page numbers.
    The when condition does not display a link for the current page--%>
    <!-- <table border="1" cellpadding="5" cellspacing="5"> -->
       <!--  <tr> -->
            <c:forEach begin="1" end="${noOfPages}" var="i">
                <c:choose>
                    <c:when test="${currentPage eq i}">
                        <!-- <td> -->${i}&nbsp;&nbsp;<!-- </td> -->
                    </c:when>
                    <c:otherwise>
                       <!--  <td> --><a href="employee.do?page=${i}">${i}&nbsp;</a><!-- </td> -->
                    </c:otherwise>
                </c:choose>
            </c:forEach>
       <!--  </tr> -->
   
    <%--For displaying Next link --%>
    <c:if test="${currentPage lt noOfPages}">
       <!--  <td> --><a href="employee.do?page=${currentPage + 1}">&nbsp;Next</a><!-- </td> -->
    </c:if>
    </td>
  </table>
</body>
</html>

Step 9 : Deploy all files in tomcat container

Step 10 : Start the tomcat

Step 11 : Access the page in browser 

http://localhost:8080/paging/employee.do

Step 12 : The Output are :

Employee IDEmpployee NameSalaryDepartmentStateCityCountry
6shyama72363.0media salesupbiharindia
7rahima387483.0techopsupbiharindia
8rahima387483.0upindia
9rahima387483.0upindia
10rahima387483.0upindia
 Previous  2     Next


Thanks & Regards


Friday, 14 June 2013

How To Access Private Members of a Java class using Reflection


How To Access Private Members of a Java class using Reflection


How To Access Private Members of a Java class using Reflection.


java.lang.reflect package provides the AccessibleObject class that is parent class of Constructor, Method, and Field class. Using the AccessibleObject class, we can change the access control flags of a Reflection Object (Reflection is a feature in the Java programming language. It allows an executing Java program to examine or “introspect” upon itself, and manipulate internal properties of the program. For example, it’s possible for a Java class to obtain the names of all its members and display them.), and the setAccessible(boolean)method is used to change the access control flag of an Object.

For Example :


package test;

public class PrivateAccessMember {
private int privateInt = 10;
private String privateString = "temp String";
private long privateLong = 1234567890L;
private void resetFields(int i, String s, long l) {
privateInt = i;
privateString = s;
privateLong = l;
}
public void display() {
System.out.println("Int = " + privateInt);
System.out.println("String = " + privateString);
System.out.println("Long = " + privateLong);
}

}


package test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestPrivateMember {
public static void main(String[] args) {
PrivateAccessMember obj = new PrivateAccessMember();
obj.display();
Class clazz = obj.getClass();
try {
Field intField = clazz.getDeclaredField("privateInt");
Field strField = clazz.getDeclaredField("privateString");
Field longField = clazz.getDeclaredField("privateLong");
intField.setAccessible(true);
strField.setAccessible(true);
longField.setAccessible(true);
System.out.println("value of privateInt field is : " + intField.get(obj));
System.out.println("value of privateString field is : " + strField.get(obj));
System.out.println("value of privateLong field is : " + longField.get(obj));
intField.set(obj, 100);
strField.set(obj, "this is new string");
longField.set(obj, 55555L);
obj.display();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
Method method = clazz.getDeclaredMethod("resetFields", int.class, String.class, long.class);
method.setAccessible(true);
method.invoke(obj, 25, "new String from resetField method.", 987654321L);
obj.display();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}


The Output are :

Int = 10
String = temp String
Long = 1234567890
value of privateInt field is : 10
value of privateString field is : temp String
value of privateLong field is : 1234567890
Int = 100
String = this is new string
Long = 55555
Int = 25
String = new String from resetField method.
Long = 987654321

Friday, 7 June 2013

Restore Mysql Database by Physical files

Restore Mysql Database by Physical files

When you want to move whole database schema and data, then you
Follows the following steps
Step 1 : Stop the database on server you want to move database.
Step 2 : Go to the directory where mysql data are ie data dir
Step 3 : Transfer over the folder (and its contents) over to the new server's mysql data directory
Step 4 : Start back up the database. And then start the mysql server
Step 5 : On the new server, issue a 'create database' command.'
Step 6 : Re-create the users & grant permissions.

Or
For existing user from old server
grant all privileges on *.* to root@'%' identified by 'admin123';
flush privileges;
or
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION; 

If you want to move database with replication then you have to move physical files
From master to new server 1 and replica to new replication server 2
Check all is working fine, then you have to configure
Replication for master to slave on new servers

The second way to restore the database to new server is pipe a mysqldump command to a sql command, You can do all databases or a specific one. So, for instance,

mysqldump -uuser -ppassword myDatabase | mysql -hremoteserver -uremoteuser -premoteserver

You can do all databases with
mysqldump --all-databases -uuser -ppassword | mysql -hremoteserver -uremoteuser -premoteserver 
 

If you just want to move a specific table try:

mysqldump -u username -ppassword databasename tablename > databasename.tablename.sql

You can specify more table names above, in the same command. Once the command completes, move the databasename.tablename.sql file to the other server and then restore using:


mysql -u username -ppassword databasename < databasename.tablename.sql

Thursday, 6 June 2013

How to install and configure FileZilla FTP server on windows

How to install and configure FileZilla FTP server on windows

1. Download from following link.

https://filezilla-project.org/

2. Run the exe installer

3. Select admin port and remember this port

4. Launch FileZilla Server Interface

5. Enter port from above, enter (new) password for administration, click ok/connect

6. Create a user and/or group with permissions to a home directory.

7. Add additional directory and set the alias name to display within home directory (e.g. /AliasName)

Setup Firewall in Windows 2008
=====================

1. Open "Windows Firewall with Advanced Security"

2. Click "New Rule" in right pane under "Inbound Rules"

3. Select Program and click "Next"

4. Browse C:\Program Files (x86)\FileZilla Server\FileZilla server.exe and click "Next"

5. Choose "Allow the connection" and click "Next"

6. Choose Domain, Private & Public and cli ck "Next"

7. Give name as "Filezilla Server Ports" and click "Finish"

Setup Firewall in Windows 2003
=====================

1. Open Control panel

2. Click "Windows Firewall"

3. Click "Exceptions" Tab

4. Click "Add Programs"

5. Browse C:\Program Files\FileZilla Server\FileZilla server.exe


==================================================

1 : Open FileZilla Client on client machine
2 : Put Hostname, username,password,port
3 : Click quickconnect button
4 : After Successful connection
5 : Download/Upload files

Friday, 31 May 2013

How to send HTTPRequest GET/POST Using Java or HttpClient

How to send HTTPRequest GET/POST Using Java or HttpClient

In this article I will show you with example of GET/POST Request via standard Java and apache client library.
I.e.  HttpURLConnection and HttpClient library.


1  : Java HttpURLConnection 

for example

package test.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionTest {

/**
* @param args
*/
public static void main(String[] args) {
HttpURLConnectionTest http=new HttpURLConnectionTest();
//http.sendGETRequest();
http.sendPOSTRequest();

}
private void sendGETRequest(){
String url = "http://www.google.com";
try{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("Sending GET request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}catch(Exception ex){
ex.printStackTrace();
}
}
private void sendPOSTRequest(){
String url = "http://www.mginger.com/login.jsp";
try{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
//con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "j_username=wakil&j_password=ahamad123343";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Sending POST request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

//print result
System.out.println(response.toString());
}catch(Exception ex){
ex.printStackTrace();
}
}

}

When you run the following output comes here :

Sending GET request to URL : http://www.google.com
Response Code : 200
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><title>Google</title><script>(function(){window.google={kEI:"CpupUZyyA4SIrAf164GQDA",getEI:function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI},https:function()

-------------------------------------------------
-------------------------------------------------


Sending POST request to URL : http://www.mginger.com/login.jsp
Post parameters : j_username=wakil&j_password=ahamad123343
Response Code : 200
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Get Deals | Earn Rewards | Free SMS | Games | Coupons - mGinger.com</title> <style type="text/css">            @import "/mobile/css/style.css"; </style> 
--------------------------------------------------
--------------------------------------------------
</html>


2 : HttpClient 

for example 

package test.http;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpClientTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HttpClientTest http=new HttpClientTest();
http.sendGETRequest();
http.sendPOSTRequest();
}
// HTTP GET request
private void sendGETRequest() throws Exception {
 
String url = "http://www.google.com/search?q=developer";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
 
HttpResponse response = client.execute(request);
 
System.out.println("Sending GET request to URL : " + url);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
 
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
 
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
 
System.out.println(result.toString());
 
}
 
// HTTP POST request
private void sendPOSTRequest() throws Exception {
 
String url = "http://www.mginger.com/login";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
 
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("j_username", "wakil"));
urlParameters.add(new BasicNameValuePair("j_password", "qwqweqe"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Sending POST request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
 
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
 
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
 

}