Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Nov 15, 2014

Java Architecture For XML Binding(Marshaling and Unmarshaling)

In This We Are Focusing On Communication Between Java Application and XML Files.
First Of All Make Sure Your Machine Is Setup With Java Development Environment.

In This Lesson Will Do Following Tasks.

1. Creating A Simple XML File
2. Generating XSD File For XML File
3. Running JAXB Compiler To Genarate Java Classes
4. Unmarshal(XML To Objects) & Marshaling(Objects To XML)
5. Running The Project

Before Starting Make Sure You Have Downloaded The "jaxb-api-2.1" & Setup The ClassPath For That.If Everything Done Lets Do Begin The Work.

1. Creating A Simple XML File
First Create A XML File As You Want, But Make It With Many Results.
I'm Going To Use XML Related To Library.

Library.xml 
<?xml version="1.0"?>
<Library>
<Book>
<Title>My Life and Times</Title>
<Author>Paul McCartney</Author>
<Date>1998</Date>
<ISBN>1-56592-235-2</ISBN>
<Publisher>McMillin Publishing</Publisher>
</Book>
<Book>
<Title>Illusions The Adventures of a Reluctant Messiah</Title>
<Author>Richard Bach</Author>
<Date>1977</Date>
<ISBN>0-440-34319-4</ISBN>
<Publisher>Dell Publishing Co.</Publisher>
</Book>
<Book>
<Title>The First and Last Freedom</Title>
<Author>J. Krishnamurti</Author>
<Date>1954</Date>
<ISBN>0-06-064831-7</ISBN>
<Publisher>Harper &amp; Row</Publisher>
</Book>

</Library>


2. Generating XSD File For XML File
Now We Need To Get The XSD File For This XML.Rather Going For A Coding To Do This, Simply Google It "XML To XSD". You Will Find Many XML To XSD Converters Online.
I Have Used One Of Them & Converted My Library.xml To Library.xsd

Library.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
  <xs:element name="Library">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Book" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Title" type="xs:string"></xs:element>
                            <xs:element name="Author" type="xs:string"></xs:element>
                            <xs:element name="Date" type="xs:int"></xs:element>
                            <xs:element name="ISBN" type="xs:string"></xs:element>
                            <xs:element name="Publisher" type="xs:string"></xs:element>
                        </xs:sequence>
</xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>


3. Running JAXB Compiler To Genarate Java Classes
First Create A Folder Inside Your Project Folder And Name It As JAXB.
Open A Command Prompt And Go To The Relevant Folder Using.
To Generate Java Classes For This XML File Run The Following Command In Command Prompt.

xjc -d JAXB Library.xsd

After Run This You Will Get The Java Classes Inside The Folder JAXB.
Following Are The Classes Which I Got.

Library.java
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "book"
})
@XmlRootElement(name = "Library")
public class Library {

    @XmlElement(name = "Book", required = true)
    protected List<Library.Book> book;

    public List<Library.Book> getBook() {
        if (book == null) {
            book = new ArrayList<Library.Book>();
        }
        return this.book;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "title",
        "author",
        "date",
        "isbn",
        "publisher"
    })
    public static class Book {

        @XmlElement(name = "Title", required = true)
        protected String title;
        @XmlElement(name = "Author", required = true)
        protected String author;
        @XmlElement(name = "Date")
        protected int date;
        @XmlElement(name = "ISBN", required = true)
        protected String isbn;
        @XmlElement(name = "Publisher", required = true)
        protected String publisher;

        public String getTitle() {
            return title;
        }

        public void setTitle(String value) {
            this.title = value;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String value) {
            this.author = value;
        }

        public int getDate() {
            return date;
        }

        public void setDate(int value) {
            this.date = value;
        }

        public String getISBN() {
            return isbn;
        }

        public void setISBN(String value) {
            this.isbn = value;
        }

        public String getPublisher() {
            return publisher;
        }

        public void setPublisher(String value) {
            this.publisher = value;
        }
    }
}

ObjectFactory.java
import javax.xml.bind.annotation.XmlRegistry;

@XmlRegistry
public class ObjectFactory {

    public ObjectFactory() {
    }

    public Library createLibrary() {
        return new Library();
    }

    public Library.Book createLibraryBook() {
        return new Library.Book();
    }
}

4. Unmarshal(XML To Objects) & Marshaling(Objects To XML)
Create Following Java Class Inside The JAXB FolderTo Do The Un-Marshaling and Marshaling.

Main.java
import java.io.File;
import java.io.FileReader;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

