Wednesday 26 September 2018

Objects

An Object represents an entity within the world like someone, thing or concept etc. An object is identified by its name. An object consists of the subsequent two things:
  • Properties: Properties are the characteristics of an object
  • Functions: Functions are the action which will be performed by an object

Examples:

Some samples of objects of different variious  are as follows:

  • Physical Objects: 

           Vehicles likes  cars, bus, trucks etc.
           Electrical components
           Elements of Computer-User Environment

  • Windows

          Menus
          Graphics objects
          Mouse and Keyboard

  • User-defined Data Types

          Time
         Angles

Properties of Object: 

The characteristics of an object are called its properties or attributes. Each object has its own properties. These properties are accustomed to describe the object. For instance, the properties of an object. Person can be as follows:

  • Name 
  • Age 
  • Weight 

The properties of an object Car is be as follows:

  • Color 
  • Price 
  • Model 
  • Engine power 

The set of values of the attributes of a selected object is named  its state. It means that the state of an object may be determined by the values of its attributes.
Functions of Object:
An object can perform different tasks and actions.The actions that may  be performed by the an object referred to as functions and methods. For the

Tuesday 25 September 2018

Java Servlet


Java servlet are programs that run on Web or Application server and act as a middle layer between an invitation coming from an internet browser or other client and database or applications on the HTTP Server.

Simple Servlet: 

import java.io.*;
import javax.servlet.* ;

public class HelloServlet extends GenericServlet{

    public void service (ServletRequest request, ServletResponse response)
        throws ServletException, IOException {

           response.setContentType("text/html");
           PrintWriter pro = response.getWriter();
           pw.println("<B> Hello! </B>");
           pw.close();

      }
}

Writing Servlet: 

Servlet Types: 


Servlet related classes are included in two main Packages.
  • javax.servlet
  • javax.servlet.http
Every servlet must implements the javax.       
 servlet.Servlet interface, it contains the servlet's life cycle method. 

In order to write down your own servlet, you'll be  subclass from GenericServlet or HttpServlet 

Genereric Servlet class 

  • Available in javax.servlet package 
  • Implements javax.servlet.Servlet
  • Extend your class from this class if you're curious about writing protocol independent servlet.

HttpServlet Class: 

  • Available in javax.servlet.http package
  • Extends from GenericServlet class            
  • Add functionality for writing Http specific servlet as compared to GenericServlet. 
  • Extends your class from HttpServlet, if you would like to write down http based Servlet. 
 
     

GET: 

       Request a page from server. This is the normal request used when browsing web pages.

POST: 

         This request is used to pass information to the server. Its most common use is with HTML forms.

PUT: 

       Use to put a replacement webpage on a server.

DELETE: 

           Used to delete a webpage from the server.

Reading HTML from Data using Servlet:

Types of data send to a WebServer

  • From Data
  • HTTP Request Header Data. 
The HTTPServletRequest object contain three main methods for extracting from data submitted by the user.

  1.  getParameter(String name): 

  • used to retrieve single from parameter and return String like  name specified. 
  • Empty String is returned in the case when user does not enter within the specified form field.   

     2.  getParameterValue(String name): 

  • return an array of string object containing all of the given values of the given request parameter. 
  • if the name specified does not exist, null is returned. 

     3.   getParameterNames(): 

  • it returns enumeration of string object containing the names of the parameters that come with the request. 
  • if the request has no parameters, the function return an empty enumeration.



Monday 24 September 2018

Java Servlets

Assume that a client enter his/her name and password in a form and sends a request to servlet. Servlet 1  will creates the connection  with database and verify the user information from the database. Table (login) show success message on console, if name found otherwise enter the information of client in table (log) with current system date and display sorry message. 


HTML Form:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML Form</title>
    </head>
    <body>
        <form name="form1" method="post" action="Servlet1">
            Username: <input type="text" name="t1" /><BR><BR>
            Password: <input type="password" name="t2" /><BR><BR>
            <input type="submit" name="Login" value="Login">
        </form>
    </body>
</html>

Servlet1:

