Monday 29 March 2021

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 selected task. It provides the reusability of code. we will also easily modify code using methods. during this section, we'll learn what's a way in Java, sorts of methods, method declaration, and the way to call a way in Java.


What is Method in JAVA language? 

A method may be a block of code or collection of statements or a group of code grouped together to perform a particular task or operation. It is wont to achieve the reusability of code. We can write a method once and use it many times. We don't require to write down code again and again. It also provides the straightforward modification and readability of code, just by adding or removing a piece of code. The method is executed only we call or invoke it.
The most important method in Java is that the main() method.


Method Declaration in JAVA. 

The method declaration provides information about method attributes, like visibility, return-type, name, and arguments. It has six components that are known as method header, as we have shown in the following figure.



Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is that the access sort of the tactic. It specifies the visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our application.

Private: once we use a personal access specifier, the tactic is accessible only within the classes during which it's defined.

Protected: once we use protected access specifier, the tactic is accessible within an equivalent package or subclasses during a different package.

Default: once we don't use any access specifier within the method declaration, Java uses default access specifier by default. It is visible only from an equivalent package only.

Return Type: Return type may be a data type that the tactic returns. It may have a primitive data type, object, collection, void, etc. If the tactic doesn't return anything, we use void keyword.

Method Name: it's a singular name that's wont to define the name of a way . It must be like the functionality of the tactic . Suppose, if we are creating a way for subtraction of two numbers, the tactic name must be subtraction(). A method is invoked by its name.

Parameter List: it's the list of parameters separated by a comma and enclosed within the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.

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:


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...