class Main { 

    public static void main(String args[]){

try{
//Creating The Context
JAXBContext jaxbcontext = JAXBContext.newInstance(Library.class);
Unmarshaller unmarshaller = jaxbcontext.createUnmarshaller();

//Unmarshaling Library XML File
Library library = (Library)unmarshaller.unmarshal(new FileReader("Library.xml"));
List<Library.Book> booklist = library.getBook();

//Printing Library Book Details
System.out.println("\nUnMarshalling :: Current XML File\n\n");
System.out.println("\n~~ Libraray Book Details ~~\n");
System.out.println("____________________________________________________");
int iBookCount = 1;
for (Library.Book book : booklist) {
System.out.println("Book No :" + iBookCount++);
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Date: " + book.getDate());
System.out.println("ISBN: " + book.getISBN());
System.out.println("Publisher: " + book.getPublisher());
System.out.println("____________________________________________________");
}

//Adding A New Book To The Library
Library.Book newBook1 = new Library.Book();
newBook1.setTitle("Learning Java in 21 Days");
newBook1.setAuthor("Sam De Costa");
newBook1.setDate(2012);
newBook1.setISBN("978-0060554736");
newBook1.setPublisher("Sun Micro Systems");
booklist.add(newBook1);

//Adding A New Book To The Library
Library.Book newBook2 = new Library.Book();
newBook2.setTitle("How Te Be A Good Programmer");
newBook2.setAuthor("Nifal Nizar");
newBook2.setDate(2014);
newBook2.setISBN("1245-0060-5547");
newBook2.setPublisher("ADVANCE PUBLISHERS");
booklist.add(newBook2);

//Printing New Library Book Details
System.out.println("\n~~ New Libraray Book Details ~~\n");
System.out.println("____________________________________________________");
iBookCount = 1;
for (Library.Book book : booklist) {
System.out.println("Book No :" + iBookCount++);
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Date: " + book.getDate());
System.out.println("ISBN: " + book.getISBN());
System.out.println("Publisher: " + book.getPublisher());
System.out.println("____________________________________________________");
}

//Creating Library Object To Write To The XML File
ObjectFactory objectfactory = new ObjectFactory();
Library mylibrary = objectfactory.createLibrary();
for (Library.Book book : booklist) {
mylibrary.getBook().add(book);
}

//Marshalling
Marshaller marshaller = jaxbcontext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(mylibrary, new File("Library.xml"));

//Printing New XML File
System.out.println("\n\nMarshaling Done");
                        System.out.println("This Is The Newest xml File\n");
marshaller.marshal(mylibrary, System.out);

}

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

}


5. Running The Project
Go To Folder JAXB In The Command Prompt.
Compile All The Classes Using Command *.java
Run The Project Using Command java Main

You Will Get The Output.

Enjoy Coding...

Nov 5, 2014

RMI Multiple Clients Chat Program

In This Article I Will Demonstrate You To Create A Simple Chat Program Using Java Remote Method Invocation(RMI). Following Program Supports Multiple Client Chat. The Chat Program Only Has The Broadcast Message Feature. You Can Use This Program and Can Improve To Chat Between Two Clients. Program Contains Three Java Files.

1. ChatInterface - Which Is A Interface Common For Both Client and Server.
2. Server - Which Implements The RMI Server
3. Client - Which Implements The Client.

NOTE : Server Is Initially Hard Coded With Five Client Names and Password. In Order To Do That I Have Used Two String Arrays. Their Are Lot Of More Easy Ways To Implement The Logging Scenario. If You Want You Can Use A Database or Separate File Store Client Details.     


ChatInterface.java
1
2
3
4
5
6
7
import java.rmi.RemoteException;

public interface ChatInterface extends java.rmi.Remote {
    boolean checkClientCredintials(ChatInterface ci,String name, String pass) throws RemoteException;
    void broadcastMessage(String name,String message) throws RemoteException;
    void sendMessageToClient(String message) throws RemoteException;
}


Server.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.net.MalformedURLException;
import java.util.ArrayList;

public class Server extends UnicastRemoteObject implements ChatInterface {
    private static final long serialVersionUID = 1L;
    private String clientName [] = {"Nifal","Dinesh","Asjad","Clarry","Tahar"};
    private String clientPass [] = {"12345","123456","12345","123456","12345"};
    private ArrayList<ChatInterface> clientList;
 
    protected Server() throws RemoteException {
        clientList = new ArrayList<ChatInterface>();
    }

