Monday, July 28, 2014

Important points in Java Networking/ RMI / Socket Programming/Regular Expressions

ඔන්න Java EE ඉගන ගන්න අයට Java Networking/ RMI / Socket Programming වැදගත් කොටස් කිහිපයක විස්කරයක් කරන්නයි යන්නෙ ගවේෂක අද.

 Java Networking

In java networking we can divide it into two categories and let's see the comparision

  1. Stream Based(TCP)
    • Connection based
    • Reliable
  2. Packet Based(UDP)
    • Connectionless
    •  Not Reliable

Establish a simple Server using Stram Socket
1.Server Socket

ServerSocket server=new ServerSocket (Port_Number,Queue_Lengh);

2.Accept Client

Socket Connection=Server.accept();

3.Open Path

Input and OutPut Stream

4.Processing Part

Communication

5.Server Close

************************************************************************
Client/Server Communication Process Using TCP


  1. Server issues a call to create a listening socket.
  2. Server and client create a socket.
  3. Server and client bind socket. (This step is optional for a client.)
  4. Server converts an unconnected socket into a passive socket (LISTEN state).
  5. Server issues an accept() and process blocks waiting for a connection request.
  6. Client sends a connection request.
  7. Server accepts the connection; a new socket is created for communication with this client.
  8. Server receives device information from the local host.
  9. Data exchange takes place.
  10. Client and server delete the socket.
  11. Server deletes the listener socket when the service to the client is terminated.
UDP Socket Communication Process


  1. Server and client create a socket.
  2. Server and client bind the socket name.
  3. Data exchange takes place.
  4. Server and client delete the socket.

Port Vs Socket(Referenced)



port is a logical connection method two end points communicate with. Ports operate at the Transport layer of the OSI
A TCP socket is not a connection, it is the endpoint of a specific connection.
There can be concurrent connections to a service endpoint, because a connection is identified by both its local and remote endpoints, allowing traffic to be routed to a specific service instance.
Sockets are a means of plugging the application layer in. Sockets are determined by an IP address and port number.A socket is one end point of a connection.

A socket consists of three things:
  1. An IP address
  2. A transport protocol
  3. A port number
A port is a number between 1 and 65535 inclusive that signifies a logical gate in a device. Every connection between a client and server requires a unique socket.
For example:
  • 1030 is a port.
  • (10.1.1.2 , TCP , port 1030) is a socket.
A port is a virtualisation identifier defining a service endpoint (as distinct from a service instance endpoint aka session identifier).

A TCP socket is an endpoint instance defined by an IP address and a port in the context of either a particular TCP connection or the listening state.

There can only be one listener socket for a given address/port combination.

Java Remote Method Invocation


Steps of RMI
  • Make sure there is these classes are available
    • Serializable Classes
    • Remote Classes and Interfaces
  • Should be as follow the programming part order
    • Programming a client
    • Programming a server
  • Finally Runing the programme should be as  follows
    • Run the Client First

Codings


Hello.java
import java.rmi.server.*;
import java.rmi.*;

public class Hello extends UnicastRemoteObject implements HelloInterface{
public String message;
public Hello(String msg) throws RemoteException{
message=msg;
}
public void login(String name, String pass) throws RemoteException{

}
public void logout(String name) throws RemoteException{

}

public String chat(String name, String msg) throws RemoteException{

return message;
}

}

HelloClient.java
import java.rmi.*;

public class HelloClient{

public static void main(String[] arg){

try{
HelloInterface hello = (HelloInterface)Naming.lookup("//localhost:1099/Hello");
hello.login("Lahiru","123");
System.out.println(hello.chat("Lahiru","Hi!!!"));
}catch(Exception e){
System.out.println("Exception :"+e.getMessage());
}

}

}

HelloServer.java
import java.rmi.*;
import java.io.*;

public class HelloServer{
public static void main(String[] arg){
try{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Login Name: ");
String name = br.readLine();
Naming.rebind("Hello", new Hello(name));
System.out.println("Hello Server Ready");
}catch(Exception e){
System.out.println("Exception "+e);
}
}

}

HelloInterface.java
import java.rmi.*;

public interface HelloInterface extends Remote{

public void login(String name, String pass) throws RemoteException;
public void logout(String name) throws RemoteException;

public String chat(String name, String pass) throws RemoteException;

}


Regular Expressions





Regular ExpressionDescription
\dAny digit, short for [0-9]
\DA non-digit, short for [^0-9]
\sA whitespace character, short for [ \t\n\x0b\r\f]
\SA non-whitespace character, short for [^\s]
\wA word character, short for [a-zA-Z_0-9]
\WA non-word character [^\w]
Here is a code for email validation pattern

EmailValidator.java
package com.mkyong.regex;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class EmailValidator {
 
 private Pattern pattern;
 private Matcher matcher;
 
 private static final String EMAIL_PATTERN = 
  "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
  + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
 
 public EmailValidator() {
  pattern = Pattern.compile(EMAIL_PATTERN);
 }
 
 /**
  * Validate hex with regular expression
  * 
  * @param hex
  *            hex for validation
  * @return true valid hex, false invalid hex
  */
 public boolean validate(final String hex) {
 
  matcher = pattern.matcher(hex);
  return matcher.matches();
 
 }
}
For Validate a Form Entry Data

Validate.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RegularEx;
import java.util.Scanner;
/**
 *
 * @author Lahiru Dhananjaya
 */
