Sunday, 27 January 2013

What is Java?

Java is a technology which consists of Java Programming Language, Java Development Environment, Java Application Environment and Java Deployment Environment.  Java Programming Language is platform independent. It means that it can run on any platform (any operating system, any hardware) and can be used to develop any type of application like web applications, server applications and desktop applications. The syntax of Java Programming Language is similar to that of C++ programming language.


Code for simple program in C++
#include <iostream>
using namespace std;
int main() {
std::cout << “Welcome to the wonderful world of C++!!!\n”;
return 0;
}
Code for simple program in Java
class Apple
{
public static void main(String []a)
{
System.out.println(“Welcome to the wonderful world of java programming”);
}
}
As illustrated above, both the programs in C++ and Java have a main function which is the entry point. C++ uses cout function for printing a statement while Java uses println function for printing a statement.  The rest of the syntax of the Java code will be explained in further posts.
Main Objectives of Java Technology
- Enables users to develop the code easily.
- Java code can be developed and run on any platform that is a certified Java Virtual Machine.
- Increases development speed
- Ability to run more than one block of code at the same time.
- JVM provides high level of security.
The java technology architecture has the following components for achieving its objectives –
- The JVM
- Garbage collection
- The JRE
- JVM tool interface
The java virtual machine Java virtual machine is an imaginary machine that is executed by emulating it in a software or real machine. Code for the JVM resides in .class file that contain code for at most one public class.

Client-Server Chat Application

Server  Side Application

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Server {
public static void main(String []a1){
Chat c=new Chat();

}

}
class Chat{
JFrame frame;
Panel login_panel,message_panel,chat_panel;
Label lUserName,lPassword,lmessage;
TextField tUserName,message;
JTextArea chatWindow;
JPasswordField tPassword;
Button login, cancel,send;

ServerSocket ss;
    Socket s1;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    BufferedReader br;
    BufferedWriter bw;
    PrintWriter pw;
    String input,username="SERVER";
 
MenuBar menubar;
Menu history,available;
MenuItem exit,logout,conversation;

    public Chat(){
frame = new JFrame("Login");
login_panel = new Panel();
lUserName = new Label("User Name");
tUserName = new TextField(15);
lPassword = new Label("Password");
tPassword = new JPasswordField(15);
login = new Button("Login");
login.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String in,password="";
username=(String)tUserName.getText();
try{
br=new BufferedReader(new FileReader("Login.txt"));
for(char i:tPassword.getPassword())
password+=i;
while((in=br.readLine())!=null){
String []s=in.split("~");
if(s[0].equals(username)&&s[1].equals(password)){
frame.remove(lmessage);
login_panel.setVisible(false);
frame.add(chat_panel);
chat_panel.setSize(200, 300);
frame.setSize(300,300);
frame.setMenuBar(menubar);
chat_panel.setVisible(true);
frame.setTitle(username);
break;
}else{
lmessage.setText("Username and Password is worng !");
}
}
}catch(IOException exception){
exception.printStackTrace();
}
}
}
);
cancel = new Button("Cancel");
cancel.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
tUserName.setText("");
tPassword.setText("");
}
}
);
lmessage=new Label();
login_panel.add(lUserName);
login_panel.add(tUserName);
login_panel.add(lPassword);
login_panel.add(tPassword);
login_panel.add(login);
login_panel.add(cancel);
frame.add(lmessage,BorderLayout.SOUTH);
frame.add(login_panel);

menubar=new MenuBar();

history=new Menu("History");
conversation=new MenuItem("conversation");
history.add(conversation);
conversation.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
br=new BufferedReader(new FileReader("conversation.txt"));
String s;
while((s=br.readLine())!=null){
chatWindow.append(s+"\n");
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
);

available=new Menu("Available");
logout=new MenuItem("Logout");
logout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(chat_panel);
tUserName.setText("");
tPassword.setText("");
                                        frame.remove(menubar);