    public synchronized boolean checkClientCredintials(ChatInterface chatinterface,String clientname,String password) throws RemoteException {
        boolean chkLog = false;  
        for(int i=0; i<clientName.length; i++) {
            if(clientName[i].equals(clientname) && clientPass[i].equals(password)) {
                chkLog = true;
                this.clientList.add(chatinterface);
            }
        }
        return chkLog;
    }
 
    public synchronized void broadcastMessage(String clientname , String message) throws RemoteException {
        for(int i=0; i<clientList.size(); i++) {
            clientList.get(i).sendMessageToClient(clientname.toUpperCase() + " : "+ message);
        }
    }
 
    public synchronized void sendMessageToClient(String message) throws RemoteException{}

    public static void main(String[] arg) throws RemoteException, MalformedURLException {
        Naming.rebind("RMIServer", new Server());
    }
 
}


Client.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.net.MalformedURLException;
import java.util.Scanner;

public class Client extends UnicastRemoteObject implements ChatInterface , Runnable {
    private static final long serialVersionUID = 1L;
    private ChatInterface server;
    private String ClientName;
    boolean chkExit = true;
    boolean chkLog = false;
 
    protected Client(ChatInterface chatinterface,String clientname,String password) throws RemoteException {
        this.server = chatinterface;
        this.ClientName = clientname;
        chkLog = server.checkClientCredintials(this,clientname,password);
    }

    public void sendMessageToClient(String message) throws RemoteException {
        System.out.println(message); 
    }
 
    public void broadcastMessage(String clientname,String message) throws RemoteException {}
 
    public boolean checkClientCredintials(ChatInterface chatinterface ,String clientname,String password) throws RemoteException {
        return true;
    }

    public void run() {
        if(chkLog) {
            System.out.println("Successfully Connected To RMI Server");
            System.out.println("NOTE : Type LOGOUT to Exit From The Service");
            System.out.println("Now Your Online To Chat\n");
            Scanner scanner = new Scanner(System.in);
            String message;
            
            while(chkExit) {
                message = scanner.nextLine();
                if(message.equals("LOGOUT")) {
                    chkExit = false;
                }
                else {
                    try {
                        server.broadcastMessage(ClientName , message);
                    }
                    catch(RemoteException e) {
                        e.printStackTrace();
                    }
                }  
            } 
            System.out.println("\nSuccessfully Logout From The RMI Chat Program\nThank You For Using...\nDeveloped By Nifal Nizar");
        }
        else {
            System.out.println("\nClient Name or Password Incorrect...");
        }  
    }
    public static void main(String[] args) throws MalformedURLException,RemoteException,NotBoundException {
        Scanner scanner = new Scanner(System.in);
        String clientName = "";
        String clientPassword = "";
  
        System.out.println("\n~~ Welcome To RMI Chat Program ~~\n");  
        System.out.print("Enter The Name : ");
        clientName = scanner.nextLine();
        System.out.print("Enter The Password : ");
        clientPassword = scanner.nextLine();
        System.out.println("\nConnecting To RMI Server...\n");

        ChatInterface chatinterface = (ChatInterface)Naming.lookup("rmi://localhost/RMIServer");
        new Thread(new Client(chatinterface , clientName , clientPassword)).start();
    }
 
}


Create A Folder and Copy All These Codes. Then To Run This Program, Follow The Following Steps To Run The Program.

Step 01:
Open Command Prompt and Go To File Directory In The Command Prompt. Compile All The Java Files, Create Remote Classes and Run The Registry Using Following Command.
javac *.java
rmic Server
rmic Client
rmiregistry

Step 02:
Open Another Command Prompt and Start The Server Using Following Command.
java Server

Step 03:
Open Another Command Prompt and Start A Client Using Following Command.
java Client

Step 04:
Open Another Command Prompt and Start Another Client Using Following Command.
java Client

Step 05:
Enter A Client Name and Password As Per The Server and Start Chatting.


Rather Than Running Thorough Typing Commands In The Command Prompt, Create Following Batch Files To Run It Easily.

1. Build.bat
javac *.java
rmic Server
rmic Client
rmiregistry

2. Start Server.bat
java Server

3. Start Client One
java Client

4. Start Client Two
java Client


Create Clients AS You Want and Start Chatting Using JAVA RMI CHAT PROGRAM.

Oct 20, 2014

Poker 5 Card Draw Hand Ranking using Java

These are the poker ranking as per priority.

1. Royal Flush
2. Straight Flush
3. Four Of A Kind 
4. Full House
5. Flush
6. Straight
7. Three Of A Kind
8. Two Pair
9. One Pair
10. High Card

Following java class "PokerRanking " will calculate the poker ranking.
First of all you to use this create a object of PokerRanking  class.
Then assign player hands cards array to this PokerRanking object using the method "setHand(ArrayList<Card> card)".
After assigning of the player card array it will calculate the Poker Ranking.
To get the rank call the method "getPriority()".This will return a value from 1 to 10.
Sometime you will find two or more players with the same rank. For example one pair. 
Then you need to find the best rank get the rank card using method "getRankCard()".
Even its still same you have to find the next High Card of the hand.In order to do that call the method "getHighCard()".


class PokerRanking {
   private int priority, rankcard , highCard, suit;
   private ArrayList<Card> HandCards;
   private boolean chk = true;