import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) {
        try {
            PrintWriter pw = res.getWriter();
            res.setContentType("text/html");
            boolean flag = false;
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection cn = DriverManager.getConnection("Jdbc:Odbc:Exam");
            String sql = "select * from login";
            PreparedStatement st = cn.prepareStatement(sql);
            ResultSet rs = st.executeQuery();
            String s1 = req.getParameter("t1");
            String s2 = req.getParameter("t2");
            while (rs.next()) {
                if ((rs.getString(1).equals(s1)) && (rs.getString(2).equals(s2))) {
                    flag = true;
                }
            }
            if (flag) {
                pw.print("Login Succeeded!");
            } else {
                pw.print("Sorry... Login does not Succeeded!");
                String sql1 = "SELECT * FROM log";
                PreparedStatement pStmt = cn.prepareStatement(sql1, ResultSet.TYPE_SCROLL_INSENSITIVE,     ResultSet.CONCUR_UPDATABLE);
                ResultSet rs1 = pStmt.executeQuery();
                rs1.moveToInsertRow();
                rs1.updateString("username", s1);
                long time = System.currentTimeMillis();
                java.sql.Date date = new java.sql.Date(time);
                String s = date.toString();
                rs1.updateString("system_date", s);
                rs1.insertRow();
                cn.close();
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output:

REMOTE METHOD INVOCATION (RMI) | JAVA

Create an RMI based Examination server of Punjab University that will display the status of a student (Pass/ Fail) upon accept the roll number from client. The server will take "rollNo" of type string as an input from client and can will return his/her status. Suppose you have got find (String) method on server side for the searching of student's status. The client should display the status on console. 


RMI Interface:

import java.rmi.*;
public interface ExamInt extends Remote
{
  String find(String roll_n) throws RemoteException ;
}

Interface Implementation:

import java.rmi.server.*;
import java.rmi.*;
import java.sql.*;
public class ExamServerImpl extends UnicastRemoteObject implements ExamInt
{
public ExamServerImpl() throws RemoteException
{
                             }
//implementation of find(String) not required in asked question...
public String find(String roll_no) throws RemoteException
{
String status;
status=Examjdbc(roll_no);
return status;
}
public String Examjdbc(String r_no) throws RemoteException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("Jdbc:Odbc:mobileDSN");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery("Select *from status");
while(rs.next())
{
if(rs.getString(1).equals(r_no))
return rs.getString(2);
}

}
catch(Exception e)
{
System.out.println(e);
}
return null;
}
}

Server:

import java.net.*;
import java.rmi.*;
public class ExamServer
{
public static void main(String args[])
{
try{
ExamServerImpl obj= new ExamServerImpl();
Naming.rebind("ExamServer",obj);
}

catch(Exception e)
{
System.out.println("Exception "+e);
}
}
}

Client:

import javax.swing.*;
import java.rmi.*;
import java.net.*;
public class ExamClient
{
public static void main(String args[])
{
try{
    String examServerURL = "rmi://" + args[0] + "/ExamServer";
ExamInt obj= (ExamInt)Naming.lookup(examServerURL);
String r_n=JOptionPane.showInputDialog("Enter Roll number:");
String Status=obj.find(r_n);
System.out.println("You are " + Status);
}
catch(Exception e)
{
System.out.print("Exception " + e);
}
}

Output:


Remote Method Invocation (RMI) | Java

You have to build a mobile outlet server based on RMI. Client will generate a call to getPrice(string mobilename) to server class and on server you will get the name of mobile. Create a connection to Database and return the price of that particular mobile to client.
Perform all steps required for complete RMI application.
DB Name: mobile.mdb                              DSN name: mobile


Interface:

import java.rmi.*;
public interface MobileInterface extends Remote
{
double getPrice(String m_name) throws RemoteException;
}

Implementation:

import java.rmi.server.*;
import java.rmi.*;
import java.sql.*;
public class MobileServerImpl extends UnicastRemoteObject implements MobileInterface {
    public MobileServerImpl() throws RemoteException {
    }
    public double getPrice(String m_name) throws RemoteException {
        double price;
        price = Mobilejdbc(m_name);
        return price;
    }
    public double Mobilejdbc(String m_nam) throws RemoteException {
        double p;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection cn = DriverManager.getConnection("Jdbc:Odbc:mobileDSN");
            String sql = "Select *from Price where name=?";
            PreparedStatement pSt = cn.prepareStatement(sql);
            pSt.setString(1, m_nam);
            ResultSet rs = pSt.executeQuery();         
            if (rs.next()) {             
                    p = Double.parseDouble(rs.getString(2));
                    return p;
                }       
        } catch (Exception e) {
            System.out.println(e);
        }
        return 0.0;
    }
}

Server:

import java.net.*;
import java.rmi.*;
import java.sql.*;
public class MobileServer 
{
public static void main(String args[])
{
try{
MobileServerImpl obj=new MobileServerImpl();
Naming.rebind("MobileServer",obj);
}catch(Exception e)
{
System.out.println(e);
}


}

Client:

import javax.swing.*;
import java.rmi.*;
public class MobileClient 
{
public static void main(String args[])
{
try{
MobileInterface intobj=(MobileInterface)Naming.lookup("rmi://" + args[0] + "/MobileServer");
String  name=JOptionPane.showInputDialog("Enter Mobile Name:");
double p=intobj.getPrice(name);
System.out.println("Price for mobile: "+name+" is: "+p);
}catch(Exception e)
{
System.out.println(e);}
}


}

Output:



Write a Mulitithreaded TCP Server which will send system data and time to clinet.

Multithreaded TCP server:

import java.io.*;
import java.net.*;
import java.util.*;
public class MultiServe implements Runnable
{
 private ServerSocket ss;
 public static void main(String args[]) throws Exception
 {
  MultiServe m = new MultiServe();
  m.go();
 }
 public void go() throws Exception
 {
  ss = new ServerSocket(DayClient1.DAYTIME_PORT, 5);
  Thread t1 = new Thread(this, "1");
  Thread t2 = new Thread(this, "2");
  Thread t3 = new Thread(this, "3");
  t1.start(); t2.start(); t3.start();
 }
 public void run()
 {
  Socket s = null;
  BufferedWriter out = null;
  String myname = Thread.currentThread().getName();
  for (;;)
  {
   try
   {
    System.out.println("thread " + myname + " about to accept..");
    s = ss.accept();
    System.out.println("thread " + myname + " accepted a connection");
    out = new BufferedWriter(
    new OutputStreamWriter(s.getOutputStream()));
    out.write(myname + " " + new Date());
    Thread.sleep(10000);
    out.write("\n");
    out.close();
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
 }
}

Client:

//A TCP Client for the Daytime service
import java.net.*;
import java.io.*;
public class DayClient1 {
public static final int DAYTIME_PORT = 2012;
String host;
Socket s;
public static void main(String args[]) throws
IOException {
DayClient1 that = new DayClient1("192.681.158.1");
that.go();
}
public DayClient1(String host) {
this.host = host;
}
public void go() throws IOException {
s = new Socket(host, DAYTIME_PORT);
BufferedReader i = new BufferedReader(
new InputStreamReader(s.getInputStream()));
System.out.println(i.readLine());
i.close();
s.close();
}
}

Output:


‘OR’

Server:

import java.io.*;
import java.net.*;
public final class TcpServerStarter 
{
 public static void main(String[] args) throws IOException 
 {
  ServerSocket serverSocket = null;
  boolean listening = true;
  try 
  {
   serverSocket = new ServerSocket(2012);
  } 
  catch (IOException e) 
  {
   System.err.println("Could not listen on port: 2012.");
   System.exit(-1);
  }
  while (listening)
  new ConnectionHandler( serverSocket.accept()).start();
  serverSocket.close();
 }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
public final class ConnectionHandler extends Thread {
    private Socket socket;
    public ConnectionHandler(Socket socket){
          setName("ConnectionHandler");
          this.socket = socket;
    }
    public void run(){
          BufferedReader in = null;
          PrintWriter out = null;
          String request;
          try{
                // Get the input and output streams
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                while( (request = in.readLine()) != null){

                      // Deliver the current date and time if the client sends GET_TIME
                      if(request.equals("GET_TIME"))
                            out.println(new Date().toString());

                      // Deliver the JRE version if the client sends GET_JAVA_VERSION
                      else if(request.equals("GET_JAVA_VERSION"))
                            out.println(System.getProperty("java.version"));

                      // Exit the loop if the client sends CLOSE
                      else if(request.equals("CLOSE"))
                            break;
                }
          }
          catch(IOException e){
                e.printStackTrace();
          }
          finally{
                try{
                      if(socket != null)
                  socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
                catch(IOException e){
                      e.printStackTrace();
                }
          }
    }
}

Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public final class TcpClient {
    private void process() {
          Socket socket = null;
          BufferedReader in = null;
          PrintWriter out = null;
          try{
                /* Establish a TCP connection with the server running locally on the port number 2012.
                 * You can write "localhost" instead of "192.681.158.1".
                                  */
                socket = new Socket("192.681.158.1", 2012);

                // Get the input and output streams
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                // Send a GET_TIME request and print the response to the standard output
                out.println("GET_TIME");
                System.out.println(in.readLine());

                // Send a GET_JAVA_VERSION request and print the response to the standard output
                out.println("GET_JAVA_VERSION");
                System.out.println(in.readLine());

                // Send a CLOSE request to the server to end communication
                out.println("CLOSE");
          }
          catch(IOException e){
                e.printStackTrace();
          }
          finally{
                try{
                      if(socket != null)
                            socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
                catch(IOException e){
                      e.printStackTrace();
                }
          }
    }
    public static void main(String[] args){
          new TcpClient().process();
    }
}

Output:


Multithreading Program in Java

Write down a complete multithreaded connection oriented socket based server, that'll wait for the connections from clients, after the establishment of connection with client, it will receive a string word from the client and send it back the meaning of that word from the array stored on server to client. 


Multithreaded Server Starter: 

import java.io.*;
import java.net.*;
public final class TcpServerStarter 
{
 public static void main(String[] args) throws IOException 
 {
  ServerSocket serverSocket = null;
  boolean listening = true;
  try 
  {
   serverSocket = new ServerSocket(7777);
  } 
  catch (IOException e) 
  {
   System.err.println("Could not listen on port: 7777.");
   System.exit(-1);
  }
  while (listening){
  new P10_5( serverSocket.accept()).start();
  System.out.println("Accepted connection from client");}
  serverSocket.close();
 }
}

Multithreaded Server:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public final class P10_5 extends Thread {
    private final Socket socket;
    public P10_5(Socket socket) {
        setName("P10_5");
        this.socket = socket;
    }
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        int n = 3;
        String request;
        try {
            // Get the input and output streams
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            class dic {
                String word, mean;
                dic(String w, String m) {
                    word = w;
                    mean = m;
                }
            }
            dic d[] = new dic[4];
            d[0] = new dic("coincidence", "itifaq");
            d[1] = new dic("thanks", "shukriya");
            d[2] = new dic("problem", "masla");
            d[3] = new dic("night", "raat");
            while ((request = in.readLine()) != null) {
                for (int i = 0; i < n; i++) {
                    if (request.equals(d[i].word)) {
                        out.println(d[i].mean);
                        break;
                    }
                    if (i == n - 1) {
                        out.println("No knowledge for " + request);
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public final class P10_5Client {
    private void process() {
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            /* Establish a TCP refrenced to  the server running locally on the port number 7777.
             * You can write "localhost" instead of "127.0.0.1".
             * If the server is running on a foriegn computer, replace "127.0.0.1" with the server's IP address or hostname
             */
            socket = new Socket("127.0.0.1", 7777);
            // Get the input and output streams
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            Scanner user = new Scanner(System.in); // Scanning for user input
            String input;
            while (true) {
                System.out.print("Enter String: ");
                input = user.next(); // Hold the input from the user
                if (input.equals("end")) {
                    System.out.println("You ended...");
                    break;
                } else {
                    out.println(input); // Send it to the server
                    System.out.println("Name: " + input + " Meaning: " + in.readLine());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new P10_5Client().process();
    }
}

Output:





Sunday 23 September 2018

Difference between Abstract Classes and Interface in Java

Abstract Class:

Abstract class can have abstract and non-abstract methods.

Abstract class doesn't support multiple inheritance.

Abstract class can have final, non-final, static & non-static variable.

Abstract class can have static methods, main method and constructors.

Abstract class can provide the implementation of interface.

    public abstract class Shape
          {
                public abstract void shape();
          }


 A Java abstract class can have instance methods that implements a default behavior.

 An abstract class may contain non-final variable.

An abstract class can extend another Java class & implement multiple Java interfaces.

Java abstract classes are faster than interface.

Interface: 

Interface can have only abstract method.

Interface support multiple inheritance.

Interface has only static & final variable.

Interface can't  have static methods main method or constructor.

Interface can't provide the implementation of abstract classes.

public interface Drawable {
 void draw();
}

Method of Java interface are implicitly abstract & cannot have implementation.

Java interface should be implemented using keyword "implements".

Java  class can implements multiple interface.

In comparison with  java abstract classes, java interface  are slow as it requires extra indirection. 

Socket Programming in Java

Networking / Socket Programming :
                      
A socket is one endpoint of a two way  communication link between two programs running  on a Network. A socket is a bi-directional communication between host. A computer on a network often termed as host.

Socket Dynamics : 


Socket is an abstraction of the network.Each end has an input stream( to send data) and output stream( to receive data) wired up to the other host.You store and retrieve data to and from network through socket, without actually going into underlying mechanism.

What is Port?


It is transport address to which processes can listen for connection request. There are different protocols available to communicate such as TCP and UDP. There are 64k ports available for TCP sockets and 64k ports for UDP.

Client-Server Communication: 

  • A server runs on a specific computer and has  a socket that is bound to a specific port number.
  • The server just waits, listening to the socket for a client to make a connection request. 
  • On the client side : The client knows the hostname of the machine on which the server is running and the port number to which the server is connected. 
  • As client creates  a socket that socket attempts to connect to the specified server. 
  • The server listens through a specific kind of socket, which is named as server socket.
  • The sole purpose of the server socket is to listen for incoming request; it is not used for communication. 
  • If everything goes well, the server accepts the connection. 'Upon acceptance, the server gets a new socket, a communication  socket , bound to a different port number.
  • The server needs a new socket so that it can continue to listen through the original server socket for connection requests while tending to the needs  of the connected client. The scheme is helpful when two or more clients try to connect to a server simultaneously. 
  • On the server side, if the connection is accepted, a socket is successfully created and the client can use the socket  to communicate with the server. 
  • Note that the socket on the client side is not bound to the port number used to make contact with the server. Rather, the client is assigned a port number  local to the machine on which the client is running.
  • The client and server can now communicate by writing to or reading from their socket. 
Steps - To Make a Simple Client: 
 To make a client, process can be split into 5 steps. These are:

1. Import required package: 
You have to import two packages 
  • java.net.*; 
  • java.io.*; 
2. Connect / Open a Socket with server: 
Create a client socket(Communication Socket)
     Socket s  = new Socket("serverName" , serverPort);
  • serverName: Name or address of the server you wanted to connect such as  http://www.google.com  or  172.2.4.98 etc. For testing if you are running client  and server on the same machine then you can specify "localhost" as the name of server.
  • serverPort: Port number you want to connect to 
The scheme is very similar to our home address and then phone number. 

3. Get I/O Streams of Socket: 
Get input & output streams connected to your socket. 
  • For reading data from socket 
          A socket has input stream attached to it. 
               InputStream is =  s.getInputStream(); 
               // now to convert byte oriented streams into character oriented buffered reader. 

              // we use intermediary stream that helps in achieving above stated  purpose. 
              InputStreamReader isr = new InputStreamReader(is); 
             BufferedReader br = new BufferedReader(isr);
  • For writing data to socket
         A socket has also output stream attached to it. Therefore, 
                OutputStream os = s.getOutputStream(); 
                // now to convert byte oriented stream into Character oriented Printer Writer
               // here we will not use any intermediary stream because PrintWriter constructor
              // directly accepts an Object of  OutputStream. 
              PrintWriter pw = new PrintWriter(os, true); 

Here notice that true is also passed to so that output buffer will flush. 

Methods in JAVA Language

 In general, a way may be thanks to perform some task. Similarly, the tactic in Java may be a collection of instructions that performs a sel...