Tuesday 29 November 2016

Search Operation in AJAX

index.html

<!DOCTYPE html>
<html>
<head>
<script>
var request=new XMLHttpRequest();
function searchInfo(){
var name=document.vinform.name.value;
var url="index.jsp?val="+name;

try{
request.onreadystatechange=function(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById('mylocation').innerHTML=val;
}
}//end of function
request.open("GET",url,true);
request.send();
}catch(e){alert("Unable to connect to server");}
}
</script>
</head>
<body>
<h1>Search Employee Using Ajax.</h1>
<form name="vinform">
<input type="text" name="name" onkeyup="searchInfo()">
</form>

<span id="mylocation"></span>
</body>
</html>

index.jsp

<%@ page import="java.sql.*" %>
<%
String name=request.getParameter("val");
if(name==null||name.trim().equals(""))
{
out.print("<p>Please enter name!</p>");
}

else
{
try
{
   Class.forName("com.mysql.jdbc.Driver");
    Connection  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "sagan");

PreparedStatement ps=con.prepareStatement("select * from emp where empname like '"+name+"%'");

ResultSet rs=ps.executeQuery();

if(!rs.isBeforeFirst())
{  
 out.println("<p>No Record Found!</p>");
}
else
{
out.print("<table border='1' cellpadding='2' width='50%'>");
out.print("<tr><th>Id</th><th>Name</th><th>Address</th></tr>");
while(rs.next()){
out.print("<tr><td>"+rs.getString(1)+"</td><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"</td></tr>");
}
out.print("</table>");
}//end of else for rs.isBeforeFirst
con.close();
}catch(Exception e){out.print(e);}
}//end of else
%>


Output:







Wednesday 23 November 2016

Log4j

What Is Log4j:
While developing Java/J2EE applications, for debugging an application that is to know the status of a java application at its execution time, in general we use system.out.println statements in the application right…
But we have some disadvantages while using SOPL (system.out.println) statements.
  • Generally SOPL statements are printed on console, so there are temporary messages and when ever the console is closed then automatically the messages are removed from the console
  • It is not possible to store the SOPL messages in a permanent place and these are single threaded model, means these will prints only one by one message on the console screen
  • In order to overcome the problems  of  SOPL statements Log4j came into picture, with Log4j we can store the flow details of  ourJava/J2EE in a file or databases
  • This is a Open Source tool given by Apache, for only java projects, to record or write the status of an application at various places
  • Working with log4j is nothing but working with classes & interfaces given in org.apache.log4j.*
  • Log4j is a common tool, used for small to large scale Java/J2EE projects
  • In Log4j we use log statements rather SOPL statements in the code to know the status of a project while it is executing
  • In real time, after a project is released and it is installed in a client location then we call the location as on-site right, when executing the program at on-site location, if we got any problems occurred then these problems must report to the off showered engineers,  in this time we used to mail these Log files only so that they can check the problems easily

Components of Log4j:
  1. Logger
  2. Appender
  3. Layout

Logger

  • Logger is a class, in org.apache.log4j.*
  • We need to create Logger object one per java class
  • This component enables Log4j in our java class
  • Logger methods are used to generate log statements in a java class instead of sopls
  • So in order to get an object of Logger class, we need to call a static factory method [ factory method will gives an object as return type ]
  • We must create Logger object right after our class name, i will show you 

Getting Logger Object

static Logger log = Logger.getLogger(YourClassName.class.getName())
Note:  while creating a Logger object we need to pass either fully qualified class name or class object as a parameter, class means current class for which we are going to use Log4j.

Logger object has some methods, actually we used to print the status of our application by using these methods only
We have totally 5 methods in Logger class
  • debug()
  • info()
  • warn()
  • error()
  • fatal()

Appender

Appender job is to write the messages into the external file or database or smtp
  • Logger classes generates some statements under different levels right, this Appender takes these log statements and stores in some files or database
  • Appender is an interface
In log4j we have different Appender  implementation classes
  • FileAppender [ writing into a file ]
  • ConsoleAppender [ Writing into console ]
  • JDBCAppender [ For Databases ]
  • SMTPAppender [ Mails ]
  • SocketAppender [ For remote storage ]
  • SocketHubAppender
  • SyslogAppendersends
  • TelnetAppender
Again in FileAppender we have 2 more
  • RollingFileAppender
  • DailyRollingFileAppender
For now just remember, i will explain while executing the program

Layout

This component specifies the format in which the log statements are written into the destination repository by the appender
We have different type of layout classes in log4j
  • SimpleLayout
  • PatternLayout
  • HTMLLayout
  • XMLLayout

Example Program:

import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
 
public class Client 
{
 
  static Logger l = Logger.getLogger(Client.class.getName());
 
  public static void main(String[] args) {  
 
 Layout l1 = new HTMLLayout();
 Appender a;
 //Appender a = new ConsoleAppender(l1);
 try
 {
 a = new FileAppender(l1,"my.txt", false);
 
 // 3rd parameter is true by default
 // true = Appends the data into my.txt
 // false = delete previous data and re-write
 
 l.addAppender(a);
 }
 catch(Exception e) {}  
 
 l.fatal("This is the error message..");
 System.out.println("Your logic executed successfully....");
  }
}