   public PokerRanking() {

   }

public void setHand(ArrayList<Card> card) {

this.HandCards = card;
sortHandCards();
      getRank();
   }

public int getPriority() {

return priority;
}
        
public int getRankCard() {
return rankcard;
}

public int getHighCard() {

return highCard;
}

public int getSuit() {
return suit;
}

public void sortHandCards() {            

      //Copying The Hand Cards To Unsorted Card Array AND Removing All The Cards From Hand
      ArrayList<Card> unsortCards = new ArrayList<Card>();
      for (Card c : this.HandCards) {
         unsortCards.add(c); 
      }
      this.HandCards = new ArrayList<Card>();
            
      //Sorting The Card Values
      int[] arr = new int[5];
      for(int i=0;i<5;i++){
         arr[i] = unsortCards.get(i).getCardValue();
      }
      Arrays.sort(arr);

      //Copying The Sorted Cards To The Hand

      Card x = new Card();
      for(int a : arr){
         for (Card c : unsortCards) {
if(a == c.getCardValue()){
x = c;
break;
}
         }
         this.HandCards.add(x);
         unsortCards.remove(x);
      }

      /**

      //Available In jdk 1.7
      Collections.sort(this.HandCards, new Comparator<Card>() {
         @Override
         public int compare(Card c1, Card c2) {
return Integer.compare(c1.getCardValue(), c2.getCardValue());
         }
      });**/           
      highCard = HandCards.get(4).getCardValue();
      rankcard = 53;
   }