login_panel.setVisible(true);
frame.add(login_panel);
frame.setSize(215, 250);
}
}
);

exit=new MenuItem("Exit");
exit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
);

available.add(logout);
available.add(exit);

menubar.add(history);
menubar.add(available);

message_panel=new Panel();
chatWindow=new JTextArea(10,20);

message=new TextField(20);
message.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
message.setText("");
}
}
);

send=new Button("send");
send.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg=message.getText();
sendMessage(msg);
message.setText("");
}
}
);

message_panel.add(message);
message_panel.add(send);
chat_panel=new Panel();
chat_panel.add(new JScrollPane(chatWindow));
chat_panel.add(message_panel);
login_panel.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 215, 250);
frame.setVisible(true);
startChatting();
}
 
public void startChatting(){
     try{
         ss = new ServerSocket(1234);
         while(true){
            try{
                showMessage("\n Waiting for someone to connect... \n");
                s1 = ss.accept();
                showMessage(" Now connected to " + s1.getInetAddress().getHostName());
   
                //pw=new PrintWriter(new FileWriter("conversation.txt"));
                //pw.flush();
             
                bw=new BufferedWriter(new FileWriter("conversation.txt"));
                bw.flush();
             
                oos = new ObjectOutputStream(s1.getOutputStream());
                oos.flush();
                ois = new ObjectInputStream(s1.getInputStream());

                String message = " You are now connected! ";
                sendMessage(message);
                do{
                   try{
                      message = (String) ois.readObject();
                      showMessage("\n" + message);
                      saveMessage("\n" + message);
                   }catch(ClassNotFoundException classNotFoundException){
                      showMessage("\n there is some problem in message ");
                   }
                }while(!message.equals("CLIENT - END"));
             
            }catch(Exception exception){
               showMessage("\n Server ended the connection! ");
            }finally{
            ois.close();
            oos.close();
            //pw.close();
            br.close();
            s1.close();
            }
         }
      }catch(IOException ioException){
         ioException.printStackTrace();
      }finally{
      try {
ois.close();
oos.close();
      } catch (IOException e) {
e.printStackTrace();
      }
      }
}

private void sendMessage(String msg){
try {
oos.writeObject(username+" : "+msg);
oos.flush();
showMessage("\n"+username+" : "+msg);
saveMessage("\n"+username+" : " + msg);
} catch (IOException e) {
e.printStackTrace();
}
}