Tuesday 22 November 2016

Serialization and Deserialization in Java

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.


Address.java
import java.io.Serializable;  
class Address implements Serializable
{  
String addressLine,city,state;  
public Address(String addressLine, String city, String state)
 {  
  this.addressLine=addressLine;  
  this.city=city;  
  this.state=state;  
 }  
}  
Student.java
import java.io.Serializable;  
class Student implements Serializable
{  
 int id;  
 String name;  
 Address address; // aggregation
 public Student(int id, String name) 
 {  
  this.id = id;  
  this.name = name;  
 } 
}  

SerializaionTestWithAggregation.java
import java.io.*;  
class SerializaionTestWithAggregation
{  
public static void main(String args[])throws Exception
 {  
  Student s1 = new Student(1,"Sivasankar");  
  Address a1 = new Address("40-R, "Fremont","California ");  
  FileOutputStream fout=new FileOutputStream("serial.txt");  
  ObjectOutputStream out=new ObjectOutputStream(fout);  
  out.writeObject(s1);  
   out.writeObject(a1);   // Remove and run Deserialize u will get EOF
  out.flush();  
  System.out.println("success"); 
 }  
}  

Deserialize.java

import java.io.*; 

class Deserialize
{  
 public static void main(String args[])throws Exception
 {  
    
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("serial.txt"));  
  
  Student s=(Student)in.readObject();  
    Address a =(Address)in.readObject();  
  
  System.out.println(s.id+" "+s.name+" "+a.addressLine+" "+ a.city+" "+a.state);  
  
  in.close();  
 }  

}  

Output:
Run Serialize.java



Run Deserialize.java



Friday 18 November 2016

Byte Stream VS Character Stream File Reader with Elapsed Time Calculation in Java

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.

Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
  • InPutStream − The InputStream is used to read data from a source.
  • OutPutStream − The OutputStream is used for writing data to a destination.
Streams
Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O. We will see the most commonly used examples one by one −

Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are,FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file −
Example:
import java.io.*;
import java.io.IOException;
import java.util.Scanner;

class ElaspedTimetoCopyAFileUsingByteStream
{

    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;
    public void start() 
    {
        this.startTime = System.currentTimeMillis();
        this.running = true;
    }
    public void stop() 
    {
        this.stopTime = System.currentTimeMillis();
        this.running = false;
    }
    public long getElapsedTime() 
    {
        long elapsed;
        if (running) {
             elapsed = (System.currentTimeMillis() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }
        return elapsed;
    }

    public long getElapsedTimeSecs()                 
    {
        long elapsed;
        if (running) 
        {
            elapsed = ((System.currentTimeMillis() - startTime) / 1000);
        }
        else
        {
            elapsed = ((stopTime - startTime) / 1000);
        }
        return elapsed;
    }
    public static void main(String[] args) throws IOException
    {
ElaspedTimetoCopyAFileUsingByteStream  s = new ElaspedTimetoCopyAFileUsingByteStream();
        s.start();

        FileInputStream in = null;
        FileOutputStream out = null;

      try {
         in = new FileInputStream("vowels.txt");   // 23.7  MB File
         out = new FileOutputStream("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
            s.stop();
        System.out.println("elapsed time in seconds: " + s.getElapsedTimeSecs());
    }
}

OutPut   :     elapsed time in seconds:    95secs
Overwrite elapsed time in seconds: 96secs



Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, whereas JavaCharacter streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are,FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −
Example:
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
class ElaspedTimetoCopyAFileUsingCharacterStream
{
    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;
    public void start() 
    {
        this.startTime = System.currentTimeMillis();
        this.running = true;
    }
    public void stop() 
    {
        this.stopTime = System.currentTimeMillis();
        this.running = false;
    }
    public long getElapsedTime() 
    {
        long elapsed;
        if (running) {
             elapsed = (System.currentTimeMillis() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }
        return elapsed;
    }
    public long getElapsedTimeSecs()                 
    {
        long elapsed;
        if (running) 
        {
            elapsed = ((System.currentTimeMillis() - startTime) / 1000);
        }
        else
        {
            elapsed = ((stopTime - startTime) / 1000);
        }
        return elapsed;
    }

    public static void main(String[] args) throws IOException
    {
        ElaspedTimetoCopyAFileUsingCharacterStream  s = new ElaspedTimetoCopyAFileUsingCharacterStream();
        s.start();

         FileReader in = null;                // CharacterStream Reader
      FileWriter out = null;

      try {
         in = new FileReader("vowels.txt");    // 23.7 MB
         out = new FileWriter("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
        s.stop();
        System.out.println("elapsed time in seconds: " + s.getElapsedTimeSecs());
    }
}

Output:
elapsed time in seconds :   3 secs
Overwrite elapsed time in seconds  :  3 secs