public class Validate {
    public static void main(String[] args) {
        ValidateInput vi=new ValidateInput();
     
        Scanner s=new Scanner(System.in);
     
        System.out.println("Enter First Name");
        String fname=s.next();
     
        System.out.println("Enter Last Name");
        String lname=s.next();
     
        System.out.println("Enter Address");
        String address=s.next();
     
        System.out.println("Enter City");
        String city=s.next();
     
        System.out.println("Enter State");
        String state=s.next();
     
        System.out.println("Enter Zip");
        String zip=s.next();
     
        System.out.println("Enter Phone Number");
        String phone=s.next();
     
        if(!vi.validateFirstName(fname))
        {
            System.out.println("Invalid First Name");
        }
        else if(!vi.validateLastName(lname))
        {
            System.out.println("Invalid Last Name");
        }
        else if(!vi.validateAddress(address))
        {
            System.out.println("Invalid Address");
        }
        else if(!vi.validateCity(city))
        {
            System.out.println("Invalid City");
        }
        else if(!vi.validateState(state))
        {
            System.out.println("Invalid State");
        }
        else if(!vi.validateZip(zip))
        {
            System.out.println("Invalid Zip");
        }
        else if(!vi.validatePhone(phone))
        {
            System.out.println("Invalid Phone");
        }
        else
        {
             System.out.println("Ok");
        }
     
     
     
    }

}


ValidateInput.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RegularEx;

/**
 * 
 * @author Lahiru Dhananjaya
 */
public class ValidateInput {
    public static boolean validateFirstName(String firstName)
    {
        return firstName.matches("[A-Z][a-zA-Z]*");
    }
    
    public static boolean validateLastName(String lastName)
    {
        return lastName.matches("[a-zA-Z]+([ '-][a-zA-Z]*)");
    }
    
    public static boolean validateAddress(String address)
    {
        return address.matches("\\d+\\s+[a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+");
    }
    
    public static boolean validateCity(String city)
    {
        return city.matches("[a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+");
    }
    
    public static boolean validateState(String state)
    {
        return state.matches("[a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+");
    }
    
    public static boolean validateZip(String zip)
    {
        return zip.matches("\\d{5}");
    }
    
    public static boolean validatePhone(String phone)
    {
        return phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}");
    }
    
    
}


Java Bean Class Example

Edisplay.java

package xm_java_bean;

/**
 *
 * @author Lahiru Dhananjaya
 */
public class Edisplay {
    public static void main(String[] args) {
        Employee em=new Employee();
        em.setName("Lahiru");
        em.setNumber("001");
     
        System.out.println(em.getName());
        System.out.println(em.getNumber());
    }

}


Employee.java
package xm_java_bean;

/**
 *
 * @author Lahiru Dhananjaya
 */
public class Employee implements java.io.Serializable {

    private String EmployeeName;
    private String EmployeeNumber;
 
    //Default Constructor
    public Employee() {
    }

    public void setName(final String EmployeeName) {
        this.EmployeeName = EmployeeName;
    }

    public void setNumber(final String EmployeeNumber) {
        this.EmployeeNumber = EmployeeNumber;
    }
    
    public String getName() {
        return EmployeeName;
    }
    public String getNumber() {
        return EmployeeNumber;
    }
    
}

********************************************************************************
To view Full code in JSP(Referenced)


package player;
 
public class PersonBean implements java.io.Serializable {
 
    /**
     * Property <code>name</code> (note capitalization) readable/writable.
     */
    private String name = null;
 
    private boolean deceased = false;
 
    /** No-arg constructor (takes no arguments). */
    public PersonBean() {
    }
 
    /**
     * Getter for property <code>name</code>
     */
    public String getName() {
        return name;
    }
 
    /**
     * Setter for property <code>name</code>.
     * @param value
     */
    public void setName(final String value) {
        name = value;
    }
 
    /**
     * Getter for property "deceased"
     * Different syntax for a boolean field (is vs. get)
     */
    public boolean isDeceased() {
        return deceased;
    }
 
    /**
     * Setter for property <code>deceased</code>.
     * @param value
     */
    public void setDeceased(final boolean value) {
        deceased = value;
    }
}

TestPersonBean.java:

import player.PersonBean;

/**
 * Class <code>TestPersonBean</code>.
 */
public class TestPersonBean {
    /**
     * Tester method <code>main</code> for class <code>PersonBean</code>.
     * @param ARGS
     */
    public static void main(String[] args) {
        PersonBean person = new PersonBean();
 
        person.setName("Bob");
        person.setDeceased(false);
 
        // Output: "Bob [alive]"
        System.out.print(person.getName());
        System.out.println(person.isDeceased() ? " [deceased]" : " [alive]");
    }
}

testPersonBean.jsp;
<% // Use of PersonBean in a JSP. %>
<jsp:useBean id="person" class="player.PersonBean" scope="page"/>
<jsp:setProperty name="person" property="*"/>
 
<html>
    <body>
        Name: <jsp:getProperty name="person" property="name"/><br/>
        Deceased? <jsp:getProperty name="person" property="deceased"/><br/>
        <br/>
        <form name="beanTest" method="POST" action="testPersonBean.jsp">
            Enter a name: <input type="text" name="name" size="50"><br/>
            Choose an option:
            <select name="deceased">
                <option value="false">Alive</option>
                <option value="true">Dead</option>
            </select>
            <input type="submit" value="Test the Bean">
        </form>
    </body>
</html>

No comments:

Post a Comment