Wednesday, July 30, 2014

WEET (Way of Expressway E Ticketing)

What is WEET? What is is it about ? How was it begun ?

Actually WEET is a mobile Telco application which provides the facility of booking your ticket in ExpressWay .

In TADHACK 2014 Competition it was originally created with the USSD ,SMS ,CAS, and as a web services .

There three parties invovled in this application process

  1. User(Passenger )
  2. Bus Driver
  3. Bus Owner
User (Passenger )can dial the USSD code #771*933# from his Dialog mobile and he access to the E ticketing System .
Then he will get a menu and he can choose his route,time he will pay the ticket amout via this application.
After completing these steps he will get a confirmation SMS with the reference number.

In the same time Bus Driver receive that ticket purchasing details into the tab which is in the bus.So he can get the count total income and other details.

Not only that , also this transaction process can view by the  Bus Owner through a Web Application or a mobile apllication. 

The income directly transfer in to Bus Owner's bank account when the Passenger purchase his ticket.



    • So no need to be a in a huge queue until bus reaches
    • No need to pay using cash
    • Every process is transparent to the bus owner


Watch the WEET Apllication Demo and get a clear idea about how it works




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>

Saturday, July 26, 2014

Data Structures and Algorithms with Java - Part II (Data Structures & Algorithms)

‍ඔන්න DSA Final part එක දැන් post කරනවා ඔයාලට.....

Search Algorithms ගැන කතා කරොත් It can divided in to 2 categories

1. Linear Search
    • Small and Unsorted Arrays
    • Simple to implement but slow
     මෙහිදී array එකේ මුල සිට අවසානය දක්වා search key එක ලැබෙන තෙක් search කරයි.

Code  

//Code by me

public int linearSearch(int list[],int size,int SK){
    boolean found=false;
    int position=-1;
    int index=0;
    
    while(index<list.length && !found){
        if (list[index]==SK) {
                found = true;
                position = index;
            }
            ++index;
        }
        return position;
    }

 2. Binary Search
    • Large and sorted Arrays
   මෙහිදී array එක කොටස් 2 කට බෙදා එක් එක් කොටස නැවත නැවතත් බෙදා  වෙන වෙනම search key ලැබෙන තෙක්  search කරයි.


Code
//Code by me
public void binarySearch(int list[], int size, int SK) {
        int mid = (list.length - 1) / 2;
        boolean f = false;

        if (list[mid] > SK) {
            while (list[mid] != SK) {
                if (list[mid] == SK) {
                    ++mid;
                }

            }
        } else {
            while (list[mid] != SK) {
                --mid;
            }
        }

    }

Sort Algorithms ගැන කතා කරොත් It can divided in to 5 categories

1. Bubble sort

Code
//Referenced code
for (int x = 0; x < n; x++) {
            for (int y = 0; y < n - 1; y++) {
                if (array[y] > array[y + 1]) {
                    int temp = array[y + 1];
                    array[y + 1] = array[y];
                    array[y] = temp;
                }
            }
        }


2. Selection Sort


Code
//Referenced code
public static void selectionSort1(int[] x) {
        for (int i = 0; i < x.length - 1; i++) {
            for (int j = i + 1; j < x.length; j++) {
                if (x[i] > x[j]) {
                    //... Exchange elements
                    int temp = x[i];
                    x[i] = x[j];
                    x[j] = temp;
                }
            }
        }
    }

3. Insertion Sort


Code

//Referenced code

    public class MyInsertionSort {

        public static void main(String[] args) {

            int[] input = {4, 2, 9, 6, 23, 12, 34, 0, 1};
            insertionSort(input);
        }

        private static void printNumbers(int[] input) {

            for (int i = 0; i < input.length; i++) {
                System.out.print(input[i] + ", ");
            }
            System.out.println("\n");
        }

        public static void insertionSort(int array[]) {
            int n = array.length;
            for (int j = 1; j < n; j++) {
                int key = array[j];
                int i = j - 1;
                while ((i > -1) && (array[i] > key)) {
                    array[i + 1] = array[i];
                    i--;
                }
                array[i + 1] = key;
                printNumbers(array);
            }
        }
    }
4. Merger Sort


Code

//Referenced code
public class MyMergeSort {

        private int[] array;
        private int[] tempMergArr;
        private int length;