private void showMessage(final String msg){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(msg);
}
}
);
}
private void saveMessage(String message){
try {
            bw.append(message+"\n");
            bw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}

save file as Server.java


Client Side Application

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import java.net.Socket;

import javax.swing.*;

public class Client {

    public static void main(String[] args) {
        Chat c=new Chat();
    }
}
class Chat{

    JFrame frame;
    Panel login_panel,message_panel,chat_panel;
    Label lUserName,lPassword,lmessage;
    TextField tUserName,message;
    JTextArea chatWindow;
    JPasswordField tPassword;
    Button login, cancel,send;

    Socket s1;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    BufferedReader br;
    BufferedWriter bw;
    PrintWriter pw;
    String input,username="CLIENT";
 
    MenuBar menubar;
    Menu history,available;
    MenuItem conversation,logout,exit;
    public Chat(){
        frame = new JFrame("Login");
        login_panel = new Panel();
        lUserName = new Label("User Name");
        tUserName = new TextField(15);
        lPassword = new Label("Password");
        tPassword = new JPasswordField(15);
        lmessage = new Label();
        login = new Button("Login");
        login.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    String in,password="";
                    username=(String)tUserName.getText();
                    try{
                        br=new BufferedReader(new FileReader("Login.txt"));
                        for(char i:tPassword.getPassword()) {
                            password+=i;
                        }
                        while((in=br.readLine())!=null){
                            String []s=in.split("~");
                            if(s[0].equals(username)&&s[1].equals(password)){
                                frame.remove(lmessage);
                                login_panel.setVisible(false);
                                frame.add(chat_panel);
                                chat_panel.setSize(200, 300);
                                frame.setSize(300,300);
                                frame.setMenuBar(menubar);
                                chat_panel.setVisible(true);
                                frame.setTitle(username);
                                break;
                            }else{
                                lmessage.setText("Username and Password is worng !");
                            }
                        }
                    }catch(IOException exception){
                        exception.printStackTrace();
                    }
                }
            }
        );
     
        cancel = new Button("Cancel");
        cancel.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    tUserName.setText("");
                    tPassword.setText("");
                }
            }
        );
        login_panel.add(lUserName);
        login_panel.add(tUserName);
        login_panel.add(lPassword);
        login_panel.add(tPassword);
        login_panel.add(login);
        login_panel.add(cancel);
        frame.add(lmessage,BorderLayout.SOUTH);
        frame.add(login_panel);

        message_panel=new Panel();
        chatWindow=new JTextArea(10,20);

        message=new TextField(20);
        message.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    sendMessage(e.getActionCommand());
                    message.setText("");
                }
            }
        );

        send=new Button("send");
        send.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String msg=message.getText();
                    sendMessage(msg);
                    message.setText("");
                }
            }
        );
        menubar=new MenuBar();

        history=new Menu("History");
        conversation=new MenuItem("conversation");
        history.add(conversation);
        conversation.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        br=new BufferedReader(new FileReader("conversation.txt"));
                        String s;
                        while((s=br.readLine())!=null){
                        chatWindow.append(s+"\n");
                    }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }
        );
     
        available=new Menu("Available");
        logout=new MenuItem("Logout");
        logout.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    frame.remove(chat_panel);
                    tUserName.setText("");
                    tPassword.setText("");
                    frame.remove(menubar);
                    login_panel.setVisible(true);
                    frame.add(login_panel);
                    frame.setSize(215, 250);
                }
            }
        );

        exit=new MenuItem("exit");
        exit.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            }
        );
             
        available.add(logout);
        available.add(exit);
        menubar.add(history);
        menubar.add(available);

        message_panel.add(message);
        message_panel.add(send);
        chat_panel=new Panel();
        chat_panel.add(new JScrollPane(chatWindow));
        chat_panel.add(message_panel);
        login_panel.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 215, 250);
        frame.setVisible(true);
        startChatting();
    }
 
    public void startChatting(){
        try{
            String host=JOptionPane.showInputDialog("IP address");
            showMessage("Attempting connection... \n");
            s1 = new Socket(host, 1234);
            showMessage("Connected to: " + s1.getInetAddress().getHostName());
         
            bw=new BufferedWriter(new FileWriter("conversation.txt"));
            bw.flush();
         
            oos = new ObjectOutputStream(s1.getOutputStream());
            oos.flush();
            ois = new ObjectInputStream(s1.getInputStream());

            do{
                try{
                    input = (String) ois.readObject();
                    showMessage("\n" + input);
                    saveMessage("\n" + input);
                }catch(ClassNotFoundException classNotfoundException){
                    showMessage("\n there is some problem in message ");
                }
            }while(!message.equals("SERVER - END"));

        }catch(Exception e){
            showMessage("\n Client ended the connection! ");
        }finally{
         
        }
    }
 
    private void sendMessage(String msg){
        try {
            oos.writeObject(username+" : "+msg);
            oos.flush();
            showMessage("\n"+username+" : " + msg);
            saveMessage("\n"+username+" : " + msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showMessage(final String msg){
        SwingUtilities.invokeLater(
            new Runnable(){
                public void run(){
                    chatWindow.append(msg);
                }
            }
        );
    }
    private void saveMessage(String message){
        try {
            bw.append(message+"\n");
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

save file as Client.java


Create log in text file for user

(username)~(password)

ayyaz~shamshad
imran~riyaz
obid~sawood


save this file both Server.java and Client.java directory as Login.txt

You have to run Server.java first then Client.java