   private void getRank() {
      int i = 0;
      for (Card c : HandCards) {
         if (i == 0) {
suit = c.getCardType();
         }else if (suit == c.getCardType()) {
continue;
         }else {
suit = 0;
break;
         }
         i++;
      }  
      
      //Same Suit   
      if (suit != 0) {
         if (chk) { checkRoyalFlush();
         }if (chk) { checkStraightFlush();
         }if (chk) { checkFlush();
      }
      //Not Same Suit
      } else {
         if (chk) { checkFourOfAKind();
         }if (chk) { checkFullHouse();
         }if (chk) { checkStraight();
         }if (chk) { checkThreeOfAKind();
         }if (chk) { checkTwoPair();
         }if (chk) { checkOnePair();
         }if (chk) { HighCard();
         }
      }
   }

public void checkRoyalFlush() {

      if (HandCards.get(0).getCardValue() == 10 && 
HandCards.get(1).getCardValue() == 11 && 
HandCards.get(2).getCardValue() == 12 && 
HandCards.get(3).getCardValue() == 13 && 
HandCards.get(4).getCardValue() == 14) {
priority = 1;
chk = false;
      }
  }

public void checkStraightFlush() {

        //Checking For Straight Flush with A in 1st
        if ((HandCards.get(0).getCardValue() + 3) == HandCards.get(3).getCardValue() &&
HandCards.get(4).getCardValue() == 14 && 
HandCards.get(0).getCardValue() == 2) {
priority = 2;
rankcard = HandCards.get(4).getCardValue();
chk = false;
        }
//Checking Straight Flush For Other values
        else if ((HandCards.get(0).getCardValue() + 4) == HandCards.get(4).getCardValue()) {
priority = 2;
rankcard = HandCards.get(4).getCardValue();
chk = false;
        }
}

public void checkFourOfAKind() {

        if (HandCards.get(0).getCardValue() == HandCards.get(1).getCardValue() && 
HandCards.get(1).getCardValue() == HandCards.get(2).getCardValue() && 
HandCards.get(2).getCardValue() == HandCards.get(3).getCardValue() || 
HandCards.get(1).getCardValue() == HandCards.get(2).getCardValue() && 
HandCards.get(2).getCardValue() == HandCards.get(3).getCardValue() && 
HandCards.get(3).getCardValue() == HandCards.get(4).getCardValue()) {
priority = 3;
                rankcard = HandCards.get(2).getCardValue();
                chk = false;
        }
}

public void checkFullHouse() {

        if (HandCards.get(0).getCardValue() == HandCards.get(1).getCardValue() && 
HandCards.get(1).getCardValue() == HandCards.get(2).getCardValue() && 
HandCards.get(3).getCardValue() == HandCards.get(4).getCardValue() || 
HandCards.get(0).getCardValue() == HandCards.get(1).getCardValue() && 
HandCards.get(2).getCardValue() == HandCards.get(3).getCardValue() && 
HandCards.get(3).getCardValue() == HandCards.get(4).getCardValue()) {
                priority = 4;
                rankcard = HandCards.get(2).getCardValue();
                chk = false;
        }
}

public void checkFlush() {

        priority = 5;
        rankcard = HandCards.get(4).getCardValue();
highCard = HandCards.get(3).getCardValue();
        chk = false;
}

public void checkStraight() {

        if ((HandCards.get(0).getCardValue() + 1) == HandCards.get(1).getCardValue() && 
(HandCards.get(1).getCardValue() + 1) == HandCards.get(2).getCardValue() && 
(HandCards.get(2).getCardValue() + 1) == HandCards.get(3).getCardValue() && 
(HandCards.get(3).getCardValue() + 1) == HandCards.get(4).getCardValue() || 
HandCards.get(4).getCardValue() == 14 && 
HandCards.get(0).getCardValue() == 2 && 
(HandCards.get(0).getCardValue() + 1) == HandCards.get(1).getCardValue() && 
(HandCards.get(1).getCardValue() + 1) == HandCards.get(2).getCardValue() && 
(HandCards.get(2).getCardValue() + 1) == HandCards.get(3).getCardValue()) {
                priority = 6;
                rankcard = HandCards.get(4).getCardValue();
                chk = false;
        }
}

public void checkThreeOfAKind() {

        if (HandCards.get(0).getCardValue() == HandCards.get(1).getCardValue() && 
HandCards.get(1).getCardValue() == HandCards.get(2).getCardValue() || 
HandCards.get(1).getCardValue() == HandCards.get(2).getCardValue() && 
HandCards.get(2).getCardValue() == HandCards.get(3).getCardValue() || 
HandCards.get(2).getCardValue() == HandCards.get(3).getCardValue() && 
HandCards.get(3).getCardValue() == HandCards.get(4).getCardValue()) {
                priority = 7;
                rankcard = HandCards.get(2).getCardValue();
                chk = false;
        }
}

public void checkTwoPair() {

        if (HandCards.get(0).getCardValue() == HandCards.get(1).getCardValue() && 
HandCards.get(2).getCardValue() == HandCards.get(3).getCardValue() || 
HandCards.get(1).getCardValue() == HandCards.get(2).getCardValue() && 
HandCards.get(3).getCardValue() == HandCards.get(4).getCardValue() || 
HandCards.get(0).getCardValue() == HandCards.get(1).getCardValue() && 
HandCards.get(3).getCardValue() == HandCards.get(4).getCardValue()) {
                priority = 8;
                rankcard = HandCards.get(3).getCardValue();
                highCard = HandCards.get(1).getCardValue();
                chk = false;
        }
}

public void checkOnePair() {

        if (HandCards.get(0).getCardValue() == HandCards.get(1).getCardValue()) {
            priority = 9;
            rankcard = HandCards.get(1).getCardValue();
            chk = false;
        }
        if (HandCards.get(1).getCardValue() == HandCards.get(2).getCardValue()) {
            priority = 9;
            rankcard = HandCards.get(1).getCardValue();
            chk = false;
        }
        if (HandCards.get(2).getCardValue() == HandCards.get(3).getCardValue()) {
            priority = 9;
            rankcard = HandCards.get(2).getCardValue();
            chk = false;
        }
        if (HandCards.get(3).getCardValue() == HandCards.get(4).getCardValue()) {
            priority = 9;
            rankcard = HandCards.get(4).getCardValue();
            highCard = HandCards.get(2).getCardValue();
            chk = false;
        }
}

public void HighCard() {

        priority = 10;
        rankcard = HandCards.get(4).getCardValue();
        highCard = HandCards.get(3).getCardValue();
        chk = false;
}


}

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...