        public static void main(String a[]) {

            int[] inputArr = {45, 23, 11, 89, 77, 98, 4, 28, 65, 43};
            MyMergeSort mms = new MyMergeSort();
            mms.sort(inputArr);
            for (int i : inputArr) {
                System.out.print(i);
                System.out.print(" ");
            }
        }

        public void sort(int inputArr[]) {
            this.array = inputArr;
            this.length = inputArr.length;
            this.tempMergArr = new int[length];
            doMergeSort(0, length - 1);
        }

        private void doMergeSort(int lowerIndex, int higherIndex) {

            if (lowerIndex < higherIndex) {
                int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
                // Below step sorts the left side of the array
                doMergeSort(lowerIndex, middle);
                // Below step sorts the right side of the array
                doMergeSort(middle + 1, higherIndex);
                // Now merge both sides
                mergeParts(lowerIndex, middle, higherIndex);
            }
        }

        private void mergeParts(int lowerIndex, int middle, int higherIndex) {

            for (int i = lowerIndex; i <= higherIndex; i++) {
                tempMergArr[i] = array[i];
            }
            int i = lowerIndex;
            int j = middle + 1;
            int k = lowerIndex;
            while (i <= middle && j <= higherIndex) {
                if (tempMergArr[i] <= tempMergArr[j]) {
                    array[k] = tempMergArr[i];
                    i++;
                } else {
                    array[k] = tempMergArr[j];
                    j++;
                }
                k++;
            }
            while (i <= middle) {
                array[k] = tempMergArr[i];
                k++;
                i++;
            }

        }
    }

5.Quick Sort


Code
//Referenced code

    public class MyQuickSort {

        private int array[];
        private int length;

        public void sort(int[] inputArr) {

            if (inputArr == null || inputArr.length == 0) {
                return;
            }
            this.array = inputArr;
            length = inputArr.length;
            quickSort(0, length - 1);
        }

        private void quickSort(int lowerIndex, int higherIndex) {

            int i = lowerIndex;
            int j = higherIndex;
            // calculate pivot number, I am taking pivot as middle index number
            int pivot = array[lowerIndex + (higherIndex - lowerIndex) / 2];
            // Divide into two arrays
            while (i <= j) {
                /**
                 * In each iteration, we will identify a number from left side
                 * which is greater then the pivot value, and also we will
                 * identify a number from right side which is less then the
                 * pivot value. Once the search is done, then we exchange both
                 * numbers.
                 */
                while (array[i] < pivot) {
                    i++;
                }
                while (array[j] > pivot) {
                    j--;
                }
                if (i <= j) {
                    exchangeNumbers(i, j);
                    //move index to next position on both sides
                    i++;
                    j--;
                }
            }
            // call quickSort() method recursively
            if (lowerIndex < j) {
                quickSort(lowerIndex, j);
            }
            if (i < higherIndex) {
                quickSort(i, higherIndex);
            }
        }

        private void exchangeNumbers(int i, int j) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }

        public static void main(String a[]) {

            MyQuickSort sorter = new MyQuickSort();
            int[] input = {24, 2, 45, 20, 56, 75, 2, 56, 99, 53, 12};
            sorter.sort(input);
            for (int i : input) {
                System.out.print(i);
                System.out.print(" ");
            }
        }
    }


Recursion

  • Recursion is the function calling  it self 
  • We can use instead of a loop which is in a large looping times
Code

Factorial

int factorial(int num ){
if (num <= 0) {
                return 1;
            } else {
                return num * factorial(--num );
            }
        }


Fabonaci

int fibonaci(int num ){

if (num <= 0) {
                return 0;
            } else {
                return num +  fibonaci(--num);
            }

        }



Trees

  • Hierarchy Concept
  • For File Systems/Java Class Hierarchy
  • Fast Searchable
  • Each Node Connect to multiple Nodes
  • Root/Parent/Child/Leaves/Height/Depth are some key words used in trees



Tress Traversing
  • PreOrder - VLR process
    • Visit first Left Right
  • PostOrder- LRV process
    • Left Right and Visit
  • InOrder- LVR process
    • Left Visit Right





Tree Balancing Techniques
  • Global
    • DSW Algorithm

  • Local
    • AVL
      • This consider about the level difference is equal to 1 or 0, it is balanced

    • Red Black
      • This consider about the level difference is upto 2 ,it is balanced



Tree Balancing

  • Left Rotate 
  • Right Rotate




Thank you for following The Explorer's DSA Tutorial. See you in another Tutorial :D